diff --git a/.zcode-plugin/plugin.json b/.zcode-plugin/plugin.json index 6e9035e..ebd7c03 100644 --- a/.zcode-plugin/plugin.json +++ b/.zcode-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "seal-home", - "version": "0.6.0", + "version": "0.7.0", "description": "Seal Home tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.", "author": { "name": "yingqing" diff --git a/dist/mcp/server.js b/dist/mcp/server.js index ae71c72..9223fd5 100644 --- a/dist/mcp/server.js +++ b/dist/mcp/server.js @@ -1,3 +1,4 @@ +import { createRequire } from "node:module"; var __create = Object.create; var __getProtoOf = Object.getPrototypeOf; var __defProp = Object.defineProperty; @@ -42,6 +43,7 @@ var __export = (target, all) => { set: __exportSetter.bind(all, name) }); }; +var __require = /* @__PURE__ */ createRequire(import.meta.url); // node_modules/ajv/dist/compile/codegen/code.js var require_code = __commonJS((exports) => { @@ -6603,7 +6605,7 @@ var require_dist = __commonJS((exports, module) => { }); // src/server.ts -import { dirname as dirname4, resolve } from "node:path"; +import { dirname as dirname6, resolve } from "node:path"; import { fileURLToPath as fileURLToPath2 } from "node:url"; // node_modules/zod/v4/core/index.js @@ -23230,238 +23232,9 @@ class StdioServerTransport { } // src/cli/runner.ts -import { spawnSync } from "node:child_process"; -import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "node:fs"; -import { homedir as homedir3 } from "node:os"; -import { dirname as dirname3, join as join4 } from "node:path"; +import { dirname as dirname5, join as join9 } from "node:path"; import { fileURLToPath } from "node:url"; -// src/core/config/loader.ts -import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; -import { dirname, join } from "node:path"; -// src/core/config/types.ts -var HoseSealSourceSchema = exports_external.object({ - type: exports_external.literal("hose"), - domain: exports_external.string().url().default("https://app.ekuaibao.com"), - appKey: exports_external.string().optional(), - appSecurity: exports_external.string().optional(), - key: exports_external.string().optional(), - password: exports_external.string().optional(), - staffId: exports_external.string(), - corpId: exports_external.string(), - sealUrl: exports_external.string().url().optional() -}).superRefine((source, ctx) => { - if (!source.appKey && !source.key) { - ctx.addIssue({ - code: "custom", - path: ["appKey"], - message: "Hose source requires appKey or key" - }); - } - if (!source.appSecurity && !source.password) { - ctx.addIssue({ - code: "custom", - path: ["appSecurity"], - message: "Hose source requires appSecurity or password" - }); - } -}); -var DirectSealSourceSchema = exports_external.object({ - type: exports_external.literal("direct"), - token: exports_external.string(), - sealUrl: exports_external.string().url(), - expiresIn: exports_external.number().int().positive().default(3600), - staffId: exports_external.string().default("direct"), - corpId: exports_external.string().optional() -}); -var NativeSealSourceSchema = exports_external.object({ - type: exports_external.literal("seal"), - token: exports_external.string(), - sealUrl: exports_external.string().url(), - expiresIn: exports_external.number().int().positive().default(3600), - staffId: exports_external.string().default("seal"), - corpId: exports_external.string().optional(), - tenantId: exports_external.string().optional(), - tenantSlug: exports_external.string().optional(), - tenantName: exports_external.string().optional(), - providerUserId: exports_external.string().optional(), - provider: exports_external.string().optional(), - providerName: exports_external.string().optional() -}); -var SealSourceSchema = exports_external.discriminatedUnion("type", [ - HoseSealSourceSchema, - DirectSealSourceSchema, - NativeSealSourceSchema -]); -var SealEndpointSchema = exports_external.object({ - url: exports_external.string().url().optional(), - tenantSlug: exports_external.string().optional(), - endpoints: exports_external.object({ - approvalStylePreferences: exports_external.string().default("api/v1/agent/ai-approval/config") - }).default({ - approvalStylePreferences: "api/v1/agent/ai-approval/config" - }) -}).default({ - endpoints: { - approvalStylePreferences: "api/v1/agent/ai-approval/config" - } -}); -var CorpAuthConfigSchema = exports_external.object({ - refreshTtl: exports_external.number().int().positive().default(300) -}).default({ refreshTtl: 300 }); -var CorpConfigSchema = exports_external.object({ - id: exports_external.string(), - name: exports_external.string(), - seal: SealEndpointSchema, - source: SealSourceSchema, - auth: CorpAuthConfigSchema -}); -var GlobalConfigSchema = exports_external.object({ - stateful: exports_external.boolean().default(false), - defaultCorpId: exports_external.string().min(1).optional() -}); - -// src/core/config/loader.ts -var ENTERPRISES_DIR = "enterprises"; -var CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR"; -var USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR"; -var GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE"; -var GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json"); -var USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises"); -function loadCorpConfigs() { - const dirs = resolveEnterprisesDirs(); - const byId = new Map; - for (const dir of dirs) { - for (const file2 of readdirSync(dir).filter((item) => item.endsWith(".json")).filter((item) => !item.startsWith("example."))) { - const content = readFileSync(join(dir, file2), "utf-8"); - const corp = CorpConfigSchema.parse(JSON.parse(content)); - byId.set(corp.id, corp); - } - } - return Array.from(byId.values()); -} -function resolveEnterprisesDirs() { - const configured = process.env[CONFIG_ENV]?.trim(); - if (configured) - return existsSync(configured) ? [configured] : []; - const userDir = process.env[USER_DIR_ENV]?.trim() || USER_ENTERPRISES_DIR; - return [ENTERPRISES_DIR, userDir].filter((dir) => existsSync(dir)); -} -function resolveWritableEnterprisesDir() { - return process.env[CONFIG_ENV]?.trim() || USER_ENTERPRISES_DIR; -} -function getEnterprisesDirCandidates() { - return [ - `${CONFIG_ENV}=`, - ENTERPRISES_DIR, - USER_ENTERPRISES_DIR - ]; -} -function resolveGlobalConfigFile() { - return process.env[GLOBAL_CONFIG_ENV]?.trim() || GLOBAL_CONFIG_FILE; -} -function loadGlobalConfig() { - const file2 = resolveGlobalConfigFile(); - if (!existsSync(file2)) { - return GlobalConfigSchema.parse({}); - } - return GlobalConfigSchema.parse(JSON.parse(readFileSync(file2, "utf-8"))); -} -function saveGlobalConfig(config2) { - const normalized = GlobalConfigSchema.parse(config2); - const file2 = resolveGlobalConfigFile(); - mkdirSync(dirname(file2), { recursive: true, mode: 448 }); - writeFileSync(file2, `${JSON.stringify(normalized, null, 2)} -`, { mode: 384 }); - return normalized; -} - -// src/core/config/manager.ts -function resolveCorpConfig(corps, options, candidates = []) { - const requestedCorpId = options.corpId?.trim() || undefined; - const configuredCorpId = options.stateful ? options.defaultCorpId?.trim() || undefined : undefined; - const selectedCorpId = requestedCorpId ?? configuredCorpId; - if (selectedCorpId) { - const corp = corps.find((item) => item.id === selectedCorpId); - if (corp) - return corp; - throw new Error(`No enterprise config found for ${selectedCorpId}`); - } - if (!options.stateful) { - throw new Error("Stateless mode is enabled. Every enterprise command requires --corp . " + "Use `seal-home config mode stateful` to enable a default enterprise."); - } - const firstCorp = corps[0]; - if (firstCorp) - return firstCorp; - throw new Error("No enterprise config found. Add a non-example JSON file under one of: " + (candidates.length ? candidates.join(", ") : "the configured enterprise directories")); -} - -class CorpContext { - current = null; - corps = new Map; - stateful = false; - defaultCorpId; - constructor(corps, options = { stateful: false }) { - this.stateful = options.stateful; - this.defaultCorpId = options.defaultCorpId; - this.replaceCorps(corps); - this.selectCurrent(corps[0]); - } - refresh(corps, options = { - stateful: this.stateful, - defaultCorpId: this.defaultCorpId - }) { - const currentId = this.current?.id; - this.stateful = options.stateful; - this.defaultCorpId = options.defaultCorpId; - this.replaceCorps(corps); - this.selectCurrent(currentId ? this.corps.get(currentId) ?? corps[0] : corps[0]); - } - replaceCorps(corps) { - this.corps = new Map; - for (const corp of corps) { - this.corps.set(corp.id, corp); - } - } - getCurrent() { - return this.current; - } - getCorp(corpId) { - return this.corps.get(corpId) ?? null; - } - resolve(corpId) { - if (corpId) - return this.getCorp(corpId); - return this.current; - } - switchCorp(corpId) { - if (!this.stateful) - return false; - const corp = this.corps.get(corpId); - if (!corp) - return false; - this.current = corp; - this.defaultCorpId = corp.id; - return true; - } - listCorps() { - return Array.from(this.corps.values()).map((corp) => ({ - id: corp.id, - name: corp.name, - sourceType: corp.source.type, - current: corp.id === this.current?.id - })); - } - selectCurrent(fallback) { - if (!this.stateful) { - this.current = null; - return; - } - this.current = this.defaultCorpId !== undefined ? this.corps.get(this.defaultCorpId) ?? null : fallback ?? null; - } -} - // node_modules/ky/distribution/errors/KyError.js class KyError extends Error { name = "KyError"; @@ -24800,10 +24573,9 @@ async function getDirectSealSession(corp) { } // src/core/auth/token-store.ts -import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs"; -import { dirname as dirname2, join as join2 } from "node:path"; -import { homedir as homedir2 } from "node:os"; - +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { homedir } from "node:os"; // src/core/auth/types.ts var TokenEntrySchema = exports_external.object({ token: exports_external.string(), @@ -24837,23 +24609,23 @@ var TokenStoreSchema = exports_external.record(exports_external.string(), CorpTo // src/core/auth/token-store.ts function storePath() { - return process.env.SEAL_HOME_TOKEN_STORE ?? join2(homedir2(), ".config", "seal-home", "seal_tokens.json"); + return process.env.SEAL_HOME_TOKEN_STORE ?? join(homedir(), ".config", "seal-home", "seal_tokens.json"); } function readStore() { const path = storePath(); - if (!existsSync2(path)) { + if (!existsSync(path)) { return {}; } try { - return TokenStoreSchema.parse(JSON.parse(readFileSync2(path, "utf-8"))); + return TokenStoreSchema.parse(JSON.parse(readFileSync(path, "utf-8"))); } catch { return {}; } } function writeStore(store) { const path = storePath(); - mkdirSync2(dirname2(path), { recursive: true }); - writeFileSync2(path, JSON.stringify(store, null, 2)); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, JSON.stringify(store, null, 2)); } function getSealSession(corpId) { return readStore()[corpId]?.seal; @@ -25168,6 +24940,271 @@ async function createSealClientForToken(corp, token) { } }); } +// package.json +var package_default = { + name: "seal-home", + version: "0.7.0", + type: "module", + module: "src/server.ts", + bin: { + "seal-home": "src/cli.ts" + }, + scripts: { + dev: "bun run --watch src/server.ts", + start: "bun run src/server.ts", + probe: "bun run src/probe.ts", + cli: "bun run src/cli.ts", + check: "tsc --noEmit", + "build:binary": "node scripts/build-binary.mjs", + "build:plugin": "node scripts/build-plugin.mjs", + "openapi:bundle": "bun run scripts/bundle-openapi.ts", + test: "bun test" + }, + dependencies: { + "@modelcontextprotocol/sdk": "^1.29.0", + ky: "^2.0.2", + zod: "^4.4.3" + }, + devDependencies: { + "@types/bun": "^1.3.14", + "bun-types": "^1.3.14", + typescript: "^5.9.3", + yaml: "^2.9.0" + } +}; + +// src/version.ts +var VERSION = package_default.version; + +// src/core/config/loader.ts +import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, readdirSync, writeFileSync as writeFileSync2 } from "node:fs"; +import { homedir as homedir2 } from "node:os"; +import { dirname as dirname2, join as join2 } from "node:path"; + +// src/core/config/types.ts +var HoseSealSourceSchema = exports_external.object({ + type: exports_external.literal("hose"), + domain: exports_external.string().url().default("https://app.ekuaibao.com"), + appKey: exports_external.string().optional(), + appSecurity: exports_external.string().optional(), + key: exports_external.string().optional(), + password: exports_external.string().optional(), + staffId: exports_external.string(), + corpId: exports_external.string(), + sealUrl: exports_external.string().url().optional() +}).superRefine((source, ctx) => { + if (!source.appKey && !source.key) { + ctx.addIssue({ + code: "custom", + path: ["appKey"], + message: "Hose source requires appKey or key" + }); + } + if (!source.appSecurity && !source.password) { + ctx.addIssue({ + code: "custom", + path: ["appSecurity"], + message: "Hose source requires appSecurity or password" + }); + } +}); +var DirectSealSourceSchema = exports_external.object({ + type: exports_external.literal("direct"), + token: exports_external.string(), + sealUrl: exports_external.string().url(), + expiresIn: exports_external.number().int().positive().default(3600), + staffId: exports_external.string().default("direct"), + corpId: exports_external.string().optional() +}); +var NativeSealSourceSchema = exports_external.object({ + type: exports_external.literal("seal"), + token: exports_external.string(), + sealUrl: exports_external.string().url(), + expiresIn: exports_external.number().int().positive().default(3600), + staffId: exports_external.string().default("seal"), + corpId: exports_external.string().optional(), + tenantId: exports_external.string().optional(), + tenantSlug: exports_external.string().optional(), + tenantName: exports_external.string().optional(), + providerUserId: exports_external.string().optional(), + provider: exports_external.string().optional(), + providerName: exports_external.string().optional() +}); +var SealSourceSchema = exports_external.discriminatedUnion("type", [ + HoseSealSourceSchema, + DirectSealSourceSchema, + NativeSealSourceSchema +]); +var SealEndpointSchema = exports_external.object({ + url: exports_external.string().url().optional(), + tenantSlug: exports_external.string().optional(), + endpoints: exports_external.object({ + approvalStylePreferences: exports_external.string().default("api/v1/agent/ai-approval/config") + }).default({ + approvalStylePreferences: "api/v1/agent/ai-approval/config" + }) +}).default({ + endpoints: { + approvalStylePreferences: "api/v1/agent/ai-approval/config" + } +}); +var CorpAuthConfigSchema = exports_external.object({ + refreshTtl: exports_external.number().int().positive().default(300) +}).default({ refreshTtl: 300 }); +var CorpConfigSchema = exports_external.object({ + id: exports_external.string(), + name: exports_external.string(), + seal: SealEndpointSchema, + source: SealSourceSchema, + auth: CorpAuthConfigSchema +}); +var GlobalConfigSchema = exports_external.object({ + stateful: exports_external.boolean().default(false), + defaultCorpId: exports_external.string().min(1).optional() +}); + +// src/core/config/loader.ts +var ENTERPRISES_DIR = "enterprises"; +var CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR"; +var USER_DIR_ENV = "SEAL_HOME_USER_ENTERPRISES_DIR"; +var GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE"; +var GLOBAL_CONFIG_FILE = join2(homedir2(), ".config", "seal-home", "config.json"); +var USER_ENTERPRISES_DIR = join2(homedir2(), ".config", "seal-home", "enterprises"); +function loadCorpConfigs() { + const dirs = resolveEnterprisesDirs(); + const byId = new Map; + for (const dir of dirs) { + for (const file2 of readdirSync(dir).filter((item) => item.endsWith(".json")).filter((item) => !item.startsWith("example."))) { + const content = readFileSync2(join2(dir, file2), "utf-8"); + const corp = CorpConfigSchema.parse(JSON.parse(content)); + byId.set(corp.id, corp); + } + } + return Array.from(byId.values()); +} +function resolveEnterprisesDirs() { + const configured = process.env[CONFIG_ENV]?.trim(); + if (configured) + return existsSync2(configured) ? [configured] : []; + const userDir = process.env[USER_DIR_ENV]?.trim() || USER_ENTERPRISES_DIR; + return [ENTERPRISES_DIR, userDir].filter((dir) => existsSync2(dir)); +} +function resolveWritableEnterprisesDir() { + return process.env[CONFIG_ENV]?.trim() || USER_ENTERPRISES_DIR; +} +function getEnterprisesDirCandidates() { + return [ + `${CONFIG_ENV}=`, + ENTERPRISES_DIR, + USER_ENTERPRISES_DIR + ]; +} +function resolveGlobalConfigFile() { + return process.env[GLOBAL_CONFIG_ENV]?.trim() || GLOBAL_CONFIG_FILE; +} +function loadGlobalConfig() { + const file2 = resolveGlobalConfigFile(); + if (!existsSync2(file2)) { + return GlobalConfigSchema.parse({}); + } + return GlobalConfigSchema.parse(JSON.parse(readFileSync2(file2, "utf-8"))); +} +function saveGlobalConfig(config2) { + const normalized = GlobalConfigSchema.parse(config2); + const file2 = resolveGlobalConfigFile(); + mkdirSync2(dirname2(file2), { recursive: true, mode: 448 }); + writeFileSync2(file2, `${JSON.stringify(normalized, null, 2)} +`, { mode: 384 }); + return normalized; +} + +// src/core/config/manager.ts +function resolveCorpConfig(corps, options, candidates = []) { + const requestedCorpId = options.corpId?.trim() || undefined; + const configuredCorpId = options.stateful ? options.defaultCorpId?.trim() || undefined : undefined; + const selectedCorpId = requestedCorpId ?? configuredCorpId; + if (selectedCorpId) { + const corp = corps.find((item) => item.id === selectedCorpId); + if (corp) + return corp; + throw new Error(`No enterprise config found for ${selectedCorpId}`); + } + if (!options.stateful) { + throw new Error("Stateless mode is enabled. Every enterprise command requires --corp . " + "Use `seal-home config mode stateful` to enable a default enterprise."); + } + const firstCorp = corps[0]; + if (firstCorp) + return firstCorp; + throw new Error("No enterprise config found. Add a non-example JSON file under one of: " + (candidates.length ? candidates.join(", ") : "the configured enterprise directories")); +} + +class CorpContext { + current = null; + corps = new Map; + stateful = false; + defaultCorpId; + constructor(corps, options = { stateful: false }) { + this.stateful = options.stateful; + this.defaultCorpId = options.defaultCorpId; + this.replaceCorps(corps); + this.selectCurrent(corps[0]); + } + refresh(corps, options = { + stateful: this.stateful, + defaultCorpId: this.defaultCorpId + }) { + const currentId = this.current?.id; + this.stateful = options.stateful; + this.defaultCorpId = options.defaultCorpId; + this.replaceCorps(corps); + this.selectCurrent(currentId ? this.corps.get(currentId) ?? corps[0] : corps[0]); + } + replaceCorps(corps) { + this.corps = new Map; + for (const corp of corps) { + this.corps.set(corp.id, corp); + } + } + getCurrent() { + return this.current; + } + getCorp(corpId) { + return this.corps.get(corpId) ?? null; + } + resolve(corpId) { + if (corpId) + return this.getCorp(corpId); + return this.current; + } + switchCorp(corpId) { + if (!this.stateful) + return false; + const corp = this.corps.get(corpId); + if (!corp) + return false; + this.current = corp; + this.defaultCorpId = corp.id; + return true; + } + listCorps() { + return Array.from(this.corps.values()).map((corp) => ({ + id: corp.id, + name: corp.name, + sourceType: corp.source.type, + current: corp.id === this.current?.id + })); + } + selectCurrent(fallback) { + if (!this.stateful) { + this.current = null; + return; + } + this.current = this.defaultCorpId !== undefined ? this.corps.get(this.defaultCorpId) ?? null : fallback ?? null; + } +} + +// src/domains/seal/tools.ts +import { readFileSync as readFileSync3 } from "node:fs"; // src/domains/seal/api.ts import { randomBytes } from "node:crypto"; @@ -26098,35 +26135,6 @@ async function listBillingFeatures(client) { return JsonResponseSchema.parse(json2.data ?? json2); } -// src/domains/seal/source.ts -async function resolveLiveSealEnterpriseConfig(corp) { - const [baseConfig, client] = await Promise.all([ - resolveSealEnterpriseConfig(corp), - createSealClient(corp) - ]); - const me = await getMe(client); - return { - ...baseConfig, - tenantId: me.tenant.id, - tenantSlug: me.tenant.tenantSlug ?? baseConfig.tenantSlug, - tenantName: me.tenant.name, - raw: { - ...typeof baseConfig.raw === "object" && baseConfig.raw !== null ? baseConfig.raw : {}, - user: { - id: me.user.id, - name: me.user.name, - isAdmin: me.user.isAdmin, - providerUserId: me.user.providerUserId, - hosecloudStaff: me.user.hosecloudStaff - }, - tenant: me.tenant - } - }; -} - -// src/domains/seal/tools.ts -import { readFileSync as readFileSync3 } from "node:fs"; - // src/domains/seal/search.ts var CACHE_TTL_MS = 5 * 60 * 1000; var searchCache = new Map; @@ -28474,872 +28482,234 @@ function localParts(date6, timezone) { hour12: false }).formatToParts(date6).filter((part) => part.type !== "literal").map((part) => [part.type, part.value])); } -// package.json -var package_default = { - name: "seal-home", - version: "0.6.0", - type: "module", - module: "src/server.ts", - bin: { - "seal-home": "src/cli.ts" - }, - scripts: { - dev: "bun run --watch src/server.ts", - start: "bun run src/server.ts", - probe: "bun run src/probe.ts", - cli: "bun run src/cli.ts", - check: "tsc --noEmit", - "build:binary": "node scripts/build-binary.mjs", - "build:plugin": "node scripts/build-plugin.mjs", - "openapi:bundle": "bun run scripts/bundle-openapi.ts", - test: "bun test" - }, - dependencies: { - "@modelcontextprotocol/sdk": "^1.29.0", - ky: "^2.0.2", - zod: "^4.4.3" - }, - devDependencies: { - "@types/bun": "^1.3.14", - "bun-types": "^1.3.14", - typescript: "^5.9.3", - yaml: "^2.9.0" - } -}; -// src/version.ts -var VERSION = package_default.version; +// src/cli/printer.ts +import { writeFileSync as writeFileSync3 } from "node:fs"; -// src/cli/service.ts -import { spawn, execFileSync } from "node:child_process"; -import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, rmSync, writeFileSync as writeFileSync3 } from "node:fs"; -import { join as join3 } from "node:path"; -async function runServiceCommand(action, config2, options = {}) { - switch (action) { - case "run": - await runService(config2); - return; - case "start": - return startService(config2); - case "stop": - return stopService(config2, options); - case "restart": - stopService(config2, { quiet: true }); - return startService(config2); - case "status": - case undefined: - return serviceStatus(config2); - default: - throw new Error("Usage: seal-home service "); +// src/cli/parser.ts +function parseArgs(argv) { + const command = []; + const options = {}; + let json2; + for (let index = 0;index < argv.length; index += 1) { + const arg = argv[index]; + if (!arg) + continue; + if (arg === "--json") { + const raw = argv[index + 1]; + if (!raw) + throw new Error("--json requires a JSON object argument"); + json2 = JSON.parse(raw); + index += 1; + continue; + } + if (arg.startsWith("-")) { + const key = arg.replace(/^-+/, ""); + const next = argv[index + 1]; + if (!next || next.startsWith("-")) { + options[key] = true; + } else { + options[key] = next; + index += 1; + } + continue; + } + command.push(arg); } + return { command, options, json: json2 }; } -function serviceStatus(config2) { - const pidFile = getPidFile(config2); - const pid = readServicePid(pidFile); - const running = pid ? isSealHomeProcess(pid, config2.appRoot) : false; - if (pid && !running) { - rmSync(pidFile, { force: true }); +function jsonObject(value) { + if (value === undefined) + return {}; + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("--json must be an object"); + } + return value; +} +function stringOption(value) { + return typeof value === "string" ? value : undefined; +} +function numberOption(value) { + if (typeof value !== "string") + return; + const number5 = Number(value); + if (!Number.isFinite(number5)) + throw new Error(`Invalid number: ${value}`); + return number5; +} +function splitOption(value) { + if (typeof value !== "string") + return; + const items = value.split(",").map((item) => item.trim()).filter(Boolean); + return items.length ? items : undefined; +} +function booleanOption(value) { + if (value === undefined) + return; + if (typeof value === "boolean") + return value; + if (value === "true") + return true; + if (value === "false") + return false; + throw new Error(`Invalid boolean: ${value}`); +} +function requiredString(input, key) { + const value = optionalString(input, key); + if (!value) + throw new Error(`Missing required JSON field: ${key}`); + return value; +} +function requiredStringAlias(input, keys) { + for (const key of keys) { + const value = optionalString(input, key); + if (value) + return value; + } + throw new Error(`Missing required JSON field: ${keys.join(" or ")}`); +} +function optionalString(input, key) { + const value = input[key]; + return typeof value === "string" && value.trim() ? value.trim() : undefined; +} +function optionalNumber(input, key) { + const value = input[key]; + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} +function inferCorpIdFromStaffId(staffId) { + const [corpId] = staffId.split(":", 1); + return corpId || undefined; +} +function safeFileName(value) { + return value.replace(/[^a-zA-Z0-9._-]/g, "_"); +} +function parseStateMode(value) { + 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."); +} +function parseRuleVersionSelector(value) { + if (value === "latest") + return { latest: true }; + const versionNumber = Number(value); + if (Number.isInteger(versionNumber) && versionNumber > 0) { + return { versionNumber }; + } + return { versionId: value }; +} +function ruleVersionSearchOptions(value) { + if (!value) + return {}; + const selector = parseRuleVersionSelector(value); + if ("latest" in selector) { + return { + ruleVersionScope: "version", + latestRuleVersion: true + }; + } + if ("versionNumber" in selector) { + return { + ruleVersionScope: "version", + ruleVersionNumber: selector.versionNumber + }; } return { - running, - pid: running ? pid : undefined, - version: config2.version, - appRoot: config2.appRoot, - stateDir: config2.stateDir, - pidFile, - logFile: getLogFile(config2) + ruleVersionScope: "version", + ruleVersionId: selector.versionId }; } -async function runService(config2) { - const pidFile = getPidFile(config2); - const logFile = getLogFile(config2); - ensureStateDir(config2.stateDir); - writeFileSync3(pidFile, `${process.pid} -`, { mode: 384 }); - appendLog(logFile, `running pid=${process.pid}`); - const cleanup = () => { - if (readServicePid(pidFile) === process.pid) { - rmSync(pidFile, { force: true }); - } - appendLog(logFile, `stopped pid=${process.pid}`); - }; - await new Promise((resolve) => { - let stopped = false; - const heartbeat = setInterval(() => {}, 60000); - const stop2 = () => { - if (stopped) - return; - stopped = true; - cleanup(); - clearInterval(heartbeat); - process.off("SIGTERM", stop2); - process.off("SIGINT", stop2); - resolve(); - }; - process.once("SIGTERM", stop2); - process.once("SIGINT", stop2); - }); -} -function startService(config2) { - ensureStateDir(config2.stateDir); - const current = serviceStatus(config2); - if (current.running) { - return current; +function ruleVersionContextOptions(value) { + if (!value) + return {}; + const selector = parseRuleVersionSelector(value); + if ("latest" in selector) { + return { latestRuleVersion: true }; } - const launcher = config2.launcher ?? { command: process.execPath, args: [config2.entryFile] }; - const child = spawn(launcher.command, [ - ...launcher.args ?? [], - "service", - "run" - ], { - cwd: config2.appRoot, - detached: true, - stdio: ["ignore", "ignore", "ignore"], - env: process.env - }); - child.unref(); - const pidFile = getPidFile(config2); - writeFileSync3(pidFile, `${child.pid} -`, { mode: 384 }); - appendLog(getLogFile(config2), `started pid=${child.pid}`); - return { started: true, ...serviceStatus(config2) }; -} -function stopService(config2, options = {}) { - const pidFile = getPidFile(config2); - const pid = readServicePid(pidFile); - if (!pid || !isSealHomeProcess(pid, config2.appRoot)) { - rmSync(pidFile, { force: true }); - return options.quiet ? undefined : { stopped: false, reason: "not running" }; + if ("versionNumber" in selector) { + return { ruleVersionNumber: selector.versionNumber }; } - process.kill(pid, "SIGTERM"); - rmSync(pidFile, { force: true }); - appendLog(getLogFile(config2), `stop requested pid=${pid}`); - return options.quiet ? undefined : { stopped: true, pid }; + return { ruleVersionId: selector.versionId }; } -function isSealHomeProcess(pid, appRoot) { - if (!isProcessRunning(pid)) - return false; - try { - const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }); - return command.includes(appRoot) && command.includes("service") && command.includes("run"); - } catch { - return false; +function ruleVersionGetOptions(value) { + if (!value) + return {}; + const selector = parseRuleVersionSelector(value); + if ("latest" in selector) { + return { latest: true }; } -} -function isProcessRunning(pid) { - try { - process.kill(pid, 0); - return true; - } catch { - return false; + if ("versionNumber" in selector) { + return { versionNumber: selector.versionNumber }; } + return { versionId: selector.versionId }; } -function getPidFile(config2) { - return join3(config2.stateDir, "service.pid"); -} -function getLogFile(config2) { - return join3(config2.stateDir, "service.log"); -} -function readServicePid(path) { - if (!existsSync3(path)) +function parseWebhookMode(value) { + if (!value) return; - const pid = Number(readFileSync4(path, "utf8").trim()); - return Number.isInteger(pid) && pid > 0 ? pid : undefined; + const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_"); + const aliases = { + assisted: "assisted", + 辅助: "assisted", + semi_automatic: "semi_automatic", + 半自动: "semi_automatic", + fully_automatic: "fully_automatic", + 全自动: "fully_automatic" + }; + const mode = aliases[normalized]; + if (!mode) { + throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic"); + } + return mode; } -function ensureStateDir(stateDir) { - mkdirSync3(stateDir, { recursive: true, mode: 448 }); +function webhookRateOption(options) { + const value = numberOption(options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"]); + if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) { + throw new Error("Webhook auto approval rate must be an integer between 0 and 100"); + } + return value; } -function appendLog(path, message) { - writeFileSync3(path, `${new Date().toISOString()} ${message} -`, { flag: "a", mode: 384 }); +function webhookShowSecretOption(options) { + return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]); } -// src/cli/runner.ts -var DEFAULT_APP_ROOT = dirname3(dirname3(dirname3(fileURLToPath(import.meta.url)))); -var STATE_DIR = join4(homedir3(), ".config", "seal-home"); +// src/cli/printer.ts var RULE_LIST_FULL_COUNT_LIMIT = 100; var RULE_LIST_FULL_BYTES_LIMIT = 120000; var RULE_SUMMARY_FIELDS = ["id", "code", "status", "strictness", "scope", "createdAt", "updatedAt"]; var DEFAULT_OUTPUT_BYTES_LIMIT = 200000; -var KNOWN_AREAS = new Set([ - "config", - "service", - "update", - "tools", - "corps", - "tool", - "source", - "auth", - "delegation", - "users", - "llm", - "permissions", - "billing", - "webhook", - "webhooks", - "context", - "rules", - "approval-runs", - "simulation" -]); -var runQueue = Promise.resolve(); -function runCli(argv, options = {}) { - const run = runQueue.then(() => runCliOnce(argv, options)); - runQueue = run.then(() => { - return; - }, () => { - return; - }); - return run; +function formatConsoleOutput(values) { + return values.map((value) => typeof value === "string" ? value : String(value)).join(" "); } -async function runCliOnce(argv, options) { - const stdout = []; - const stderr = []; - const originalLog = console.log; - const originalError = console.error; - const runtime = { - appRoot: options.appRoot ?? DEFAULT_APP_ROOT, - entryFile: options.entryFile ?? join4(options.appRoot ?? DEFAULT_APP_ROOT, "src", "cli.ts"), - launcher: options.launcher - }; - console.log = (...values) => { - stdout.push(formatConsoleOutput(values)); - }; - console.error = (...values) => { - stderr.push(formatConsoleOutput(values)); - }; - try { - await dispatch(argv, runtime); - return { - stdout: joinOutput(stdout), - stderr: joinOutput(stderr), - isError: false, - exitCode: 0 - }; - } catch (error51) { - stderr.push(redactSensitiveText(error51 instanceof Error ? error51.message : String(error51))); - return { - stdout: joinOutput(stdout), - stderr: joinOutput(stderr), - isError: true, - exitCode: 1 - }; - } finally { - console.log = originalLog; - console.error = originalError; - } +function joinOutput(lines) { + if (!lines.length) + return ""; + return `${lines.join(` +`)} +`; } -async function dispatch(argv, runtime) { - const args = parseArgs(argv); - const [area, action, maybeName] = args.command; - if (area === "version" || area === "v" || Boolean(args.options.version) || Boolean(args.options.v) || Boolean(args.options.V)) { - printJson({ - name: "seal-home", - version: VERSION - }); - return; - } - if (!area || area === "help" || args.options.help) { - printHelp(); - return; - } - if (!KNOWN_AREAS.has(area)) { - throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); - } - if (area === "config" && action === "paths") { - printJson({ - candidates: getEnterprisesDirCandidates(), - globalConfigFile: resolveGlobalConfigFile() - }); - return; - } - if (area === "config" && (action === "get" || action === "status")) { - printJson(globalConfigSummary()); - return; - } - if (area === "config" && action === "mode") { - const mode = maybeName ?? stringOption(args.options.mode); - if (!mode) { - printJson(globalConfigSummary()); - return; - } - const stateful = parseStateMode(mode); - const requestedCorpId = stringOption(args.options.corp); - const previousConfig = loadGlobalConfig(); - const defaultCorpId = stateful ? requestedCorpId ? resolveCorpConfig(loadCorpConfigs(), { stateful: true, corpId: requestedCorpId }, getEnterprisesDirCandidates()).id : previousConfig.defaultCorpId : undefined; - const config2 = saveGlobalConfig({ - stateful, - ...defaultCorpId ? { defaultCorpId } : {} - }); - printJson(globalConfigSummary(config2)); - return; - } - if (area === "service") { - const result = await runServiceCommand(action, { - appRoot: runtime.appRoot, - entryFile: runtime.entryFile, - stateDir: STATE_DIR, - version: VERSION, - launcher: runtime.launcher - }); - if (result !== undefined) - printJson(result); - return; - } - if (area === "update") { - await updateAndRestart(runtime); - return; - } - if (area === "tools" && action === "list") { - printJson(sealTools.map((tool) => ({ name: tool.name, description: tool.description }))); - return; - } - if (area === "corps" && action === "list") { - const corpId = stringOption(args.options.corp); - const corps = loadCorpConfigs(); - const globalConfig2 = loadGlobalConfig(); - const currentCorpId = corpId ?? (globalConfig2.stateful ? globalConfig2.defaultCorpId ?? corps[0]?.id : undefined); - printJson(corps.map((item) => ({ - id: item.id, - name: item.name, - sourceType: item.source.type, - provider: item.source.provider ?? item.source.type, - current: item.id === currentCorpId - }))); - return; - } - if (area === "corps" && action === "current") { - const corp2 = selectCorp(stringOption(args.options.corp)); - printJson({ - id: corp2.id, - name: corp2.name, - sourceType: corp2.source.type, - provider: corp2.source.provider ?? corp2.source.type - }); - return; - } - if (area === "corps" && action === "switch") { - const corpId = maybeName; - if (!corpId) - throw new Error("Usage: seal-home corps switch "); - const globalConfig2 = loadGlobalConfig(); - if (!globalConfig2.stateful) { - throw new Error("Cannot switch the default enterprise while stateless mode is enabled. " + "Use `seal-home config mode stateful` first."); - } - const corp2 = selectCorp(corpId); - saveGlobalConfig({ ...globalConfig2, stateful: true, defaultCorpId: corp2.id }); - printJson({ - current: true, - id: corp2.id, - name: corp2.name - }); - return; - } - if (area === "corps" && action === "add-hose") { - await addHoseCorp(jsonObject(args.json)); - return; - } - if (area === "corps" && action === "add-seal") { - await addSealCorp(jsonObject(args.json)); - return; - } - const corp = selectCorp(stringOption(args.options.corp)); - if (area === "source" && action === "config") { - printJson(await resolveLiveSealEnterpriseConfig(corp)); - return; - } - if (area === "auth" && action === "diagnose") { - printJson(await diagnoseAuth(corp)); - return; - } - if (area === "auth" && action === "hose-link") { - const expiresIn = numberOption(args.options.expire) ?? 7200; - printJson(await getHoseProvisionalAuthLink(corp, expiresIn)); - return; - } - const client = await createSealClient(corp); - if (area === "delegation" && action === "list") { - await runTool("seal_delegation_list", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "delegation" && action === "create") { - const note = stringOption(args.options.note) ?? (maybeName ? [maybeName, ...args.command.slice(2)].join(" ") : undefined); - await runTool("seal_delegation_create", client, corp, { note }, outputOptions(args.options)); - return; - } - if (area === "delegation" && action === "revoke") { - const tokenId = maybeName ?? stringOption(args.options.tokenId); - if (!tokenId) - throw new Error("Usage: seal-home delegation revoke "); - await runTool("seal_delegation_revoke", client, corp, { tokenId }, outputOptions(args.options)); - return; - } - if (area === "users" && action === "create") { - const name = stringOption(args.options.name) ?? maybeName; - const phone = stringOption(args.options.phone); - if (!name || !phone) - throw new Error("Usage: seal-home users create --name --phone [--dept ]"); - const deptId = stringOption(args.options.dept) ?? stringOption(args.options.departmentId); - const departmentIds = deptId ? [deptId] : undefined; - await runTool("seal_user_create", client, corp, { name, phone, departmentIds }, outputOptions(args.options)); - return; - } - if (area === "users" && action === "reset-password") { - const userId = maybeName ?? stringOption(args.options.userId); - if (!userId) - throw new Error("Usage: seal-home users reset-password "); - await runTool("seal_user_reset_password", client, corp, { userId }, outputOptions(args.options)); - return; - } - if (area === "users" && (action === "search" || action === "list")) { - const keyword = maybeName ?? stringOption(args.options.keyword) ?? stringOption(args.options.query) ?? ""; - await runTool("seal_user_search", client, corp, { keyword }, outputOptions(args.options)); - return; - } - if (area === "users" && action === "get") { - const userId = maybeName ?? stringOption(args.options.userId); - if (!userId) - throw new Error("Usage: seal-home users get "); - await runTool("seal_user_get", client, corp, { userId }, outputOptions(args.options)); - return; - } - if (area === "users" && action === "delete") { - const userId = maybeName ?? stringOption(args.options.userId); - if (!userId) - throw new Error("Usage: seal-home users delete "); - await runTool("seal_user_delete", client, corp, { userId }, outputOptions(args.options)); - return; - } - if (area === "users" && action === "activate") { - const userId = maybeName ?? stringOption(args.options.userId); - if (!userId) - throw new Error("Usage: seal-home users activate "); - await runTool("seal_user_activate", client, corp, { userId }, outputOptions(args.options)); - return; - } - if (area === "users" && (action === "delegation" || action === "impersonate")) { - const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone); - if (!userIdOrPhone) - throw new Error("Usage: seal-home users delegation [--note ]"); - const note = stringOption(args.options.note); - await runTool("seal_user_delegation_create", client, corp, { userIdOrPhone, note }, outputOptions(args.options)); - return; - } - if (area === "llm" && (action === "config" || action === "get")) { - await runTool("seal_llm_config_get", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "llm" && (action === "providers" || action === "list")) { - await runTool("seal_llm_providers_list", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "permissions" && action === "available") { - await runTool("seal_permissions_available_list", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "permissions" && (action === "configs" || action === "list")) { - await runTool("seal_permissions_configs_list", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "billing" && (action === "status" || action === "get")) { - await runTool("seal_billing_status_get", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "billing" && action === "plans") { - await runTool("seal_billing_plans_list", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "billing" && action === "features") { - await runTool("seal_billing_features_list", client, corp, {}, outputOptions(args.options)); - return; - } - if ((area === "webhook" || area === "webhooks") && action === "list") { - await runTool("seal_webhook_list", client, corp, { - query: stringOption(args.options.query) ?? stringOption(args.options.keyword), - includeSecret: webhookShowSecretOption(args.options) - }, outputOptions(args.options)); - return; - } - if ((area === "webhook" || area === "webhooks") && (action === "get" || action === "find")) { - const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); - if (!selector) - throw new Error("Usage: seal-home webhook get [--show-secret]"); - await runTool("seal_webhook_get", client, corp, { - selector, - includeSecret: webhookShowSecretOption(args.options) - }, outputOptions(args.options)); - return; - } - if ((area === "webhook" || area === "webhooks") && (action === "add" || action === "create")) { - const name = stringOption(args.options.name) ?? maybeName; - const outgoingResultWebhook = stringOption(args.options.resultUrl) ?? stringOption(args.options["result-url"]) ?? stringOption(args.options.outgoingResultWebhook) ?? stringOption(args.options["outgoing-result-webhook"]); - if (!name || !outgoingResultWebhook) { - throw new Error("Usage: seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic]"); - } - const autoApprovalRate = webhookRateOption(args.options); - await runTool("seal_webhook_add", client, corp, { - name, - mode: parseWebhookMode(stringOption(args.options.mode)), - outgoingResultWebhook, - autoApprovalRate, - secret: stringOption(args.options.secret) - }, outputOptions(args.options)); - return; - } - if ((area === "webhook" || area === "webhooks") && action === "update") { - const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); - if (!selector) - throw new Error("Usage: seal-home webhook update [options]"); - const secret = stringOption(args.options.secret); - const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]); - if (secret !== undefined && rotateSecret) { - throw new Error("Use either --secret or --rotate-secret, not both"); - } - const name = stringOption(args.options.name); - const mode = parseWebhookMode(stringOption(args.options.mode)); - const outgoingResultWebhook = stringOption(args.options.resultUrl) ?? stringOption(args.options["result-url"]) ?? stringOption(args.options.outgoingResultWebhook) ?? stringOption(args.options["outgoing-result-webhook"]); - const autoApprovalRate = webhookRateOption(args.options); - if (name === undefined && mode === undefined && outgoingResultWebhook === undefined && autoApprovalRate === undefined && secret === undefined && !rotateSecret) { - throw new Error("Webhook update requires at least one field option"); - } - await runTool("seal_webhook_update", client, corp, { - selector, - name, - mode, - outgoingResultWebhook, - autoApprovalRate, - secret, - rotateSecret - }, outputOptions(args.options)); - return; - } - if ((area === "webhook" || area === "webhooks") && action === "delete") { - const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); - if (!selector) - throw new Error("Usage: seal-home webhook delete --yes"); - if (booleanOption(args.options.yes) !== true) { - throw new Error("Refusing to delete Webhook integration without --yes"); - } - await runTool("seal_webhook_delete", client, corp, { - selector, - confirm: true - }, outputOptions(args.options)); - return; - } - if (area === "context") { - await runTool("seal_approval_context_get", client, corp, { - documentLimit: numberOption(args.options.documentLimit), - ...ruleVersionContextOptions(stringOption(args.options.ruleVersion)) - }, outputOptions(args.options)); - return; - } - if (area === "rules" && action === "count") { - await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options)); - return; - } - if (area === "rules" && action === "list") { - if (booleanOption(args.options.count)) { - await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options)); - return; - } - const limit = numberOption(args.options.limit); - const offset = numberOption(args.options.offset); - if (booleanOption(args.options.summary)) { - await runTool("seal_approval_rules_list", client, corp, { - fields: RULE_SUMMARY_FIELDS, - limit, - offset - }, outputOptions(args.options)); - return; - } - const result = await runToolResult("seal_approval_rules_list", client, corp, { limit, offset }); - protectLargeRuleListOutput(result, booleanOption(args.options.full) === true); - printJson(result); - return; - } - if (area === "rules" && action === "clear") { - const confirmed = booleanOption(args.options.yes) === true; - const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed; - if (!confirmed && !dryRun) { - throw new Error("Refusing to clear rules without --yes. Use --dry-run to preview."); - } - const result = await runToolResult("seal_approval_rules_clear", client, corp, { - dryRun, - recode: booleanOption(args.options.recode) - }); - if (!confirmed && dryRun && result && typeof result === "object") { - printJson({ - ...result, - nextCommand: `seal-home rules clear --corp ${corp.id} --yes` - }, outputOptions(args.options)); - return; - } - printJson(result, outputOptions(args.options)); - return; - } - if (area === "rules" && action === "versions") { - await runTool("seal_approval_rule_versions_list", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "rules" && action === "version") { - const version2 = maybeName ?? stringOption(args.options.version); - if (!version2) - throw new Error("Usage: seal-home rules version "); - await runTool("seal_approval_rule_version_get", client, corp, parseRuleVersionSelector(version2), outputOptions(args.options)); - return; - } - if (area === "rules" && action === "get") { - await runTool("seal_approval_rule_get", client, corp, { - ...ruleVersionGetOptions(stringOption(args.options.version)), - code: stringOption(args.options.code), - runtimeId: stringOption(args.options.runtimeId) ?? stringOption(args.options["runtime-id"]), - recordId: stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]) - }, outputOptions(args.options)); - return; - } - if (area === "rules" && action === "search") { - const keyword = maybeName ?? stringOption(args.options.query); - if (!keyword) - throw new Error("Usage: seal-home rules search [--version ]"); - await runTool("seal_approval_search", client, corp, { - keywords: [keyword], - areas: ["rules"], - maxResults: numberOption(args.options.maxResults), - contextLines: numberOption(args.options.contextLines), - refresh: booleanOption(args.options.refresh), - snippetOnly: booleanOption(args.options.snippetOnly) ?? booleanOption(args.options["snippet-only"]), - maxChars: numberOption(args.options.maxChars) ?? numberOption(args.options["max-chars"]), - fields: splitOption(args.options.fields), - ...ruleVersionSearchOptions(stringOption(args.options.version)) - }, outputOptions(args.options)); - return; - } - if (area === "tool") { - if (!action) - throw new Error("Usage: seal-home tool [--json '{...}']"); - await runTool(action, client, corp, jsonObject(args.json), outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "summary") { - await runTool("seal_approval_runs_summary", client, corp, { - date: stringOption(args.options.date), - timezone: stringOption(args.options.timezone), - limit: numberOption(args.options.limit), - startDate: stringOption(args.options.startDate), - endDate: stringOption(args.options.endDate), - status: stringOption(args.options.status), - taskMode: stringOption(args.options.taskMode), - manualApprovalStatus: stringOption(args.options.manualApprovalStatus), - sourceDocumentSN: stringOption(args.options.sourceDocumentSN), - sourceDocumentId: stringOption(args.options.sourceDocumentId), - humanResult: stringOption(args.options.humanResult), - query: stringOption(args.options.query) - }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "search") { - await runTool("seal_approval_runs_search", client, corp, { - limit: numberOption(args.options.limit), - offset: numberOption(args.options.offset), - startDate: stringOption(args.options.startDate), - endDate: stringOption(args.options.endDate), - status: stringOption(args.options.status), - taskMode: stringOption(args.options.taskMode), - manualApprovalStatus: stringOption(args.options.manualApprovalStatus), - sourceDocumentSN: stringOption(args.options.sourceDocumentSN), - sourceDocumentId: stringOption(args.options.sourceDocumentId), - humanResult: stringOption(args.options.humanResult), - query: stringOption(args.options.query), - includeBridge: booleanOption(args.options.includeBridge) - }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "bridge") { - await runTool("seal_approval_run_langfuse_bridge_get", client, corp, { - recordId: stringOption(args.options.recordId), - sourceDocumentSN: stringOption(args.options.sourceDocumentSN), - sourceDocumentId: stringOption(args.options.sourceDocumentId), - simulationBatchId: stringOption(args.options.simulationBatchId), - limit: numberOption(args.options.limit) - }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "pick") { - const query = maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.sn); - if (!query) - throw new Error("Usage: seal-home approval-runs pick --sn "); - await runTool("seal_approval_run_pick", client, corp, { - query, - sn: stringOption(args.options.sn), - batchId: stringOption(args.options.batch) ?? stringOption(args.options.batchId), - latest: booleanOption(args.options.latest), - fields: stringOption(args.options.fields), - limit: numberOption(args.options.limit), - includeBridge: booleanOption(args.options.includeBridge) - }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "get") { - const recordId = args.command[2]; - if (!recordId) - throw new Error("Missing approval run recordId"); - await runTool("seal_approval_run_get", client, corp, { - recordId, - fields: stringOption(args.options.fields), - summary: booleanOption(args.options.summary) - }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "cited-rules") { - const recordId = args.command[2]; - if (!recordId) - throw new Error("Usage: seal-home approval-runs cited-rules "); - await runTool("seal_approval_run_cited_rules_get", client, corp, { recordId }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "document-summary") { - const recordId = args.command[2]; - if (!recordId) - throw new Error("Usage: seal-home approval-runs document-summary "); - await runTool("seal_approval_run_document_summary_get", client, corp, { recordId }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "attachments") { - const recordId = args.command[2]; - if (!recordId) - throw new Error("Usage: seal-home approval-runs attachments "); - await runTool("seal_approval_run_attachments_get", client, corp, { - recordId, - summary: booleanOption(args.options.summary) - }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "result") { - const recordId = args.command[2]; - if (!recordId) - throw new Error("Usage: seal-home approval-runs result [--summary]"); - await runTool("seal_approval_run_result_get", client, corp, { - recordId, - summary: booleanOption(args.options.summary) - }, outputOptions(args.options)); - return; - } - if (area === "approval-runs" && action === "url") { - await runTool("seal_approval_run_url_get", client, corp, { - recordId: maybeName, - sourceDocumentSN: stringOption(args.options.sourceDocumentSN), - sourceDocumentId: stringOption(args.options.sourceDocumentId) - }, outputOptions(args.options)); - return; - } - if (area === "simulation" && action === "batch-records") { - const batchId = maybeName ?? stringOption(args.options.batchId); - if (!batchId) - throw new Error("Usage: seal-home simulation batch-records "); - await runTool("seal_simulation_batch_records_get", client, corp, { - batchId, - query: stringOption(args.options.query) - }, outputOptions(args.options)); - return; - } - if (area === "simulation" && action === "create") { - const modeArg = stringOption(args.options.mode) ?? "hosecloud"; - const mode = modeArg === "material-pack" ? "material_pack" : modeArg; - const schemaConfigPath = stringOption(args.options.schemaConfig) ?? stringOption(args.options["schema-config"]); - const schemaConfig = schemaConfigPath ? JSON.parse(readFileSync5(schemaConfigPath, "utf8")) : undefined; - await runTool("seal_simulation_batch_create", client, corp, { - mode, - flowIds: splitOption(args.options.flowIds) ?? splitOption(args.options["flow-ids"]), - rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null, - thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]), - skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]), - skipExpenseExtraction: booleanOption(args.options.skipExpenseExtraction) ?? booleanOption(args.options["skip-expense-extraction"]), - disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]), - signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]), - packageIds: splitOption(args.options.packageIds) ?? splitOption(args.options["package-ids"]), - templateId: stringOption(args.options.templateId) ?? stringOption(args.options["template-id"]), - schemaConfig, - rawParams: jsonObject(args.json) - }, outputOptions(args.options)); - return; - } - if (area === "simulation" && action === "list") { - await runTool("seal_simulation_batches_list", client, corp, { - limit: numberOption(args.options.limit) - }, outputOptions(args.options)); - return; - } - if (area === "simulation" && action === "get") { - const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]); - if (!batchId) - throw new Error("Usage: seal-home simulation get "); - await runTool("seal_simulation_batch_get", client, corp, { batchId }, outputOptions(args.options)); - return; - } - if (area === "simulation" && action === "templates") { - await runTool("seal_simulation_templates_get", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "simulation" && action === "integrations") { - await runTool("seal_simulation_integrations_get", client, corp, {}, outputOptions(args.options)); - return; - } - if (area === "simulation" && action === "package-upload") { - const filePath = maybeName ?? stringOption(args.options.file); - if (!filePath) - throw new Error("Usage: seal-home simulation package-upload <材料包.zip>"); - if (!existsSync4(filePath)) - throw new Error(`File not found: ${filePath}`); - await runTool("seal_simulation_material_package_upload", client, corp, { filePath }, outputOptions(args.options)); - return; - } - throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); +function redactSensitiveText(value) { + return value.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi, "$1").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1"); } -async function updateAndRestart(runtime) { - const serviceConfig = { - appRoot: runtime.appRoot, - entryFile: runtime.entryFile, - stateDir: STATE_DIR, - version: VERSION, - launcher: runtime.launcher - }; - const wasRunning = serviceStatus(serviceConfig).running; - if (wasRunning) - await runServiceCommand("stop", serviceConfig); - runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]); - runCommand("bun", ["install"], { cwd: runtime.appRoot }); - if (wasRunning) - await runServiceCommand("start", serviceConfig); - printJson({ - updated: true, - serviceRestarted: wasRunning, - version: VERSION - }); -} -function runCommand(command, args, options = {}) { - const result = spawnSync(command, args, { - cwd: options.cwd, - encoding: "utf8", - stdio: ["ignore", "pipe", "pipe"] - }); - if (result.stdout) - console.error(result.stdout.trimEnd()); - if (result.stderr) - console.error(result.stderr.trimEnd()); - if (result.status !== 0) { - throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`); +function printJson(value, options = {}) { + protectLargeOutput(value, options); + const json2 = `${JSON.stringify(value, null, 2)} +`; + if (options.outputFile) { + writeFileSync3(options.outputFile, json2); + console.log(JSON.stringify({ outputFile: options.outputFile, bytes: Buffer.byteLength(json2, "utf-8") }, null, 2)); + return; } + console.log(json2.trimEnd()); } -async function runTool(name, client, corp, params, options = {}) { - printJson(await runToolResult(name, client, corp, params), options); -} -async function runToolResult(name, client, corp, params) { - const tool = sealTools.find((item) => item.name === name); - if (!tool) - throw new Error(`Unknown Seal tool: ${name}`); - const compactParams = Object.fromEntries(Object.entries(params).filter(([, value]) => value !== undefined)); - const handler = tool.handler; - return handler(client, compactParams, { corp }); +function protectLargeOutput(result, options = {}) { + if (options.allowFull || options.outputFile) + return; + const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); + if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) { + throw new Error(`Output is large (${bodyBytes} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`); + } } function protectLargeRuleListOutput(result, allowFull) { if (allowFull) @@ -29353,20 +28723,93 @@ function protectLargeRuleListOutput(result, allowFull) { throw new Error(`Rule list is large (${effectiveCount} rules, ${bodyBytes} bytes). Use "seal-home rules list --summary" or "seal-home rules count"; pass --full only when you really need full descriptions.`); } } -function protectLargeOutput(result, options = {}) { - if (options.allowFull || options.outputFile) - return; - const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); - if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) { - throw new Error(`Output is large (${bodyBytes} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`); - } -} function outputOptions(options) { return { allowFull: booleanOption(options.full) === true, outputFile: stringOption(options.outputFile) ?? stringOption(options["output-file"]) }; } +function printHelp() { + console.log(`seal-home CLI + +Usage: + seal-home version + seal-home mcp + seal-home mcp config + seal-home mcp-config + seal-home skill dump + seal-home skill install [--dir |--local] + seal-home skill status + seal-home probe [] + seal-home config paths + seal-home config get + seal-home config mode [--corp ] + seal-home service + seal-home update + seal-home tools list + seal-home corps list [--corp ] + seal-home corps current [--corp ] + seal-home corps switch + seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' + seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' + seal-home auth diagnose [--corp ] + seal-home auth hose-link [--corp ] [--expire 7200] + seal-home delegation list [--corp ] + seal-home delegation create [--note ] [--corp ] + seal-home delegation revoke [--corp ] + seal-home users create --name --phone [--dept ] [--corp ] + seal-home users search [--corp ] + seal-home users delegation [--note ] [--corp ] + seal-home users reset-password [--corp ] + seal-home users get [--corp ] + seal-home users delete [--corp ] + seal-home llm config [--corp ] + seal-home llm providers [--corp ] + seal-home permissions available [--corp ] + seal-home permissions configs [--corp ] + seal-home billing status [--corp ] + seal-home billing plans [--corp ] + seal-home billing features [--corp ] + seal-home webhook list [--query ] [--show-secret] [--corp ] + seal-home webhook get|find [--show-secret] [--corp ] + seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ] + seal-home webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ] + seal-home webhook delete --yes [--corp ] + seal-home source config [--corp ] + seal-home tool [--corp ] [--json '{"key":"value"}'] + seal-home rules count [--corp ] + seal-home rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp ] + seal-home rules clear [--corp ] [--dry-run|--yes] + seal-home rules versions [--corp ] + seal-home rules version [--corp ] + seal-home rules get --corp --version --code '#0038' + seal-home rules get --corp --record-id --runtime-id rule-205 + seal-home rules search [--version ] [--maxResults 20] [--corp ] + seal-home context [--ruleVersion ] [--documentLimit 50] [--corp ] + seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp ] + seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp ] + seal-home approval-runs pick --sn [--batch ] [--latest] [--fields recordId,status,aiDecision] [--corp ] + seal-home approval-runs get [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp ] + seal-home approval-runs cited-rules [--corp ] + seal-home approval-runs document-summary [--corp ] + seal-home approval-runs attachments [--summary] [--corp ] + seal-home approval-runs result [--summary] [--corp ] + seal-home approval-runs url [--corp ] + seal-home approval-runs url [--corp ] + seal-home approval-runs url --sourceDocumentSN B26022501 [--corp ] + seal-home approval-runs bridge [--sourceDocumentSN B26001887] [--corp ] + seal-home simulation batch-records [--corp ] + seal-home simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp ] + seal-home simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp ] + seal-home simulation list [--limit 50] [--corp ] + seal-home simulation get [--corp ] + seal-home simulation templates [--corp ] + seal-home simulation integrations [--corp ] + seal-home simulation package-upload <材料包.zip> [--corp ] +`); +} + +// src/cli/helpers.ts function selectCorp(corpId) { const corps = loadCorpConfigs(); const globalConfig2 = loadGlobalConfig(); @@ -29384,133 +28827,147 @@ function globalConfigSummary(config2 = loadGlobalConfig()) { configFile: resolveGlobalConfigFile() }; } -function parseStateMode(value) { - 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."); +async function runTool(name, client, corp, params, options = {}) { + printJson(await runToolResult(name, client, corp, params), options); } -async function addHoseCorp(input) { - const nameInput = optionalString(input, "name"); - const appKey = requiredString(input, "appKey"); - const appSecurity = requiredString(input, "appSecurity"); - const staffId = requiredStringAlias(input, ["staffId", "proxyStaffBizId"]); - const corpIdInput = optionalString(input, "corpId") ?? optionalString(input, "corporationId"); - const domain2 = optionalString(input, "domain") ?? "https://app.ekuaibao.com"; - const verify = input.force === true || input.verify === false ? false : true; - const remote = corpIdInput && !verify ? undefined : await resolveHoseCorporation(domain2, appKey, appSecurity); - const corpId = corpIdInput ?? remote?.id ?? (!verify ? inferCorpIdFromStaffId(staffId) : undefined); - if (!corpId) { - throw new Error("Missing required JSON field: corpId. Hose login did not return corporationId. Pass force:true to infer it from proxyStaffBizId."); - } - const id = optionalString(input, "id") ?? corpId; - const name = nameInput ?? remote?.name ?? corpId; - const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`; - const config2 = { - id, - name, - seal: { - url: sealUrl, - endpoints: { - approvalStylePreferences: "api/v1/agent/ai-approval/config" - } - }, - source: { - type: "hose", - domain: domain2, - appKey, - appSecurity, - corpId, - staffId - }, - auth: { - refreshTtl: 300 - } - }; - if (verify) { - clearCorpTokenCache(id); - await resolveLiveSealEnterpriseConfig(config2); - } - const enterprisesDir = resolveWritableEnterprisesDir(); - mkdirSync4(enterprisesDir, { recursive: true, mode: 448 }); - const file2 = join4(enterprisesDir, `${safeFileName(id)}.json`); - if (existsSync4(file2) && input.overwrite !== true) { - throw new Error(`Enterprise config already exists: ${file2}. Pass "overwrite": true to replace it.`); - } - writeFileSync4(file2, `${JSON.stringify(config2, null, 2)} -`, { mode: 384 }); - printJson({ - id, - name, - corpId, - verified: verify, - path: file2 - }); +async function runToolResult(name, client, corp, params) { + const tool = sealTools.find((item) => item.name === name); + if (!tool) + throw new Error(`Unknown Seal tool: ${name}`); + const compactParams = Object.fromEntries(Object.entries(params).filter(([, value]) => value !== undefined)); + const handler = tool.handler; + return handler(client, compactParams, { corp }); } -async function addSealCorp(input) { - const token = requiredString(input, "token"); - const sealUrl = (optionalString(input, "sealUrl") ?? optionalString(input, "url") ?? "").replace(/\/+$/, ""); - if (!sealUrl) - throw new Error("Missing required JSON field: sealUrl"); - const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60; - const verify = input.force === true || input.verify === false ? false : true; - const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined; - const remoteUser = remote?.user; - const remoteTenant = remote?.tenant; - const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue(remoteTenant?.tenantSlug); - const tenantId = optionalString(input, "tenantId") ?? stringValue(remoteTenant?.id); - const tenantName = optionalString(input, "tenantName") ?? optionalString(input, "name") ?? stringValue(remoteTenant?.name); - const id = optionalString(input, "id") ?? tenantSlug ?? tenantId; - if (!id) { - throw new Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId."); + +// src/cli/commands/approval-runs.ts +async function handleApprovalRunsCommand(action, maybeName, client, corp, args) { + if (action === "summary") { + await runTool("seal_approval_runs_summary", client, corp, { + date: stringOption(args.options.date), + timezone: stringOption(args.options.timezone), + limit: numberOption(args.options.limit), + startDate: stringOption(args.options.startDate), + endDate: stringOption(args.options.endDate), + status: stringOption(args.options.status), + taskMode: stringOption(args.options.taskMode), + manualApprovalStatus: stringOption(args.options.manualApprovalStatus), + sourceDocumentSN: stringOption(args.options.sourceDocumentSN), + sourceDocumentId: stringOption(args.options.sourceDocumentId), + humanResult: stringOption(args.options.humanResult), + query: stringOption(args.options.query) + }, outputOptions(args.options)); + return; } - const staffId = optionalString(input, "staffId") ?? stringValue(remoteUser?.providerUserId) ?? stringValue(remoteUser?.id) ?? "seal"; - const provider = optionalString(input, "provider") ?? stringValue(remoteUser?.provider) ?? stringValue(remoteTenant?.providerConfig?.provider); - const config2 = { - id, - name: tenantName ?? id, - seal: { - url: sealUrl, - tenantSlug, - endpoints: { - approvalStylePreferences: "api/v1/agent/ai-approval/config" - } - }, - source: { - type: "seal", - token, - sealUrl, - expiresIn, - staffId, - corpId: tenantSlug ?? tenantId ?? id, - tenantId, - tenantSlug, - tenantName, - providerUserId: stringValue(remoteUser?.providerUserId), - provider - }, - auth: { - refreshTtl: 300 - } - }; - const enterprisesDir = resolveWritableEnterprisesDir(); - mkdirSync4(enterprisesDir, { recursive: true, mode: 448 }); - const file2 = join4(enterprisesDir, `${safeFileName(id)}.json`); - if (existsSync4(file2) && input.overwrite !== true) { - throw new Error(`Enterprise config already exists: ${file2}. Pass "overwrite": true to replace it.`); + if (action === "search") { + await runTool("seal_approval_runs_search", client, corp, { + limit: numberOption(args.options.limit), + offset: numberOption(args.options.offset), + startDate: stringOption(args.options.startDate), + endDate: stringOption(args.options.endDate), + status: stringOption(args.options.status), + taskMode: stringOption(args.options.taskMode), + manualApprovalStatus: stringOption(args.options.manualApprovalStatus), + sourceDocumentSN: stringOption(args.options.sourceDocumentSN), + sourceDocumentId: stringOption(args.options.sourceDocumentId), + humanResult: stringOption(args.options.humanResult), + query: stringOption(args.options.query), + includeBridge: booleanOption(args.options.includeBridge) + }, outputOptions(args.options)); + return; } - writeFileSync4(file2, `${JSON.stringify(config2, null, 2)} -`, { mode: 384 }); - printJson({ - id, - name: config2.name, - tenantId, - tenantSlug, - verified: verify, - path: file2 - }); + if (action === "bridge") { + await runTool("seal_approval_run_langfuse_bridge_get", client, corp, { + recordId: stringOption(args.options.recordId), + sourceDocumentSN: stringOption(args.options.sourceDocumentSN), + sourceDocumentId: stringOption(args.options.sourceDocumentId), + simulationBatchId: stringOption(args.options.simulationBatchId), + limit: numberOption(args.options.limit) + }, outputOptions(args.options)); + return; + } + if (action === "pick") { + const query = maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.sn); + if (!query) + throw new Error("Usage: seal-home approval-runs pick --sn "); + await runTool("seal_approval_run_pick", client, corp, { + query, + sn: stringOption(args.options.sn), + batchId: stringOption(args.options.batch) ?? stringOption(args.options.batchId), + latest: booleanOption(args.options.latest), + fields: stringOption(args.options.fields), + limit: numberOption(args.options.limit), + includeBridge: booleanOption(args.options.includeBridge) + }, outputOptions(args.options)); + return; + } + if (action === "get") { + const recordId = args.command[2]; + if (!recordId) + throw new Error("Missing approval run recordId"); + await runTool("seal_approval_run_get", client, corp, { + recordId, + fields: stringOption(args.options.fields), + summary: booleanOption(args.options.summary) + }, outputOptions(args.options)); + return; + } + if (action === "cited-rules") { + const recordId = args.command[2]; + if (!recordId) + throw new Error("Usage: seal-home approval-runs cited-rules "); + await runTool("seal_approval_run_cited_rules_get", client, corp, { recordId }, outputOptions(args.options)); + return; + } + if (action === "document-summary") { + const recordId = args.command[2]; + if (!recordId) + throw new Error("Usage: seal-home approval-runs document-summary "); + await runTool("seal_approval_run_document_summary_get", client, corp, { recordId }, outputOptions(args.options)); + return; + } + if (action === "attachments") { + const recordId = args.command[2]; + if (!recordId) + throw new Error("Usage: seal-home approval-runs attachments "); + await runTool("seal_approval_run_attachments_get", client, corp, { + recordId, + summary: booleanOption(args.options.summary) + }, outputOptions(args.options)); + return; + } + if (action === "result") { + const recordId = args.command[2]; + if (!recordId) + throw new Error("Usage: seal-home approval-runs result [--summary]"); + await runTool("seal_approval_run_result_get", client, corp, { + recordId, + summary: booleanOption(args.options.summary) + }, outputOptions(args.options)); + return; + } + if (action === "url") { + await runTool("seal_approval_run_url_get", client, corp, { + recordId: maybeName, + sourceDocumentSN: stringOption(args.options.sourceDocumentSN), + sourceDocumentId: stringOption(args.options.sourceDocumentId) + }, outputOptions(args.options)); + return; + } + throw new Error(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/cli/commands/auth.ts +async function handleAuthCommand(action, corp, args) { + if (action === "diagnose") { + printJson(await diagnoseAuth(corp)); + return; + } + if (action === "hose-link") { + const expiresIn = numberOption(args.options.expire) ?? 7200; + printJson(await getHoseProvisionalAuthLink(corp, expiresIn)); + return; + } + throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-home help' for available commands.`); } async function diagnoseAuth(corp) { if (corp.source.type !== "hose") { @@ -29695,16 +29152,6 @@ async function getJson(url2, headers = {}) { }); return parseJsonResponse(response); } -async function resolveSealWhoami(sealUrl, token) { - const json2 = await getJson(`${sealUrl}/api/v1/auth/me`, { - authorization: `Bearer ${token}` - }); - const data = objectValue(json2.data); - return { - user: objectValue(data.user ?? json2.user), - tenant: objectValue(data.tenant ?? json2.tenant) - }; -} async function parseJsonResponse(response) { const body = await response.text(); if (!response.ok) { @@ -29735,31 +29182,267 @@ function summarizeHoseCorpConfig(value) { function compactObject2(value) { return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)); } -function requiredString(input, key) { - const value = optionalString(input, key); - if (!value) - throw new Error(`Missing required JSON field: ${key}`); - return value; -} -function requiredStringAlias(input, keys) { - for (const key of keys) { - const value = optionalString(input, key); - if (value) - return value; + +// src/cli/commands/billing.ts +async function handleBillingCommand(action, client, corp, args) { + if (action === "status" || action === "get") { + await runTool("seal_billing_status_get", client, corp, {}, outputOptions(args.options)); + return; } - throw new Error(`Missing required JSON field: ${keys.join(" or ")}`); + if (action === "plans") { + await runTool("seal_billing_plans_list", client, corp, {}, outputOptions(args.options)); + return; + } + if (action === "features") { + await runTool("seal_billing_features_list", client, corp, {}, outputOptions(args.options)); + return; + } + throw new Error(`Unknown billing command: ${action ?? ""}. Run 'seal-home help' for available commands.`); } -function optionalString(input, key) { - const value = input[key]; - return typeof value === "string" && value.trim() ? value.trim() : undefined; + +// src/cli/commands/config.ts +function handleConfigCommand(action, maybeName, args) { + if (action === "paths") { + printJson({ + candidates: getEnterprisesDirCandidates(), + globalConfigFile: resolveGlobalConfigFile() + }); + return; + } + if (action === "get" || action === "status") { + printJson(globalConfigSummary()); + return; + } + if (action === "mode") { + const mode = maybeName ?? stringOption(args.options.mode); + if (!mode) { + printJson(globalConfigSummary()); + return; + } + const stateful = parseStateMode(mode); + const requestedCorpId = stringOption(args.options.corp); + const previousConfig = loadGlobalConfig(); + const defaultCorpId = stateful ? requestedCorpId ? resolveCorpConfig(loadCorpConfigs(), { stateful: true, corpId: requestedCorpId }, getEnterprisesDirCandidates()).id : previousConfig.defaultCorpId : undefined; + const config2 = saveGlobalConfig({ + stateful, + ...defaultCorpId ? { defaultCorpId } : {} + }); + printJson(globalConfigSummary(config2)); + return; + } + throw new Error(`Unknown config command: ${action ?? ""}. Run 'seal-home help' for available commands.`); } -function optionalNumber(input, key) { - const value = input[key]; - return typeof value === "number" && Number.isFinite(value) ? value : undefined; + +// src/cli/commands/context.ts +async function handleContextCommand(client, corp, args) { + await runTool("seal_approval_context_get", client, corp, { + documentLimit: numberOption(args.options.documentLimit), + ...ruleVersionContextOptions(stringOption(args.options.ruleVersion)) + }, outputOptions(args.options)); } -function inferCorpIdFromStaffId(staffId) { - const [corpId] = staffId.split(":", 1); - return corpId || undefined; + +// src/cli/commands/corps.ts +import { existsSync as existsSync3, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "node:fs"; +import { join as join3 } from "node:path"; + +// src/domains/seal/source.ts +async function resolveLiveSealEnterpriseConfig(corp) { + const [baseConfig, client] = await Promise.all([ + resolveSealEnterpriseConfig(corp), + createSealClient(corp) + ]); + const me = await getMe(client); + return { + ...baseConfig, + tenantId: me.tenant.id, + tenantSlug: me.tenant.tenantSlug ?? baseConfig.tenantSlug, + tenantName: me.tenant.name, + raw: { + ...typeof baseConfig.raw === "object" && baseConfig.raw !== null ? baseConfig.raw : {}, + user: { + id: me.user.id, + name: me.user.name, + isAdmin: me.user.isAdmin, + providerUserId: me.user.providerUserId, + hosecloudStaff: me.user.hosecloudStaff + }, + tenant: me.tenant + } + }; +} + +// src/cli/commands/corps.ts +async function handleCorpsCommand(action, maybeName, args) { + if (action === "list") { + const corpId = stringOption(args.options.corp); + const corps = loadCorpConfigs(); + const globalConfig2 = loadGlobalConfig(); + const currentCorpId = corpId ?? (globalConfig2.stateful ? globalConfig2.defaultCorpId ?? corps[0]?.id : undefined); + printJson(corps.map((item) => ({ + id: item.id, + name: item.name, + sourceType: item.source.type, + provider: item.source.provider ?? item.source.type, + current: item.id === currentCorpId + }))); + return; + } + if (action === "current") { + const corp = selectCorp(stringOption(args.options.corp)); + printJson({ + id: corp.id, + name: corp.name, + sourceType: corp.source.type, + provider: corp.source.provider ?? corp.source.type + }); + return; + } + if (action === "switch") { + const corpId = maybeName; + if (!corpId) + throw new Error("Usage: seal-home corps switch "); + const globalConfig2 = loadGlobalConfig(); + if (!globalConfig2.stateful) { + throw new Error("Cannot switch the default enterprise while stateless mode is enabled. " + "Use `seal-home config mode stateful` first."); + } + const corp = selectCorp(corpId); + saveGlobalConfig({ ...globalConfig2, stateful: true, defaultCorpId: corp.id }); + printJson({ + current: true, + id: corp.id, + name: corp.name + }); + return; + } + if (action === "add-hose") { + await addHoseCorp(jsonObject(args.json)); + return; + } + if (action === "add-seal") { + await addSealCorp(jsonObject(args.json)); + return; + } + throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} +async function addHoseCorp(input) { + const nameInput = optionalString(input, "name"); + const appKey = requiredString(input, "appKey"); + const appSecurity = requiredString(input, "appSecurity"); + const staffId = requiredStringAlias(input, ["staffId", "proxyStaffBizId"]); + const corpIdInput = optionalString(input, "corpId") ?? optionalString(input, "corporationId"); + const domain2 = optionalString(input, "domain") ?? "https://app.ekuaibao.com"; + const verify = input.force === true || input.verify === false ? false : true; + const remote = corpIdInput && !verify ? undefined : await resolveHoseCorporation(domain2, appKey, appSecurity); + const corpId = corpIdInput ?? remote?.id ?? (!verify ? inferCorpIdFromStaffId(staffId) : undefined); + if (!corpId) { + throw new Error("Missing required JSON field: corpId. Hose login did not return corporationId. Pass force:true to infer it from proxyStaffBizId."); + } + const id = optionalString(input, "id") ?? corpId; + const name = nameInput ?? remote?.name ?? corpId; + const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`; + const config2 = { + id, + name, + seal: { + url: sealUrl, + endpoints: { + approvalStylePreferences: "api/v1/agent/ai-approval/config" + } + }, + source: { + type: "hose", + domain: domain2, + appKey, + appSecurity, + corpId, + staffId + }, + auth: { + refreshTtl: 300 + } + }; + if (verify) { + clearCorpTokenCache(id); + await resolveLiveSealEnterpriseConfig(config2); + } + const enterprisesDir = resolveWritableEnterprisesDir(); + mkdirSync3(enterprisesDir, { recursive: true, mode: 448 }); + const file2 = join3(enterprisesDir, `${safeFileName(id)}.json`); + if (existsSync3(file2) && input.overwrite !== true) { + throw new Error(`Enterprise config already exists: ${file2}. Pass "overwrite": true to replace it.`); + } + writeFileSync4(file2, `${JSON.stringify(config2, null, 2)} +`, { mode: 384 }); + printJson({ + id, + name, + corpId, + verified: verify, + path: file2 + }); +} +async function addSealCorp(input) { + const token = requiredString(input, "token"); + const sealUrl = (optionalString(input, "sealUrl") ?? optionalString(input, "url") ?? "").replace(/\/+$/, ""); + if (!sealUrl) + throw new Error("Missing required JSON field: sealUrl"); + const expiresIn = optionalNumber(input, "expiresIn") ?? 30 * 24 * 60 * 60; + const verify = input.force === true || input.verify === false ? false : true; + const remote = verify ? await resolveSealWhoami(sealUrl, token) : undefined; + const remoteUser = remote?.user; + const remoteTenant = remote?.tenant; + const tenantSlug = optionalString(input, "tenantSlug") ?? stringValue2(remoteTenant?.tenantSlug); + const tenantId = optionalString(input, "tenantId") ?? stringValue2(remoteTenant?.id); + const tenantName = optionalString(input, "tenantName") ?? optionalString(input, "name") ?? stringValue2(remoteTenant?.name); + const id = optionalString(input, "id") ?? tenantSlug ?? tenantId; + if (!id) { + throw new Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId."); + } + const staffId = optionalString(input, "staffId") ?? stringValue2(remoteUser?.providerUserId) ?? stringValue2(remoteUser?.id) ?? "seal"; + const provider = optionalString(input, "provider") ?? stringValue2(remoteUser?.provider) ?? stringValue2(remoteTenant?.providerConfig?.provider); + const config2 = { + id, + name: tenantName ?? id, + seal: { + url: sealUrl, + tenantSlug, + endpoints: { + approvalStylePreferences: "api/v1/agent/ai-approval/config" + } + }, + source: { + type: "seal", + token, + sealUrl, + expiresIn, + staffId, + corpId: tenantSlug ?? tenantId ?? id, + tenantId, + tenantSlug, + tenantName, + providerUserId: stringValue2(remoteUser?.providerUserId), + provider + }, + auth: { + refreshTtl: 300 + } + }; + const enterprisesDir = resolveWritableEnterprisesDir(); + mkdirSync3(enterprisesDir, { recursive: true, mode: 448 }); + const file2 = join3(enterprisesDir, `${safeFileName(id)}.json`); + if (existsSync3(file2) && input.overwrite !== true) { + throw new Error(`Enterprise config already exists: ${file2}. Pass "overwrite": true to replace it.`); + } + writeFileSync4(file2, `${JSON.stringify(config2, null, 2)} +`, { mode: 384 }); + printJson({ + id, + name: config2.name, + tenantId, + tenantSlug, + verified: verify, + path: file2 + }); } async function resolveHoseCorporation(domain2, appKey, appSecurity) { const response = await fetch(`${domain2.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, { @@ -29783,258 +29466,2229 @@ async function resolveHoseCorporation(domain2, appKey, appSecurity) { name: data.value?.corporation?.name } : undefined; } -function safeFileName(value) { - return value.replace(/[^a-zA-Z0-9._-]/g, "_"); +async function resolveSealWhoami(sealUrl, token) { + const json2 = await getJson2(`${sealUrl}/api/v1/auth/me`, { + authorization: `Bearer ${token}` + }); + const data = objectValue2(json2.data); + return { + user: objectValue2(data.user ?? json2.user), + tenant: objectValue2(data.tenant ?? json2.tenant) + }; } -function parseRuleVersionSelector(value) { - if (value === "latest") - return { latest: true }; - const versionNumber = Number(value); - if (Number.isInteger(versionNumber) && versionNumber > 0) { - return { versionNumber }; +async function getJson2(url2, headers = {}) { + const response = await fetch(url2, { + headers + }); + const body = await response.text(); + if (!response.ok) { + throw new Error(`${response.status} ${body}`); } - return { versionId: value }; + const json2 = JSON.parse(body); + return objectValue2(json2); } -function ruleVersionSearchOptions(value) { - if (!value) - return {}; - const selector = parseRuleVersionSelector(value); - if ("latest" in selector) { - return { - ruleVersionScope: "version", - latestRuleVersion: true - }; +function objectValue2(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : {}; +} +function stringValue2(value) { + return typeof value === "string" && value ? value : undefined; +} + +// src/cli/commands/delegation.ts +async function handleDelegationCommand(action, maybeName, client, corp, args) { + if (action === "list") { + await runTool("seal_delegation_list", client, corp, {}, outputOptions(args.options)); + return; } - if ("versionNumber" in selector) { - return { - ruleVersionScope: "version", - ruleVersionNumber: selector.versionNumber - }; + if (action === "create") { + const note = stringOption(args.options.note) ?? (maybeName ? [maybeName, ...args.command.slice(2)].join(" ") : undefined); + await runTool("seal_delegation_create", client, corp, { note }, outputOptions(args.options)); + return; + } + if (action === "revoke") { + const tokenId = maybeName ?? stringOption(args.options.tokenId); + if (!tokenId) + throw new Error("Usage: seal-home delegation revoke "); + await runTool("seal_delegation_revoke", client, corp, { tokenId }, outputOptions(args.options)); + return; + } + throw new Error(`Unknown delegation command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/cli/commands/llm.ts +async function handleLlmCommand(action, client, corp, args) { + if (action === "config" || action === "get") { + await runTool("seal_llm_config_get", client, corp, {}, outputOptions(args.options)); + return; + } + if (action === "providers" || action === "list") { + await runTool("seal_llm_providers_list", client, corp, {}, outputOptions(args.options)); + return; + } + throw new Error(`Unknown llm command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/cli/commands/mcp.ts +async function handleMcpCommand(action, args) { + if (action === "config" || action === "json") { + printMcpConfig(); + return; + } + await startServer(); +} +function printMcpConfig() { + printJson({ + mcpServers: { + "seal-home": { + type: "stdio", + command: "seal-home", + args: ["mcp"], + env: { + SEAL_HOME_MCP_ENABLED: "true" + } + } + } + }); +} + +// src/cli/commands/permissions.ts +async function handlePermissionsCommand(action, client, corp, args) { + if (action === "available") { + await runTool("seal_permissions_available_list", client, corp, {}, outputOptions(args.options)); + return; + } + if (action === "configs" || action === "list") { + await runTool("seal_permissions_configs_list", client, corp, {}, outputOptions(args.options)); + return; + } + throw new Error(`Unknown permissions command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/probe.ts +async function runProbe(options = {}) { + const corps = loadCorpConfigs(); + const globalConfig2 = loadGlobalConfig(); + const corp = resolveCorpConfig(corps, { + stateful: globalConfig2.stateful, + defaultCorpId: globalConfig2.defaultCorpId, + corpId: options.corpId + }, getEnterprisesDirCandidates()); + console.log(`[probe] corp=${corp.id} source=${corp.source.type}`); + const enterprise = await resolveLiveSealEnterpriseConfig(corp); + console.log("[probe] seal enterprise"); + console.log(JSON.stringify(enterprise, null, 2)); + const client = await createSealClient(corp); + const context = await getApprovalContext(client, { + documentLimit: 20, + stylePreferencesEndpoint: corp.seal.endpoints.approvalStylePreferences + }); + console.log("[probe] approval context summary"); + console.log(JSON.stringify({ + rules: context.rules.rules.length, + hasPendingRuleDeletes: context.rules.hasPendingDeletes, + documents: context.documents.articles.length, + documentsTotal: context.documents.total, + stylePreferences: context.stylePreferences.ok ? "ok" : `error: ${context.stylePreferences.error}` + }, null, 2)); +} +if (false) {} + +// src/cli/commands/probe.ts +async function handleProbeCommand(action, maybeName, args) { + const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined); + await runProbe({ corpId }); +} + +// src/cli/commands/rules.ts +async function handleRulesCommand(action, maybeName, client, corp, args) { + if (action === "count") { + await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options)); + return; + } + if (action === "list") { + if (booleanOption(args.options.count)) { + await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options)); + return; + } + const limit = numberOption(args.options.limit); + const offset = numberOption(args.options.offset); + if (booleanOption(args.options.summary)) { + await runTool("seal_approval_rules_list", client, corp, { + fields: RULE_SUMMARY_FIELDS, + limit, + offset + }, outputOptions(args.options)); + return; + } + const result = await runToolResult("seal_approval_rules_list", client, corp, { limit, offset }); + protectLargeRuleListOutput(result, booleanOption(args.options.full) === true); + printJson(result); + return; + } + if (action === "clear") { + const confirmed = booleanOption(args.options.yes) === true; + const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed; + if (!confirmed && !dryRun) { + throw new Error("Refusing to clear rules without --yes. Use --dry-run to preview."); + } + const result = await runToolResult("seal_approval_rules_clear", client, corp, { + dryRun, + recode: booleanOption(args.options.recode) + }); + if (!confirmed && dryRun && result && typeof result === "object") { + printJson({ + ...result, + nextCommand: `seal-home rules clear --corp ${corp.id} --yes` + }, outputOptions(args.options)); + return; + } + printJson(result, outputOptions(args.options)); + return; + } + if (action === "versions") { + await runTool("seal_approval_rule_versions_list", client, corp, {}, outputOptions(args.options)); + return; + } + if (action === "version") { + const version2 = maybeName ?? stringOption(args.options.version); + if (!version2) + throw new Error("Usage: seal-home rules version "); + await runTool("seal_approval_rule_version_get", client, corp, parseRuleVersionSelector(version2), outputOptions(args.options)); + return; + } + if (action === "get") { + await runTool("seal_approval_rule_get", client, corp, { + ...ruleVersionGetOptions(stringOption(args.options.version)), + code: stringOption(args.options.code), + runtimeId: stringOption(args.options.runtimeId) ?? stringOption(args.options["runtime-id"]), + recordId: stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]) + }, outputOptions(args.options)); + return; + } + if (action === "search") { + const keyword = maybeName ?? stringOption(args.options.query); + if (!keyword) + throw new Error("Usage: seal-home rules search [--version ]"); + await runTool("seal_approval_search", client, corp, { + keywords: [keyword], + areas: ["rules"], + maxResults: numberOption(args.options.maxResults), + contextLines: numberOption(args.options.contextLines), + refresh: booleanOption(args.options.refresh), + snippetOnly: booleanOption(args.options.snippetOnly) ?? booleanOption(args.options["snippet-only"]), + maxChars: numberOption(args.options.maxChars) ?? numberOption(args.options["max-chars"]), + fields: splitOption(args.options.fields), + ...ruleVersionSearchOptions(stringOption(args.options.version)) + }, outputOptions(args.options)); + return; + } + throw new Error(`Unknown rules command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/cli/commands/service.ts +import { homedir as homedir3 } from "node:os"; +import { join as join5 } from "node:path"; + +// src/cli/service.ts +import { spawn, execFileSync } from "node:child_process"; +import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, rmSync, writeFileSync as writeFileSync5 } from "node:fs"; +import { join as join4 } from "node:path"; +async function runServiceCommand(action, config2, options = {}) { + switch (action) { + case "run": + await runService(config2); + return; + case "start": + return startService(config2); + case "stop": + return stopService(config2, options); + case "restart": + stopService(config2, { quiet: true }); + return startService(config2); + case "status": + case undefined: + return serviceStatus(config2); + default: + throw new Error("Usage: seal-home service "); + } +} +function serviceStatus(config2) { + const pidFile = getPidFile(config2); + const pid = readServicePid(pidFile); + const running = pid ? isSealHomeProcess(pid, config2.appRoot) : false; + if (pid && !running) { + rmSync(pidFile, { force: true }); } return { - ruleVersionScope: "version", - ruleVersionId: selector.versionId + running, + pid: running ? pid : undefined, + version: config2.version, + appRoot: config2.appRoot, + stateDir: config2.stateDir, + pidFile, + logFile: getLogFile(config2) }; } -function ruleVersionContextOptions(value) { - if (!value) - return {}; - const selector = parseRuleVersionSelector(value); - if ("latest" in selector) { - return { latestRuleVersion: true }; - } - if ("versionNumber" in selector) { - return { ruleVersionNumber: selector.versionNumber }; - } - return { ruleVersionId: selector.versionId }; -} -function ruleVersionGetOptions(value) { - if (!value) - return {}; - const selector = parseRuleVersionSelector(value); - if ("latest" in selector) { - return { latest: true }; - } - if ("versionNumber" in selector) { - return { versionNumber: selector.versionNumber }; - } - return { versionId: selector.versionId }; -} -function parseArgs(argv) { - const command = []; - const options = {}; - let json2; - for (let index = 0;index < argv.length; index += 1) { - const arg = argv[index]; - if (!arg) - continue; - if (arg === "--json") { - const raw = argv[index + 1]; - if (!raw) - throw new Error("--json requires a JSON object argument"); - json2 = JSON.parse(raw); - index += 1; - continue; +async function runService(config2) { + const pidFile = getPidFile(config2); + const logFile = getLogFile(config2); + ensureStateDir(config2.stateDir); + writeFileSync5(pidFile, `${process.pid} +`, { mode: 384 }); + appendLog(logFile, `running pid=${process.pid}`); + const cleanup = () => { + if (readServicePid(pidFile) === process.pid) { + rmSync(pidFile, { force: true }); } - if (arg.startsWith("-")) { - const key = arg.replace(/^-+/, ""); - const next = argv[index + 1]; - if (!next || next.startsWith("-")) { - options[key] = true; - } else { - options[key] = next; - index += 1; - } - continue; - } - command.push(arg); - } - return { command, options, json: json2 }; -} -function jsonObject(value) { - if (value === undefined) - return {}; - if (!value || typeof value !== "object" || Array.isArray(value)) { - throw new Error("--json must be an object"); - } - return value; -} -function stringOption(value) { - return typeof value === "string" ? value : undefined; -} -function numberOption(value) { - if (typeof value !== "string") - return; - const number5 = Number(value); - if (!Number.isFinite(number5)) - throw new Error(`Invalid number: ${value}`); - return number5; -} -function splitOption(value) { - if (typeof value !== "string") - return; - const items = value.split(",").map((item) => item.trim()).filter(Boolean); - return items.length ? items : undefined; -} -function parseWebhookMode(value) { - if (!value) - return; - const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_"); - const aliases = { - assisted: "assisted", - 辅助: "assisted", - semi_automatic: "semi_automatic", - 半自动: "semi_automatic", - fully_automatic: "fully_automatic", - 全自动: "fully_automatic" + appendLog(logFile, `stopped pid=${process.pid}`); }; - const mode = aliases[normalized]; - if (!mode) { - throw new Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic"); + await new Promise((resolve) => { + let stopped = false; + const heartbeat = setInterval(() => {}, 60000); + const stop2 = () => { + if (stopped) + return; + stopped = true; + cleanup(); + clearInterval(heartbeat); + process.off("SIGTERM", stop2); + process.off("SIGINT", stop2); + resolve(); + }; + process.once("SIGTERM", stop2); + process.once("SIGINT", stop2); + }); +} +function startService(config2) { + ensureStateDir(config2.stateDir); + const current = serviceStatus(config2); + if (current.running) { + return current; } - return mode; + const launcher = config2.launcher ?? { command: process.execPath, args: [config2.entryFile] }; + const child = spawn(launcher.command, [ + ...launcher.args ?? [], + "service", + "run" + ], { + cwd: config2.appRoot, + detached: true, + stdio: ["ignore", "ignore", "ignore"], + env: process.env + }); + child.unref(); + const pidFile = getPidFile(config2); + writeFileSync5(pidFile, `${child.pid} +`, { mode: 384 }); + appendLog(getLogFile(config2), `started pid=${child.pid}`); + return { started: true, ...serviceStatus(config2) }; } -function webhookRateOption(options) { - const value = numberOption(options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"]); - if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) { - throw new Error("Webhook auto approval rate must be an integer between 0 and 100"); +function stopService(config2, options = {}) { + const pidFile = getPidFile(config2); + const pid = readServicePid(pidFile); + if (!pid || !isSealHomeProcess(pid, config2.appRoot)) { + rmSync(pidFile, { force: true }); + return options.quiet ? undefined : { stopped: false, reason: "not running" }; } - return value; + process.kill(pid, "SIGTERM"); + rmSync(pidFile, { force: true }); + appendLog(getLogFile(config2), `stop requested pid=${pid}`); + return options.quiet ? undefined : { stopped: true, pid }; } -function webhookShowSecretOption(options) { - return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]); -} -function booleanOption(value) { - if (value === undefined) - return; - if (typeof value === "boolean") - return value; - if (value === "true") - return true; - if (value === "false") +function isSealHomeProcess(pid, appRoot) { + if (!isProcessRunning(pid)) return false; - throw new Error(`Invalid boolean: ${value}`); + try { + const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" }); + const matchesTarget = command.includes(appRoot) || command.includes("seal-home") || command.includes("src/cli.ts"); + return matchesTarget && command.includes("service") && command.includes("run"); + } catch { + return false; + } } -function printJson(value, options = {}) { - protectLargeOutput(value, options); - const json2 = `${JSON.stringify(value, null, 2)} -`; - if (options.outputFile) { - writeFileSync4(options.outputFile, json2); - console.log(JSON.stringify({ outputFile: options.outputFile, bytes: Buffer.byteLength(json2, "utf-8") }, null, 2)); +function isProcessRunning(pid) { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} +function getPidFile(config2) { + return join4(config2.stateDir, "service.pid"); +} +function getLogFile(config2) { + return join4(config2.stateDir, "service.log"); +} +function readServicePid(path) { + if (!existsSync4(path)) + return; + const pid = Number(readFileSync4(path, "utf8").trim()); + return Number.isInteger(pid) && pid > 0 ? pid : undefined; +} +function ensureStateDir(stateDir) { + mkdirSync4(stateDir, { recursive: true, mode: 448 }); +} +function appendLog(path, message) { + writeFileSync5(path, `${new Date().toISOString()} ${message} +`, { flag: "a", mode: 384 }); +} + +// src/cli/commands/service.ts +var STATE_DIR = join5(homedir3(), ".config", "seal-home"); +async function handleServiceCommand(action, runtime) { + const result = await runServiceCommand(action, { + appRoot: runtime.appRoot, + entryFile: runtime.entryFile, + stateDir: STATE_DIR, + version: VERSION, + launcher: runtime.launcher + }); + if (result !== undefined) + printJson(result); +} + +// src/cli/commands/simulation.ts +import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs"; +async function handleSimulationCommand(action, maybeName, client, corp, args) { + if (action === "batch-records") { + const batchId = maybeName ?? stringOption(args.options.batchId); + if (!batchId) + throw new Error("Usage: seal-home simulation batch-records "); + await runTool("seal_simulation_batch_records_get", client, corp, { + batchId, + query: stringOption(args.options.query) + }, outputOptions(args.options)); return; } - console.log(json2.trimEnd()); + if (action === "create") { + const modeArg = stringOption(args.options.mode) ?? "hosecloud"; + const mode = modeArg === "material-pack" ? "material_pack" : modeArg; + const schemaConfigPath = stringOption(args.options.schemaConfig) ?? stringOption(args.options["schema-config"]); + const schemaConfig = schemaConfigPath ? JSON.parse(readFileSync5(schemaConfigPath, "utf8")) : undefined; + await runTool("seal_simulation_batch_create", client, corp, { + mode, + flowIds: splitOption(args.options.flowIds) ?? splitOption(args.options["flow-ids"]), + rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null, + thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]), + skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]), + skipExpenseExtraction: booleanOption(args.options.skipExpenseExtraction) ?? booleanOption(args.options["skip-expense-extraction"]), + disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]), + signKey: stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]), + packageIds: splitOption(args.options.packageIds) ?? splitOption(args.options["package-ids"]), + templateId: stringOption(args.options.templateId) ?? stringOption(args.options["template-id"]), + schemaConfig, + rawParams: jsonObject(args.json) + }, outputOptions(args.options)); + return; + } + if (action === "list") { + await runTool("seal_simulation_batches_list", client, corp, { + limit: numberOption(args.options.limit) + }, outputOptions(args.options)); + return; + } + if (action === "get") { + const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]); + if (!batchId) + throw new Error("Usage: seal-home simulation get "); + await runTool("seal_simulation_batch_get", client, corp, { batchId }, outputOptions(args.options)); + return; + } + if (action === "templates") { + await runTool("seal_simulation_templates_get", client, corp, {}, outputOptions(args.options)); + return; + } + if (action === "integrations") { + await runTool("seal_simulation_integrations_get", client, corp, {}, outputOptions(args.options)); + return; + } + if (action === "package-upload") { + const filePath = maybeName ?? stringOption(args.options.file); + if (!filePath) + throw new Error("Usage: seal-home simulation package-upload <材料包.zip>"); + if (!existsSync5(filePath)) + throw new Error(`File not found: ${filePath}`); + await runTool("seal_simulation_material_package_upload", client, corp, { filePath }, outputOptions(args.options)); + return; + } + throw new Error(`Unknown simulation command: ${action ?? ""}. Run 'seal-home help' for available commands.`); } -function printHelp() { - console.log(`seal-home CLI -Usage: - seal-home version - seal-home config paths - seal-home config get - seal-home config mode [--corp ] - seal-home service - seal-home update - seal-home tools list - seal-home corps list [--corp ] - seal-home corps current [--corp ] - seal-home corps switch - seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' - seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' - seal-home auth diagnose [--corp ] - seal-home auth hose-link [--corp ] [--expire 7200] - seal-home delegation list [--corp ] - seal-home delegation create [--note ] [--corp ] - seal-home delegation revoke [--corp ] - seal-home users create --name --phone [--dept ] [--corp ] - seal-home users search [--corp ] - seal-home users delegation [--note ] [--corp ] - seal-home users reset-password [--corp ] - seal-home users get [--corp ] - seal-home users delete [--corp ] - seal-home llm config [--corp ] - seal-home llm providers [--corp ] - seal-home permissions available [--corp ] - seal-home permissions configs [--corp ] - seal-home billing status [--corp ] - seal-home billing plans [--corp ] - seal-home billing features [--corp ] - seal-home webhook list [--query ] [--show-secret] [--corp ] - seal-home webhook get|find [--show-secret] [--corp ] - seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ] - seal-home webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ] - seal-home webhook delete --yes [--corp ] - seal-home source config [--corp ] - seal-home tool [--corp ] [--json '{"key":"value"}'] - seal-home rules count [--corp ] - seal-home rules list [--summary] [--count] [--limit 20] [--offset 0] [--corp ] - seal-home rules clear [--corp ] [--dry-run|--yes] - seal-home rules versions [--corp ] - seal-home rules version [--corp ] - seal-home rules get --corp --version --code '#0038' - seal-home rules get --corp --record-id --runtime-id rule-205 - seal-home rules search [--version ] [--maxResults 20] [--corp ] - seal-home context [--ruleVersion ] [--documentLimit 50] [--corp ] - seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp ] - seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp ] - seal-home approval-runs pick --sn [--batch ] [--latest] [--fields recordId,status,aiDecision] [--corp ] - seal-home approval-runs get [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp ] - seal-home approval-runs cited-rules [--corp ] - seal-home approval-runs document-summary [--corp ] - seal-home approval-runs attachments [--summary] [--corp ] - seal-home approval-runs result [--summary] [--corp ] - seal-home approval-runs url [--corp ] - seal-home approval-runs url [--corp ] - seal-home approval-runs url --sourceDocumentSN B26022501 [--corp ] - seal-home approval-runs bridge [--sourceDocumentSN B26001887] [--corp ] - seal-home simulation batch-records [--corp ] - seal-home simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp ] - seal-home simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp ] - seal-home simulation list [--limit 50] [--corp ] - seal-home simulation get [--corp ] - seal-home simulation templates [--corp ] - seal-home simulation integrations [--corp ] - seal-home simulation package-upload <材料包.zip> [--corp ] -`); -} -function formatConsoleOutput(values) { - return values.map((value) => typeof value === "string" ? value : String(value)).join(" "); -} -function joinOutput(lines) { - if (!lines.length) - return ""; - return `${lines.join(` -`)} +// src/cli/commands/skill.ts +import { existsSync as existsSync7 } from "node:fs"; +import { join as join7 } from "node:path"; + +// src/core/embedded-skill.ts +import { existsSync as existsSync6, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6 } from "node:fs"; +import { homedir as homedir4 } from "node:os"; +import { dirname as dirname3, join as join6 } from "node:path"; + +// skills/seal-home/SKILL.md +var SKILL_default = `--- +name: seal-home +description: "v0.7.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search." +metadata: + version: 0.7.0 + short-description: Seal tenant and Hose approval automation (v0.7.0) +--- + +# Seal Home (v0.7.0) + +Use the \`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-home\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail. + +\`\`\`bash +seal-home help +seal-home version +seal-home tools list +\`\`\` + +## First Rules + +- Prefer compact commands first: \`pick\`, \`--summary\`, \`--fields\`, \`attachments --summary\`, \`rules count\`, and \`rules list --summary\`. +- Parse JSON stdout. Do not scrape human text. +- Do not hand-edit enterprise configs for normal setup. Use \`seal-home corps ...\`. +- Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For repeat test-environment rule resets, prefer \`rules clear --dry-run\` followed by \`rules clear --yes\`. +- For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of \`description\`; preserve \`scope\`, \`strictness\`, and unrelated clauses unless the user explicitly approves otherwise. +- Resolve and lock the target enterprise \`corpId\` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing. +- For date questions, use explicit dates and \`--timezone Asia/Shanghai\`. +- If output may be large, use \`--summary\`, \`--fields\`, \`--count\`, or \`--output-file\`; use \`--full\` only when the user really needs full payloads. +- When returning ANY authorization, login, or delegation links (e.g. 合思授权链接, Seal授权链接/委托链接), ALWAYS provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) for easy copying without accidental default browser redirection, AND a clickable hyperlink. +- For delegation links, always prefer \`seal-home delegation create\` over \`users delegation\` for link generation to ensure persistent token tracking. +- Never treat “Seal 协助/Seal 授权/委托” as a 合思授权入口. They are different links and must use different commands. +- In the default stateless mode, every enterprise command requires \`--corp \`. In stateful mode, omitting \`--corp\` uses the configured default enterprise and is unsafe for an explicitly named enterprise. +- For an explicitly named enterprise, first resolve it with \`seal-home corps list\`, then pass its exact \`corpId\` to every command. After creation, verify the returned URL host matches that enterprise's Seal tenant; if the host is the current/default tenant or cannot be verified, do not present the link as the target enterprise's link. + +## Route By Intent + +- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run \`seal-home delegation create --corp --note ''\`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink. +- Packaged customer feedback → approval-rule remediation: read \`references/customer-feedback-rule-remediation.md\`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version. +- 模拟测试发布闭环: \`seal-home simulation create --mode hosecloud --flow-ids ... --corp \` (合思指定单号) 或 \`--mode material_pack --package-ids ... --schema-config file.json\` (材料包导入), 创建后 \`simulation list\`/\`get\`/\`batch-records\` 轮询批次与记录; 其他取数模式通过 \`--json\` 透传预留。创建前确认目标环境为测试环境。 +- User-facing 合思 authorization link (合思/易快报授权): \`seal-home auth hose-link --corp --expire 7200\`; read \`references/hose-enterprise-auth.md\`. Never use this route when the user says Seal 协助. Always provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) AND a hyperlink. +- Delegation links management: \`seal-home delegation list --corp \`, \`create [--note ...] --corp \`, \`revoke --corp \`. +- User & Contacts Management (用户搜索、激活与一键代生成授权): \`seal-home users search [keyword] --corp \`, \`users delegation --corp \` (仅适用于 Seal 本地创建的账号 \`provider: local\`;对合思同步账号系统拒绝重置密码,需改用 \`auth hose-link\`), \`users activate --corp \`, \`users create --name ... --phone ... --corp \`, \`reset-password --corp \`, \`get --corp \`, \`delete --corp \`. +- LLM Model Config & Providers: \`seal-home llm config --corp \`, \`seal-home llm providers --corp \`. +- System Permissions Config: \`seal-home permissions available --corp \`, \`seal-home permissions configs --corp \`. +- Billing & Feature Quotas: \`seal-home billing status --corp \`, \`seal-home billing plans --corp \`, \`seal-home billing features --corp \`. +- Full CLI inventory: read \`references/cli.md\`. + +## High-Value Commands + +\`\`\`bash +seal-home approval-runs pick --corp --sn --latest +seal-home approval-runs pick --corp --sn --batch --latest --fields recordId,status,aiDecision,aiSummary +seal-home approval-runs get --corp --summary +seal-home approval-runs get --corp --fields metadata,document.fields,result.summary +seal-home approval-runs document-summary --corp +seal-home approval-runs cited-rules --corp +seal-home approval-runs attachments --corp --summary +seal-home approval-runs result --corp --summary +seal-home rules count --corp +seal-home rules list --corp --summary +seal-home rules clear --corp --dry-run +seal-home rules clear --corp --yes +seal-home rules get --corp --version 16 --code '#0038' +seal-home rules get --corp --record-id --runtime-id rule-205 +seal-home simulation create --corp --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] +seal-home simulation create --corp --mode material_pack --package-ids [--schema-config file.json] +seal-home simulation package-upload <材料包.zip> --corp +seal-home simulation list --corp +seal-home simulation get --corp +seal-home simulation batch-records --corp +seal-home tool seal_approval_search --corp --json '{"keywords":["差旅","发票"],"areas":["rules"],"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}' +\`\`\` + +## Important Fields + +- \`sourceDocumentSN\`: external document number, often the easiest 合思/易快报 lookup key. +- \`sourceDocumentId\`: external source document ID. +- \`recordId\`: Seal approval run record ID. +- \`simulationBatchId\`: simulation batch identifier. +- \`status\`: run status. +- \`taskMode\` / \`finalExecutionMode\`: execution mode information. +- \`ruleSetVersionNumber\`: approval rule version used by a run. +- \`langfuseTraceId\`: direct Langfuse trace lookup key. +- \`langfuseSessionFallback\`: fallback session key, usually \`hosecloud-{sourceDocumentSN}\`. + +## References + +- \`references/approval-run-lightweight.md\`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。 +- \`references/rule-lightweight.md\`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。 +- \`references/customer-feedback-rule-remediation.md\`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。 +- \`references/hose-enterprise-auth.md\`: Hose 企业配置、认证诊断、授权链接。 +- \`references/approval-attachment-trace.md\`: 附件/发票/OCR/图片争议的 Langfuse 追踪工作流。 +- \`references/cli.md\`: 完整 CLI 命令清单。 + +## Safety + +Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real \`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export. `; + +// skills/seal-home/agents/openai.yaml +var openai_default = `interface: + display_name: "Seal Home" + short_description: "Diagnose approval feedback and publish minimal rule fixes" + default_prompt: "Use $seal-home to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation." +`; + +// skills/seal-home/references/rule-lightweight.md +var rule_lightweight_default = `# Rule Lightweight Queries + +Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions. + +## Count Rules + +Use count when only scale or existence matters. + +\`\`\`bash +seal-home rules count --corp +\`\`\` + +Expected shape: + +\`\`\`json +{ "count": 191 } +\`\`\` + +Tool-layer equivalent: + +\`\`\`bash +seal-home tool seal_approval_rules_list --corp --json '{"countOnly":true}' +seal-home tool seal_approval_rules_list --corp --json '{"fields":["id"],"limit":0}' +\`\`\` + +## List Rule Summaries + +Use summaries for navigation and selection. + +\`\`\`bash +seal-home rules list --corp --summary +\`\`\` + +Default summary should include only fields such as \`id\`, \`code\`, \`scope\`, \`strictness\`, \`status\`, and \`updatedAt\`. Do not pull \`description\` unless the user needs rule text. + +Tool-layer equivalent: + +\`\`\`bash +seal-home tool seal_approval_rules_list --corp --json '{"fields":["id","code","scope","strictness","status","updatedAt"]}' +\`\`\` + +## Clear Draft Rules Before Import + +Use this for test tenants when the next step is importing another tenant's rule set. Always preview first unless the user has already confirmed the exact tenant. + +\`\`\`bash +seal-home rules clear --corp --dry-run +seal-home rules clear --corp --yes +\`\`\` + +Expected shape: + +\`\`\`json +{ + "corpId": "xiezihao", + "dryRun": false, + "beforeCount": 49, + "deleted": 49, + "afterCount": 0 } -function redactSensitiveText(value) { - return value.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi, "$1").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1"); +\`\`\` + +Tool-layer equivalent: + +\`\`\`bash +seal-home tool seal_approval_rules_clear --corp --json '{"dryRun":true}' +seal-home tool seal_approval_rules_clear --corp --json '{"dryRun":false}' +\`\`\` + +## Get One Historical Rule + +Use this when a run used a historical rule version and current rules may differ. + +\`\`\`bash +seal-home rules get --corp --version 16 --code '#0038' +seal-home rules get --corp --version latest --code '#0038' +\`\`\` + +If the user starts from a run and a runtime ID such as \`rule-205\`, resolve against that run: + +\`\`\`bash +seal-home rules get --corp --record-id --runtime-id rule-205 +\`\`\` + +Return the single rule text plus \`scope\`, \`strictness\`, \`status\`, \`versionNumber\`, and version metadata. Avoid commands that dump a whole rule version unless the user asks for the full version. + +## Search Approval Knowledge Compactly + +Prefer scoped and trimmed search: + +\`\`\`bash +seal-home tool seal_approval_search --corp --json '{"keywords":["关键词"],"areas":["rules"],"matchMode":"any","maxResults":20,"snippetOnly":true,"maxChars":500,"fields":["id","title","snippet"]}' +\`\`\` + +When investigating historical behavior, search the matching rule version if the API supports it: + +\`\`\`bash +seal-home tool seal_approval_search --corp --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","versionNumber":16,"snippetOnly":true,"maxChars":500}' +\`\`\` + +Use current search only when the question is about current draft/current knowledge, not why a historical run behaved a certain way. + +## Output Discipline + +If a rule command would return many descriptions or more than about 20 rules, use \`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports. +`; + +// skills/seal-home/references/approval-bad-cases.md +var approval_bad_cases_default = `# Approval Bad Case Catalog + +Use this file only as a comparison catalog after inspecting the current trace. Do not treat any case below as a default diagnosis. + +## Case A: Receipt-Like Attachments Labeled As Invoices + +Symptom: + +- UI finding said attachments contained fixed-amount invoices that were not uploaded to the invoice field. +- Customer said the 160 and 90 slips were receipts, not invoices. + +Failure pattern: + +- Raw attachment objects and invoice-list objects had similar names/content but different IDs. +- \`image_understanding\` first introduced loose or wrong labels such as "发票(或收据)" and "定额发票". +- \`document_parsing\` inherited those labels. +- \`approval_review\` converted the inherited labels into a rule finding. + +Checklist: + +- Compare raw attachment IDs and invoice-list IDs before making a claim. +- Inspect the original image for formal invoice elements. +- If the image lacks invoice title, tax supervision seal, invoice code/number, and tax fields, the customer's receipt interpretation may be reasonable. + +## Case B: Payment Amount Passed Earlier, Then Excluded Later + +Symptom: + +- UI finding said payment screenshots totaled only 1550 (\`650+900\`) against reimbursement amount 3400. +- Customer said the 1850 screenshot was also a payment-support screenshot and should have been included. + +Failure pattern: + +- The same six images appeared twice: under fee-detail attachments (\`file-1\` to \`file-6\`) and form-level attachments (\`file-7\` to \`file-12\`). +- \`image_understanding\` did not lose the 1850 amount; it extracted \`1850.00\`. +- \`pre_analysis\` explicitly passed 1850 as a payment-screenshot amount candidate in a review point: "付款截图金额(1850.00元)". +- \`document_parsing\` later reclassified \`1850.jpg\` as "收款凭证,非付款截图", overriding the review-point premise. +- Duplicate \`900.jpg\` entries produced inconsistent parser conclusions; final review included 900 but excluded 1850. + +Checklist: + +- If an amount is missing from the final total, check whether it was recognized in \`image_understanding\`. +- If recognized, check whether \`pre_analysis\` passed it in \`attachmentInstructions.reviewPoints\`. +- If passed, check whether \`document_parsing\` ignored or reclassified it. +- If the same image appears under multiple \`fileId\`s, compare duplicate conclusions before trusting final aggregation. + +Important nuance: + +- This is a bad-case pattern, not a general rule that every amount-total dispute is caused by \`pre_analysis\`. +- Use it when the current trace shows recognized amounts being excluded downstream or duplicate attachments producing inconsistent conclusions. +`; + +// skills/seal-home/references/cli.md +var cli_default = `# Seal Home CLI Reference + +Run from any directory after installing the global CLI: + +\`\`\`bash +seal-home +\`\`\` + +Enterprise config lookup: + +- If \`SEAL_HOME_ENTERPRISES_DIR\` is set, only that directory is loaded. +- Otherwise \`./enterprises\` and \`~/.config/seal-home/enterprises\` are merged. +- User-level configs override same-ID local configs. + +Enterprise selection is stateless by default. Commands that access an enterprise require +\`--corp \` unless stateful mode is explicitly enabled: + +\`\`\`bash +seal-home config mode stateful --corp +seal-home corps switch +seal-home config mode stateless +\`\`\` + +The global mode is stored in \`~/.config/seal-home/config.json\`; set \`SEAL_HOME_CONFIG_FILE\` to +override that path. The legacy \`current-corp\` file is not read. + +## Top-Level Commands + +\`\`\`bash +seal-home version +seal-home config paths +seal-home config get +seal-home config mode [--corp ] +seal-home service +seal-home update +seal-home tools list +seal-home corps list [--corp ] +seal-home corps current [--corp ] +seal-home corps switch +seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' +seal-home corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}' +seal-home auth diagnose [--corp ] +seal-home auth hose-link [--corp ] [--expire 7200] +seal-home delegation list [--corp ] +seal-home delegation create [--note ] [--corp ] +seal-home delegation revoke [--corp ] +seal-home users create --name --phone [--dept ] [--corp ] +seal-home users reset-password [--corp ] +seal-home users get [--corp ] +seal-home users delete [--corp ] +seal-home llm config [--corp ] +seal-home llm providers [--corp ] +seal-home permissions available [--corp ] +seal-home permissions configs [--corp ] +seal-home billing status [--corp ] +seal-home billing plans [--corp ] +seal-home billing features [--corp ] +seal-home webhook list [--query ] [--show-secret] [--corp ] +seal-home webhook get|find [--show-secret] [--corp ] +seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ] +seal-home webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ] +seal-home webhook delete --yes [--corp ] +seal-home source config [--corp ] +seal-home tool [--corp ] [--json '{"key":"value"}'] +seal-home approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai] +seal-home approval-runs search --corp [--query text] [--limit 20] [--includeBridge true] +seal-home approval-runs get --corp [--fields metadata|document.fields,result.summary] [--output-file file.json] +seal-home approval-runs attachments --corp +seal-home approval-runs result --corp [--summary] +seal-home approval-runs url --corp +seal-home approval-runs url --corp +seal-home approval-runs url --sourceDocumentSN --corp +seal-home approval-runs bridge --corp [--sourceDocumentSN ] +seal-home simulation batch-records --corp +seal-home simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp +seal-home simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp +seal-home simulation list [--limit 50] --corp +seal-home simulation get --corp +seal-home simulation templates --corp +seal-home simulation integrations --corp +seal-home simulation package-upload <材料包.zip> --corp +\`\`\` + +## Fine-Grained Tools + +\`seal-home version\` returns: + +\`\`\`json +{ + "name": "seal-home", + "version": "" +} +\`\`\` + +\`seal-home service status\` returns the PID, version, state directory, PID file, and log file for the optional local background process. + +\`seal-home update\` updates the git checkout, runs \`bun install\`, and restarts the local service if it was running. + +Identity and session: + +- \`seal-home auth diagnose --corp \` +- \`seal_whoami\` +- \`seal_session_get\` + +Approval rule maintenance: + +- \`seal-home rules count [--corp ]\` +- \`seal-home rules list --summary [--corp ]\` +- \`seal-home rules clear [--corp ] [--dry-run|--yes]\` +- \`seal_approval_rules_list\` +- \`seal_approval_rules_clear\` +- \`seal_approval_rule_create\` +- \`seal_approval_rule_update\` +- \`seal_approval_rule_delete\` +- \`seal_approval_rule_versions_list\` +- \`seal_approval_rule_version_publish\` + +Approval run lightweight queries: + +- \`seal-home approval-runs get --corp --fields metadata\` +- \`seal-home approval-runs get --corp --summary\` +- \`seal-home approval-runs pick --corp --sn <单号> --batch --latest\` +- \`seal-home approval-runs document-summary --corp \` +- \`seal-home approval-runs cited-rules --corp \` +- \`seal-home approval-runs get --corp --fields document.fields,result.summary\` +- \`seal-home approval-runs attachments --corp --summary\` +- \`seal-home approval-runs result --corp --summary\` +- \`seal_approval_run_get\` with \`fields\` +- \`seal_approval_run_pick\` +- \`seal_approval_run_cited_rules_get\` +- \`seal_approval_run_document_summary_get\` +- \`seal_approval_run_attachments_get\` +- \`seal_approval_run_result_get\` with \`{"summary":true}\` + +Approval knowledge documents: + +- \`seal_approval_documents_list\` +- \`seal_approval_document_get\` +- \`seal_approval_document_create\` +- \`seal_approval_document_update\` + +Approval search and context: + +- \`seal_approval_search\` +- \`seal_approval_context_get\` +- \`seal-home rules get --corp --version --code '#0038'\` +- \`seal-home rules get --corp --record-id --runtime-id rule-205\` + +Style preferences: + +- \`seal_approval_style_preferences_get\` +- \`seal_approval_style_preferences_update\` + +Webhook integrations: + +- \`seal-home webhook list [--query ] [--show-secret] [--corp ]\` +- \`seal-home webhook get|find [--show-secret] [--corp ]\` +- \`seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ]\` +- \`seal-home webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ]\` +- \`seal-home webhook delete --yes [--corp ]\` +- \`seal_webhook_list\` +- \`seal_webhook_get\` +- \`seal_webhook_add\` +- \`seal_webhook_update\` +- \`seal_webhook_delete\` + +Webhook writes read the current AI approval config and POST the merged full config back to \`api/v1/agent/ai-approval/config\`, preserving non-Webhook integrations. List/get mask \`secret\` by default; add returns the generated secret once. + +Approval runs, simulations, and Langfuse bridge: + +- \`seal_approval_runs_search\` +- \`seal_approval_runs_summary\` +- \`seal_simulation_batch_records_get\` +- \`seal_simulation_batch_create\` +- \`seal_simulation_batches_list\` +- \`seal_simulation_batch_get\` +- \`seal_simulation_templates_get\` +- \`seal_simulation_integrations_get\` +- \`seal_approval_run_langfuse_bridge_get\` + +## Common Examples + +Add and verify a Hose enterprise: + +\`\`\`bash +seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' +seal-home auth diagnose --corp +\`\`\` + +Force-write a Hose config without verification: + +\`\`\`bash +seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId","force":true}' +\`\`\` + +Diagnose auth failures: + +\`\`\`bash +seal-home auth diagnose --corp +\`\`\` + +The diagnostic stages are \`hose.openapi\`, \`hose.provisional\`, \`seal.sso\`, and \`seal.whoami\`. Tokens are omitted from output. + +Search approval content: + +\`\`\`bash +seal-home tool seal_approval_search --corp --json '{"keywords":["关键词"],"matchMode":"any","maxResults":20}' +\`\`\` + +Get aggregated approval context: + +\`\`\`bash +seal-home tool seal_approval_context_get --corp --json '{"documentLimit":20}' +\`\`\` + +Create a draft approval rule: + +\`\`\`bash +seal-home tool seal_approval_rule_create --corp --json '{"description":"规则描述","scope":"适用场景","strictness":"SHOULD_FOLLOW"}' +\`\`\` + +Update an approval document: + +\`\`\`bash +seal-home tool seal_approval_document_update --corp --json '{"documentId":"doc-id","content":"Markdown 内容"}' +\`\`\` + +Summarize one local date: + +\`\`\`bash +seal-home approval-runs summary --corp --date 2026-06-09 --timezone Asia/Shanghai --limit 100 +\`\`\` + +Find a run and include Langfuse bridge rows: + +\`\`\`bash +seal-home approval-runs search --corp --query --limit 20 --includeBridge true +\`\`\` + +Resolve Langfuse trace/session hints: + +\`\`\`bash +seal-home approval-runs bridge --corp --sourceDocumentSN +\`\`\` + +模拟测试批次(模拟发布闭环)创建与查询: + +\`\`\`bash +# 合思指定单号: 创建批次(响应只含 batchId) +seal-home simulation create --mode hosecloud --flow-ids "B26017701,B26022501" --reject-node 财务 --thinking-depth medium --skip-invoice-generation --corp +# 材料包导入: 先上传材料包 ZIP(服务端解析并返回 schemaConfig), 再用返回的 id 发起 +seal-home simulation package-upload 测试材料包.zip --corp +seal-home simulation create --mode material_pack --package-ids --template-id conference_reimbursement_v1 --schema-config schema.json --corp +# 预留: 其他模式参数通过 --json 透传(如时间范围 startTime/endTime) +seal-home simulation create --mode hosecloud --flow-ids "B26017701" --json '{"startTime":0,"endTime":0}' --corp +# 创建后轮询批次状态与记录 +seal-home simulation list --limit 50 --corp +seal-home simulation get --corp +seal-home simulation batch-records --corp +seal-home simulation templates --corp +seal-home simulation integrations --corp +\`\`\` + +## Write Operation Payloads + +Create a rule: + +\`\`\`json +{ + "description": "规则描述", + "scope": "适用场景", + "strictness": "MUST_FOLLOW | SHOULD_FOLLOW | SUGGESTION" +} +\`\`\` + +Update a rule: + +\`\`\`json +{ + "ruleId": "rule-id", + "description": "可选", + "scope": "可选", + "strictness": "SHOULD_FOLLOW" +} +\`\`\` + +Publish a rule version: + +\`\`\`json +{ + "versionName": "版本名称" +} +\`\`\` + +Create a document: + +\`\`\`json +{ + "title": "标题", + "purpose": "用途", + "content": "Markdown 内容", + "contentType": "text/markdown", + "status": "可选", + "scenarios": ["场景"], + "tags": ["标签"] +} +\`\`\` + +Update a document: + +\`\`\`json +{ + "documentId": "doc-id", + "title": "可选", + "purpose": "可选", + "content": "可选", + "enabled": true, + "scenarios": ["可选"], + "tags": ["可选"] +} +\`\`\` + +Update style preferences: + +\`\`\`json +{ + "tone": "可选", + "language": "可选", + "detailLevel": "可选", + "outputFormat": "可选", + "examples": ["可选"], + "prohibitedPhrases": ["可选"], + "customInstructions": "可选" +} +\`\`\` + +## Failure Handling + +- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use \`seal-home service restart\` after updates so the optional local service picks up new code. +- If no run is found by \`sourceDocumentSN\`, retry with \`sourceDocumentId\` or a broader \`query\`. +- If date-based summaries look wrong, pass \`--timezone Asia/Shanghai\` and an explicit \`--date\`. +- If \`langfuseTraceId\` is missing, use \`langfuseSessionFallback\`. +- If a write operation fails, report the raw JSON error and do not retry with guessed payloads. +`; + +// skills/seal-home/references/approval-run-lightweight.md +var approval_run_lightweight_default = "# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-home approval-runs pick --corp --sn --latest\nseal-home approval-runs pick --corp --sn --batch --latest\nseal-home approval-runs pick --corp --sn --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-home approval-runs get --corp --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-home approval-runs get --corp --fields metadata\nseal-home approval-runs get --corp --fields document.fields,result.summary\nseal-home approval-runs get --corp --fields result.summary,result.decision,result.riskPoints\nseal-home approval-runs get --corp --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get ` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-home approval-runs document-summary --corp \n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-home approval-runs cited-rules --corp \n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\nseal-home approval-runs attachments --corp --summary\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-home approval-runs result --corp --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n"; + +// skills/seal-home/references/approval-attachment-trace.md +var approval_attachment_trace_default = `# Approval Attachment Trace Investigation + +Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result. + +The goal is to locate where an imprecise claim first entered the pipeline. Do not jump directly from the final approval result to a rule change. Many issues start earlier in the attachment understanding or attachment review stages. + +## Mental Model + +Approval traces commonly contain these stages: + +1. Source document rendering + - Seal converts the approval document into the Markdown-like "AI saw" document. + - This may include both structured invoice fields and raw attachment fields. +2. Rule matching + - Selects applicable rule scopes such as "存在发票或收据时" or "存在发票时". + - This stage is not the final source of attachment type judgments; it works from the rendered document. +3. Image understanding + - Vision model reads each image attachment and writes \`document_content\`. + - This is often where loose labels such as "发票(或收据)", "定额发票", "销售单", or "支付凭证" first appear. +4. Pre-analysis + - Generates \`attachmentInstructions\` and \`reviewPoints\` for later per-attachment review. + - This stage can matter when a later attachment review seems to ignore or override values already present in the generated review points. +5. Document parsing / attachment review + - A text model checks review points against the image-understanding text. + - If the review point already says "该附件(定额发票)", it usually inherited that label from the previous stage instead of independently classifying the original image. + - Check whether this stage uses values passed in the review point, or reclassifies the attachment and discards them. +6. Final approval review + - Produces \`rulesResult\`, summaries, and UI findings. + - Final findings can amplify earlier labels into business conclusions, for example "附件中存在定额发票未上传至发票栏位". + +## Commands + +Start from the Seal run and Langfuse trace. + +\`\`\`bash +seal-home approval-runs search --corp --query --limit 50 +seal-home approval-runs get --corp > /tmp/seal-run.json +seal-home approval-runs bridge --corp --sourceDocumentSN +\`\`\` + +Refresh and inspect the Langfuse trace. + +\`\`\`bash +langfuse-home call langfuse_trace_cache_refresh --json '{"traceId":""}' +langfuse-home call langfuse_trace_url_get --json '{"traceId":""}' +langfuse-home call langfuse_trace_outline_get --json '{"traceId":"","includeInput":true,"includeOutput":true,"maxPreviewChars":800}' +\`\`\` + +If \`langfuse_trace_qrep_search\` does not find Chinese terms reliably, grep the cached JSON directly. + +\`\`\`bash +rg -n "发票未上传至发票栏位|附件中存在定额发票|检查该附件(定额发票)|" \\ + .cache/langfuse/traces/default/.json +\`\`\` + +Read focused IO for the relevant observations. + +\`\`\`bash +langfuse-home call langfuse_observation_io_get --json '{"traceId":"","observationId":"","maxChars":30000}' +\`\`\` + +## Separate Object IDs Before Judging + +Never assume same-looking file names are the same object. + +In Seal run detail, invoice-list entries and raw attachment entries can be separate objects: + +- \`invoiceForm\` / \`发票列表\` entries often have source invoice IDs, invoice numbers, OCR-derived file names, \`verifyResult\`, \`fileInfo.fileType=invoice\`, and invoice metadata. +- \`attachments\` / \`附件\` entries often have UI file IDs such as \`file-7\`, Hose file IDs inside \`token\`, \`category=file\`, \`mimeType=image/jpeg\`, and their own OSS path. + +Use \`jq\` to list them side by side. + +\`\`\`bash +jq -r ' + .document.fields[] | select(.key=="details") | .value[0][] | select(.key=="invoiceForm") | .value[] | + ["invoiceForm", .sourceInvoiceId, .invoice.invoiceNumber, .invoice.fileInfo.fileName, .invoice.fileInfo.fileType, .invoice.fileInfo.ossPath, (.invoice.verifyResult.rawData | fromjson? | .form.sourceEntityId // "")] | @tsv +' /tmp/seal-run.json +\`\`\` + +\`\`\`bash +jq -r ' + .document.fields[] | select(.key=="details") | .value[0][] | select(.key=="attachments") | .value[] | + ["attachments", .fileId, .name, .category, .mimeType, .ossPath, .token] | @tsv +' /tmp/seal-run.json +\`\`\` + +When explaining the result, say precisely whether the disputed item is: + +- a structured invoice-list object, +- a raw attachment object, +- or two distinct objects with similar file names/content. + +## Find Where A Bad Label First Appeared + +Search for the UI finding text and the disputed label. + +\`\`\`bash +jq -r ' + def walkobs(o): o, ((o.children // [])[] | walkobs(.)); + .trace.observations[] | walkobs(.) + | select(((.input|tostring)+"\\n"+(.output|tostring)) + | contains("发票未上传至发票栏位") + or contains("附件中存在定额发票") + or contains("检查该附件(定额发票)")) + | [.id,.name,.type,.startTime,((.output|tostring)|gsub("\\n";" ")|.[0:500])] | @tsv +' .cache/langfuse/traces/default/.json +\`\`\` + +Then inspect the earliest matching observation. Typical interpretation: + +- \`image_understanding:ai.streamText\`: the vision stage first assigned the type label. +- \`pre_analysis:ai.streamText\`: the instruction-generation stage turned matched rules and parsed attachments into per-file \`reviewPoints\`; this is where attachment-side values or labels can be copied into prompts. +- \`document_parsing:ai.streamText\`: the attachment review inherited the label in its review point or document content. +- \`approval_review:ai.streamText\`: the final model converted inherited labels into a rule finding. + +## Check Pre-Analysis For Amount-Total Disputes + +When the customer says the AI "did not recognize the correct amount", "missed one payment screenshot", or "the total should be X", start with the normal trace: source document, image understanding, attachment review, and final review. Inspect \`pre_analysis\` when the evidence suggests the disputed amount was recognized earlier but later ignored, or when final review is aggregating inconsistent per-attachment conclusions. Treat this as a possible failure mode, not as the default cause. + +Find the node: + +\`\`\`bash +jq -r ' + def walkobs(x; depth): (x + {depth: depth}), ((x.children? // [])[] | walkobs(.; depth+1)); + .trace.observations[] | walkobs(.; 0) + | select(.name? | test("pre_analysis")) + | [.startTime,.id,.name,.type,.parentObservationId,((.input|tostring|length)//0),((.output|tostring|length)//0)] | @tsv +' .cache/langfuse/traces/default/.json +\`\`\` + +Then inspect its output for the disputed file and rule: + +\`\`\`bash +jq -r ' + def walkobs(x): x, ((x.children? // [])[] | walkobs(.)); + .trace.observations[] | walkobs(.) + | select(.name? == "pre_analysis:ai.streamText") + | .output +' .cache/langfuse/traces/default/.json | rg -n "fileId|fileName||付款截图金额|收款金额|金额合计" +\`\`\` + +Look for these failure patterns: + +- A global aggregate requirement was split into per-attachment review points, for example each attachment is asked whether its amount plus "other attachments" reaches the reimbursement amount. +- The pre-analysis prompt says not to write attachment OCR/image-understanding candidate values into review points, but the output still includes values such as "付款截图金额(1850.00元)" or labels such as "收款凭证". +- The same physical image appears twice because it exists under both form-level attachments and fee-detail attachments, producing duplicate \`fileId\`s and potentially inconsistent later judgments. +- \`pre_analysis\` passes a value down, but \`document_parsing\` reclassifies the file and ignores that value, for example a review point says "付款截图金额(1850.00元)" while the parser answer says "收款凭证,非付款截图". + +For these cases, the amount may not be lost in OCR or image understanding. It may be lost when a later attachment-review node overrides the pre-analysis task premise, or when final approval review aggregates inconsistent per-file conclusions. For concrete examples, see \`approval-bad-cases.md\`. + +## Check Images When The Dispute Is Visual + +If the issue depends on whether an image is a receipt or invoice, inspect the raw image. Do not rely only on the model's textual description. + +Extract raw attachment signed URLs from \`/tmp/seal-run.json\` and download the disputed files. + +\`\`\`bash +jq -r ' + .document.fields[] | select(.key=="details") | .value[0][] | select(.key=="attachments") | .value[] | + select(.fileId=="file-7" or .fileId=="file-9") | + [.fileId,.name,.ossSignedUrl] | @tsv +' /tmp/seal-run.json +\`\`\` + +Look for invoice-specific elements: + +- "发票" text in the title +- invoice code / invoice number +- tax bureau supervision seal +- tax invoice QR/code metadata +- buyer/seller tax information +- taxable amount / tax rate / tax amount fields + +If those are absent and the document is a store-stamped handwritten slip, it is safer to call it a receipt or sales voucher, not a formal invoice. + +## Reporting Pattern + +When answering the user, separate: + +- What the final UI finding says. +- The first pipeline stage where the disputed claim appeared. +- Whether the disputed file is a raw attachment or a structured invoice-list object. +- Whether the raw image supports the claim. +- Whether the final decision still stands for other independent reasons. + +Example wording: + +\`\`\`text +The UI finding was produced in final approval review, but the imprecise label started earlier: +image_understanding labeled file-9 as "定额发票"; document_parsing then inherited that as "该附件(定额发票)"; approval_review converted it into the rule-3 finding. + +The raw attachment object itself is not structurally marked as invoice; it is category=file, mimeType=image/jpeg. The image lacks formal invoice elements, so the customer's receipt interpretation is reasonable. +\`\`\` + +## Case Note: Receipt-Like Attachments Labeled As Invoices + +This case involved a UI finding: + +\`\`\`text +发票未上传至发票栏位:附件中存在定额发票(金额160元、90元),但未上传至发票栏位。 +\`\`\` + +Important correction: + +- \`file-7\` and \`file-9\` were raw attachment objects, not the same objects as the invoice-list entries. +- The invoice list had separate IDs (\`ID01P95oy1RWbB\`, \`ID01P95oy22hnV\`). +- The raw attachments had separate file IDs (\`file-7\` / Hose \`ID01P95CwuNGLJ\`, and \`file-9\` / Hose \`ID01P95RUC9T79\`). + +Root of imprecision: + +- \`file-7\` was first described by \`image_understanding\` as "发票(或收据)", then later attachment review used "定额发票". +- \`file-9\` was directly described by \`image_understanding\` as "定额发票". +- Final \`approval_review\` turned those inherited labels into the rule-3 UI warning. + +Manual image check: + +- The 160 and 90 slips looked like store-stamped handwritten receipts/sales vouchers. +- They lacked obvious formal invoice elements. +- The customer's objection that they were receipts rather than invoices was reasonable. + +However, the final rejection also had an independent rule-37 reason: payment screenshots totaled 699.48 while reimbursement was 700.00. +`; + +// skills/seal-home/references/customer-feedback-rule-remediation.md +var customer_feedback_rule_remediation_default = `# Customer Feedback Rule Remediation + +Use this low-freedom workflow when the user provides packaged customer feedback from WeChat, screenshots, rejection notifications, a document number, or expected business behavior and wants diagnosis or an approval-rule change. + +## Workflow states + +Follow these states in order: + +1. \`EVIDENCE_RECEIVED\` +2. \`TENANT_RESOLVED\` +3. \`RUN_RESOLVED\` +4. \`CAUSE_CLASSIFIED\` +5. \`PATCH_PROPOSED\` +6. \`PATCH_CONFIRMED\` +7. \`DRAFT_UPDATED\` +8. \`VERSION_PUBLISHED\` +9. \`VERSION_VERIFIED\` + +Stop at \`PATCH_PROPOSED\` unless the user explicitly approves the exact change and publication. A request to analyze, explain, or propose does not authorize a rule update or publish. + +## 1. Normalize the evidence package + +Extract only facts supported by the supplied package: + +- Customer or enterprise hints +- Source document number +- Submitter and document template when visible +- AI rejection or disputed finding +- Customer-stated business behavior +- Screenshots, invoices, or attachments relevant to the dispute +- Requested action: analysis, proposal, update, or publish + +Treat chat text as the customer's expected behavior, not proof of the current Seal rule or tenant identity. + +## 2. Resolve and lock the enterprise + +List configured enterprises first: + +\`\`\`bash +seal-home corps list +\`\`\` + +If the enterprise is named, resolve its exact \`corpId\`. If the enterprise is unclear but a source document number exists, run compact \`approval-runs pick\` queries across configured tenants and select the tenant that actually contains the document. + +After resolution, pass the exact \`--corp \` to every command. Do not rely on the current/default tenant. + +Report the enterprise name, \`corpId\`, and how it was resolved. + +## 3. Resolve the approval run + +Start compactly: + +\`\`\`bash +seal-home approval-runs pick --corp --sn --latest +seal-home approval-runs get --summary --corp +seal-home approval-runs document-summary --corp +seal-home approval-runs result --summary --corp +seal-home approval-runs cited-rules --corp +\`\`\` + +Read attachment summaries only when the dispute depends on invoices, receipts, OCR, file type, or upload position. Use the run's historical \`ruleSetVersionNumber\`; do not explain a historical decision from the current draft alone. + +## 4. Classify the cause + +Classify the issue before proposing a change: + +- \`SOURCE_DATA\`: source fields are wrong or incomplete. +- \`ATTACHMENT_UNDERSTANDING\`: OCR, vision, or attachment classification introduced the disputed fact. +- \`RULE_DEFINITION\`: the rule is missing, ambiguous, contradictory, or too broad. +- \`MODEL_INTERPRETATION\`: the supplied rule covers the case, but the model invented or misapplied a requirement. +- \`SYSTEM_LOGIC\`: deterministic preprocessing, grouping, or aggregation produced the wrong review unit or values. + +When the editable boundary is rules only, say whether a rule-only mitigation can block the observed false positive and state any residual system limitation. + +## 5. Trace only when needed + +Use the Langfuse workflow from \`approval-attachment-trace.md\` when: + +- The final decision contradicts the supplied rule. +- Cited rules are missing or incomplete. +- A disputed requirement may have entered during pre-analysis. +- The finding depends on attachment understanding. + +Identify the final UI finding, the earliest stage where the disputed claim appeared, the exact rule supplied to final review, and whether final review followed or contradicted it. + +## 6. Design the minimal rule patch + +Fetch and compare: + +- The historical rule version used by the disputed run. +- The latest published version. +- The current draft rule, including its stable rule ID. + +Apply these defaults: + +1. Preserve \`scope\`. +2. Preserve \`strictness\`. +3. Preserve every unrelated description clause. +4. Change only the narrowest sentence needed to block the reproduced false positive. +5. Put an exception or negative constraint next to the clause that was misinterpreted. +6. If the rule already states a positive allowance but the model still rejects it, add a narrow \`不得因……驳回或建议复核\` constraint covering the actual failure mode. +7. Do not add new business requirements, broad examples, or unrelated exceptions without explicit user direction. + +Show a description-only unified diff by default: + +\`\`\`diff + unchanged text ++minimal added or changed sentence + unchanged text +\`\`\` + +State the target enterprise, target rule ID, changed fields, preserved fields, expected behavior, and residual limitation. + +## 7. Mutation gate and concurrency check + +Do not update until the user explicitly approves the exact diff. + +Immediately before updating: + +1. Fetch the current draft rule again. +2. Confirm its rule ID, description, scope, strictness, and status. +3. Compare the current description with the reviewed \`before\` text. +4. Stop if the rule changed concurrently or more than one rule matches the target. + +## 8. Update and verify the draft + +Send only approved fields. For a description-only change: + +\`\`\`bash +seal-home tool seal_approval_rule_update --corp \\ + --json '{"ruleId":"","description":""}' +\`\`\` + +Do not send \`scope\` or \`strictness\` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing. + +## 9. Publish and verify + +Publish only when explicitly authorized: + +\`\`\`bash +seal-home tool seal_approval_rule_version_publish --corp \\ + --json '{"versionName":""}' +\`\`\` + +Verify after publishing: + +- The new version is latest. +- Version number and version name are correct. +- Rule count is unchanged unless intentionally modified. +- The target rule contains the exact confirmed description. +- The target rule's \`scope\` and \`strictness\` are unchanged. + +Do not automatically rerun or resubmit the customer's production document. Run a simulation or regression only when separately requested and authorized. + +## Final response contract + +Return a compact report containing: + +- Enterprise and source document number +- Root-cause classification +- Target rule and exact changed text +- New version number and version name, if published +- Verification result +- Whether a regression rerun was performed +`; + +// skills/seal-home/references/hose-enterprise-auth.md +var hose_enterprise_auth_default = `# Hose Enterprise Auth + +Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links. + +## Add or switch an enterprise + +Use the CLI for normal enterprise setup. Do not inspect source code or hand-edit \`~/.config/seal-home/enterprises/*.json\` unless the CLI fails or the user explicitly asks for low-level config debugging. + +\`\`\`bash +seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' +seal-home corps list +seal-home corps current --corp +seal-home corps switch +\`\`\` + +\`corps add-hose\` verifies by default and writes the enterprise config. If the user says not to operate business logic, stop at \`corps\` and auth/config commands; do not run approval, rule, document, simulation, or approval-run commands. + +## Diagnose authentication + +\`\`\`bash +seal-home auth diagnose --corp +\`\`\` + +Read the JSON \`stages\` in order: + +- \`hose.openapi\`: appKey/appSecurity can get a Hose OpenAPI token and corporation ID. +- \`hose.provisional\`: \`proxyStaffBizId\`/staff ID can get a provisional auth URL. +- \`seal.sso\`: Seal accepts the Hose provisional token and returns a bearer session. +- \`seal.whoami\`: the Seal bearer can read current user and tenant. + +Do not expect tokens in the output; the command intentionally redacts or omits them. + +## Get a Hose authorization link + +When the user asks for a 合思/易快报授权链接、登录链接、入口链接, or says "来一个授权链接" for a Hose sourced enterprise, return the Hose provisional/CloseAPI URL from \`getProvisionalAuth\`'s \`value.message\`. + +Flow: + +1. Obtain an OpenAPI token with appKey/appSecurity: + +\`\`\`text +POST /api/openapi/v1/auth/getAccessToken +body: {"appKey":"...","appSecurity":"..."} +\`\`\` + +2. Call provisional auth: + +\`\`\`text +POST /api/openapi/v1.1/provisional/getProvisionalAuth?accessToken= +body: {"uid":"corpId:staffId","pageType":"home","expireDate":7200} +\`\`\` + +3. Return the exact \`value.message\` URL. + +Important: + +- Do not return the Seal tenant URL such as \`https://.sealai.cc\`; that is not the Hose authorization link. +- Do not manually assemble \`thirdparty.html\` with a global/OpenAPI token. +- \`seal-home auth diagnose\` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link. +- **Formatting Requirement**: When returning a Hose authorization link to the user, ALWAYS provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) for easy copying without accidental default browser redirection, AND a clickable hyperlink. +- If the CLI later provides a dedicated command for this, prefer that command. +`; + +// src/core/embedded-skill.ts +var EMBEDDED_SKILL_FILES = { + "SKILL.md": SKILL_default, + "agents/openai.yaml": openai_default, + "references/rule-lightweight.md": rule_lightweight_default, + "references/approval-bad-cases.md": approval_bad_cases_default, + "references/cli.md": cli_default, + "references/approval-run-lightweight.md": approval_run_lightweight_default, + "references/approval-attachment-trace.md": approval_attachment_trace_default, + "references/customer-feedback-rule-remediation.md": customer_feedback_rule_remediation_default, + "references/hose-enterprise-auth.md": hose_enterprise_auth_default +}; +function getSkillContent() { + return EMBEDDED_SKILL_FILES["SKILL.md"] || ""; +} +function getDefaultGlobalSkillDir() { + return join6(homedir4(), ".agents", "skills", "seal-home"); +} +function installSkillFiles(targetDir = getDefaultGlobalSkillDir()) { + mkdirSync5(targetDir, { recursive: true }); + const installed = []; + for (const [relPath, content] of Object.entries(EMBEDDED_SKILL_FILES)) { + const fullPath = join6(targetDir, relPath); + mkdirSync5(dirname3(fullPath), { recursive: true }); + writeFileSync6(fullPath, content, "utf8"); + installed.push(relPath); + } + return { + targetDir, + files: installed + }; +} +function syncGlobalSkillIfPresent() { + const globalDir = getDefaultGlobalSkillDir(); + if (existsSync6(globalDir)) { + installSkillFiles(globalDir); + return { synced: true, targetDir: globalDir }; + } + return { synced: false }; +} + +// src/cli/commands/skill.ts +function handleSkillCommand(action, maybeName, args) { + if (action === "dump" || action === "cat" || action === "show") { + process.stdout.write(`${getSkillContent()} +`); + return; + } + if (action === "install" || action === "init" || action === "sync") { + const isLocal = booleanOption(args.options.local) || booleanOption(args.options.workspace); + const customDir = stringOption(args.options.dir) ?? stringOption(args.options.target) ?? maybeName; + const targetDir = customDir ? customDir : isLocal ? join7(process.cwd(), ".agents", "skills", "seal-home") : getDefaultGlobalSkillDir(); + const result = installSkillFiles(targetDir); + printJson({ + installed: true, + targetDir: result.targetDir, + fileCount: result.files.length, + files: result.files + }); + return; + } + if (action === "status" || action === "get" || !action) { + const globalDir = getDefaultGlobalSkillDir(); + const localDir = join7(process.cwd(), ".agents", "skills", "seal-home"); + printJson({ + global: { + dir: globalDir, + installed: existsSync7(join7(globalDir, "SKILL.md")) + }, + local: { + dir: localDir, + installed: existsSync7(join7(localDir, "SKILL.md")) + } + }); + return; + } + throw new Error(`Unknown skill command: ${action}. Run 'seal-home help' for available commands.`); +} + +// src/cli/commands/source.ts +async function handleSourceCommand(action, corp) { + if (action === "config") { + printJson(await resolveLiveSealEnterpriseConfig(corp)); + return; + } + throw new Error(`Unknown source command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/cli/commands/tool.ts +async function handleToolCommand(action, client, corp, args) { + if (!action) + throw new Error("Usage: seal-home tool [--json '{...}']"); + await runTool(action, client, corp, jsonObject(args.json), outputOptions(args.options)); +} + +// src/cli/commands/tools.ts +function handleToolsListCommand() { + printJson(sealTools.map((tool) => ({ name: tool.name, description: tool.description }))); +} + +// src/cli/commands/update.ts +import { chmodSync, mkdirSync as mkdirSync6, renameSync, rmSync as rmSync2, unlinkSync, writeFileSync as writeFileSync7 } from "node:fs"; +import { dirname as dirname4, join as join8 } from "node:path"; +import { spawnSync } from "node:child_process"; + +// src/core/runtime.ts +function isCompiledBinary(execPath = process.execPath, metaUrl = import.meta.url) { + if (metaUrl.includes("/$bunfs/") || metaUrl.includes("\\$bunfs\\")) { + return true; + } + const lower = execPath.toLowerCase().replace(/\\/g, "/"); + return !lower.endsWith("/bun") && !lower.endsWith("/bun.exe"); +} + +// src/cli/commands/update.ts +var DEFAULT_GITHUB_REPO = "yunyingk/seal-home"; +var GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO"; +async function handleUpdateCommand(runtime, options = {}) { + const serviceConfig = { + appRoot: runtime.appRoot, + entryFile: runtime.entryFile, + stateDir: STATE_DIR, + version: VERSION, + launcher: runtime.launcher + }; + if (!isCompiledBinary()) { + const wasRunning2 = serviceStatus(serviceConfig).running; + if (wasRunning2) + await runServiceCommand("stop", serviceConfig); + runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]); + runCommand("bun", ["install"], { cwd: runtime.appRoot }); + if (wasRunning2) + await runServiceCommand("start", serviceConfig); + printJson({ + updated: true, + serviceRestarted: wasRunning2, + version: VERSION, + mode: "source" + }); + return; + } + const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO; + const platform = detectPlatform(); + const arch = detectArch(); + const release = await fetchGitHubRelease(repo, options.targetVersion); + if (!release) { + printJson({ + updated: false, + currentVersion: VERSION, + mode: "binary", + message: `Failed to query releases from GitHub repository '${repo}'` + }); + return; + } + const latestVersion = release.version; + const isUpgrade = isNewerVersion(latestVersion, VERSION); + const shouldUpdate = options.force || Boolean(options.targetVersion) || isUpgrade; + if (options.checkOnly) { + printJson({ + updated: false, + updateAvailable: isUpgrade, + currentVersion: VERSION, + latestVersion, + releaseNotes: release.notes, + releaseUrl: release.htmlUrl, + mode: "binary" + }); + return; + } + if (!shouldUpdate) { + printJson({ + updated: false, + currentVersion: VERSION, + latestVersion, + mode: "binary", + message: `seal-home is already up to date (v${VERSION})` + }); + return; + } + const asset = matchAssetForPlatform(release.assets, platform, arch); + if (!asset) { + throw new Error(`No compatible binary found for ${platform}-${arch} in release v${latestVersion}. ` + `Available assets: ${release.assets.map((a) => a.name).join(", ")}`); + } + const wasRunning = serviceStatus(serviceConfig).running; + if (wasRunning) + await runServiceCommand("stop", serviceConfig); + const execPath = process.execPath; + const execDir = dirname4(execPath); + const tmpDir = join8(execDir, `.tmp-update-${Date.now()}`); + mkdirSync6(tmpDir, { recursive: true }); + try { + const downloadedFile = join8(tmpDir, asset.name); + await downloadFile(asset.downloadUrl, downloadedFile); + let newBinaryPath = downloadedFile; + if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) { + newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform); + } else if (asset.name.endsWith(".zip")) { + newBinaryPath = extractZip(downloadedFile, tmpDir, platform); + } + chmodSync(newBinaryPath, 493); + if (process.platform === "darwin") { + try { + spawnSync("/usr/bin/codesign", ["--remove-signature", newBinaryPath], { stdio: "ignore" }); + spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", newBinaryPath], { stdio: "ignore" }); + } catch {} + } + if (process.platform === "win32") { + const oldBinary = `${execPath}.old.${Date.now()}`; + try { + renameSync(execPath, oldBinary); + } catch {} + renameSync(newBinaryPath, execPath); + } else { + renameSync(newBinaryPath, execPath); + } + if (wasRunning) + await runServiceCommand("start", serviceConfig); + const skillSync = syncGlobalSkillIfPresent(); + printJson({ + updated: true, + fromVersion: VERSION, + toVersion: latestVersion, + serviceRestarted: wasRunning, + skillSynced: skillSync.synced ? skillSync.targetDir : false, + mode: "binary" + }); + } finally { + try { + rmSync2(tmpDir, { recursive: true, force: true }); + } catch {} + } +} +function detectPlatform() { + if (process.platform === "darwin") + return "darwin"; + if (process.platform === "win32") + return "windows"; + return "linux"; +} +function detectArch() { + return process.arch === "arm64" ? "arm64" : "x64"; +} +async function fetchGitHubRelease(repo, targetVersion) { + const url2 = targetVersion ? `https://api.github.com/repos/${repo}/releases/tags/${targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`}` : `https://api.github.com/repos/${repo}/releases/latest`; + const headers = { + "User-Agent": `seal-home/${VERSION}`, + Accept: "application/vnd.github.v3+json" + }; + const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; + if (token) { + headers.Authorization = `Bearer ${token}`; + } + try { + const res = await fetch(url2, { headers }); + if (!res.ok) + return; + const json2 = await res.json(); + const tagName = json2.tag_name ?? ""; + const version2 = tagName.replace(/^v/, ""); + if (!version2) + return; + const assets = (json2.assets ?? []).map((item) => ({ + name: item.name, + downloadUrl: item.browser_download_url, + size: item.size ?? 0 + })); + return { + version: version2, + tagName, + notes: json2.body ?? "", + htmlUrl: json2.html_url ?? "", + assets + }; + } catch { + return; + } +} +function matchAssetForPlatform(assets, platform, arch) { + const platformKeywords = { + darwin: ["darwin", "macos", "osx", "apple"], + linux: ["linux"], + windows: ["windows", "win32", "win"] + }; + const archKeywords = { + arm64: ["arm64", "aarch64"], + x64: ["x64", "x86_64", "amd64"] + }; + const pKeys = platformKeywords[platform] || []; + const aKeys = archKeywords[arch] || []; + const matched = assets.filter((asset) => { + const lower = asset.name.toLowerCase(); + const matchesP = pKeys.some((k) => lower.includes(k)); + const matchesA = aKeys.some((k) => lower.includes(k)); + return matchesP && matchesA; + }); + const directBinary = matched.find((asset) => !asset.name.endsWith(".tar.gz") && !asset.name.endsWith(".tgz") && !asset.name.endsWith(".zip") && !asset.name.endsWith(".sha256")); + if (directBinary) + return directBinary; + const archive = matched.find((asset) => asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz") || asset.name.endsWith(".zip")); + return archive || matched[0]; +} +async function downloadFile(url2, destPath) { + const res = await fetch(url2); + if (!res.ok) { + throw new Error(`Failed to download asset from ${url2}: ${res.status} ${res.statusText}`); + } + const buffer = Buffer.from(await res.arrayBuffer()); + writeFileSync7(destPath, buffer); +} +function extractTarGz(archivePath, targetDir, platform) { + const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" }); + if (result.status !== 0) { + throw new Error(`Failed to extract tar archive: ${result.stderr.toString()}`); + } + unlinkSync(archivePath); + const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home"; + const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" }).stdout.trim().split(` +`).filter(Boolean); + const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName)); + if (exact) + return exact; + return files[0] || archivePath; +} +function extractZip(archivePath, targetDir, platform) { + const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" }); + if (result.status !== 0) { + throw new Error(`Failed to extract zip archive: ${result.stderr.toString()}`); + } + unlinkSync(archivePath); + const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home"; + const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" }).stdout.trim().split(` +`).filter(Boolean); + const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName)); + if (exact) + return exact; + return files[0] || archivePath; +} +function isNewerVersion(latest, current) { + const lParts = latest.split(".").map(Number); + const cParts = current.split(".").map(Number); + for (let i = 0;i < Math.max(lParts.length, cParts.length); i++) { + const l = lParts[i] ?? 0; + const c = cParts[i] ?? 0; + if (l > c) + return true; + if (l < c) + return false; + } + return false; +} +function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"] + }); + if (result.stdout) + console.error(result.stdout.trimEnd()); + if (result.stderr) + console.error(result.stderr.trimEnd()); + if (result.status !== 0) { + throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`); + } +} + +// src/cli/commands/users.ts +async function handleUsersCommand(action, maybeName, client, corp, args) { + if (action === "create") { + const name = stringOption(args.options.name) ?? maybeName; + const phone = stringOption(args.options.phone); + if (!name || !phone) + throw new Error("Usage: seal-home users create --name --phone [--dept ]"); + const deptId = stringOption(args.options.dept) ?? stringOption(args.options.departmentId); + const departmentIds = deptId ? [deptId] : undefined; + await runTool("seal_user_create", client, corp, { name, phone, departmentIds }, outputOptions(args.options)); + return; + } + if (action === "reset-password") { + const userId = maybeName ?? stringOption(args.options.userId); + if (!userId) + throw new Error("Usage: seal-home users reset-password "); + await runTool("seal_user_reset_password", client, corp, { userId }, outputOptions(args.options)); + return; + } + if (action === "search" || action === "list") { + const keyword = maybeName ?? stringOption(args.options.keyword) ?? stringOption(args.options.query) ?? ""; + await runTool("seal_user_search", client, corp, { keyword }, outputOptions(args.options)); + return; + } + if (action === "get") { + const userId = maybeName ?? stringOption(args.options.userId); + if (!userId) + throw new Error("Usage: seal-home users get "); + await runTool("seal_user_get", client, corp, { userId }, outputOptions(args.options)); + return; + } + if (action === "delete") { + const userId = maybeName ?? stringOption(args.options.userId); + if (!userId) + throw new Error("Usage: seal-home users delete "); + await runTool("seal_user_delete", client, corp, { userId }, outputOptions(args.options)); + return; + } + if (action === "activate") { + const userId = maybeName ?? stringOption(args.options.userId); + if (!userId) + throw new Error("Usage: seal-home users activate "); + await runTool("seal_user_activate", client, corp, { userId }, outputOptions(args.options)); + return; + } + if (action === "delegation" || action === "impersonate") { + const userIdOrPhone = maybeName ?? stringOption(args.options.userId) ?? stringOption(args.options.phone); + if (!userIdOrPhone) + throw new Error("Usage: seal-home users delegation [--note ]"); + const note = stringOption(args.options.note); + await runTool("seal_user_delegation_create", client, corp, { userIdOrPhone, note }, outputOptions(args.options)); + return; + } + throw new Error(`Unknown users command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/cli/commands/webhook.ts +async function handleWebhookCommand(action, maybeName, client, corp, args) { + if (action === "list") { + await runTool("seal_webhook_list", client, corp, { + query: stringOption(args.options.query) ?? stringOption(args.options.keyword), + includeSecret: webhookShowSecretOption(args.options) + }, outputOptions(args.options)); + return; + } + if (action === "get" || action === "find") { + const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); + if (!selector) + throw new Error("Usage: seal-home webhook get [--show-secret]"); + await runTool("seal_webhook_get", client, corp, { + selector, + includeSecret: webhookShowSecretOption(args.options) + }, outputOptions(args.options)); + return; + } + if (action === "add" || action === "create") { + const name = stringOption(args.options.name) ?? maybeName; + const outgoingResultWebhook = stringOption(args.options.resultUrl) ?? stringOption(args.options["result-url"]) ?? stringOption(args.options.outgoingResultWebhook) ?? stringOption(args.options["outgoing-result-webhook"]); + if (!name || !outgoingResultWebhook) { + throw new Error("Usage: seal-home webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic]"); + } + const autoApprovalRate = webhookRateOption(args.options); + await runTool("seal_webhook_add", client, corp, { + name, + mode: parseWebhookMode(stringOption(args.options.mode)), + outgoingResultWebhook, + autoApprovalRate, + secret: stringOption(args.options.secret) + }, outputOptions(args.options)); + return; + } + if (action === "update") { + const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); + if (!selector) + throw new Error("Usage: seal-home webhook update [options]"); + const secret = stringOption(args.options.secret); + const rotateSecret = booleanOption(args.options.rotateSecret) ?? booleanOption(args.options["rotate-secret"]); + if (secret !== undefined && rotateSecret) { + throw new Error("Use either --secret or --rotate-secret, not both"); + } + const name = stringOption(args.options.name); + const mode = parseWebhookMode(stringOption(args.options.mode)); + const outgoingResultWebhook = stringOption(args.options.resultUrl) ?? stringOption(args.options["result-url"]) ?? stringOption(args.options.outgoingResultWebhook) ?? stringOption(args.options["outgoing-result-webhook"]); + const autoApprovalRate = webhookRateOption(args.options); + if (name === undefined && mode === undefined && outgoingResultWebhook === undefined && autoApprovalRate === undefined && secret === undefined && !rotateSecret) { + throw new Error("Webhook update requires at least one field option"); + } + await runTool("seal_webhook_update", client, corp, { + selector, + name, + mode, + outgoingResultWebhook, + autoApprovalRate, + secret, + rotateSecret + }, outputOptions(args.options)); + return; + } + if (action === "delete") { + const selector = maybeName ?? stringOption(args.options.selector) ?? stringOption(args.options.id); + if (!selector) + throw new Error("Usage: seal-home webhook delete --yes"); + if (booleanOption(args.options.yes) !== true) { + throw new Error("Refusing to delete Webhook integration without --yes"); + } + await runTool("seal_webhook_delete", client, corp, { + selector, + confirm: true + }, outputOptions(args.options)); + return; + } + throw new Error(`Unknown webhook command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} + +// src/cli/runner.ts +var DEFAULT_APP_ROOT = dirname5(dirname5(dirname5(fileURLToPath(import.meta.url)))); +var KNOWN_AREAS = new Set([ + "config", + "service", + "update", + "tools", + "corps", + "tool", + "source", + "auth", + "delegation", + "users", + "llm", + "permissions", + "billing", + "webhook", + "webhooks", + "context", + "rules", + "approval-runs", + "simulation", + "mcp", + "server", + "mcp-config", + "skill", + "probe" +]); +var runQueue = Promise.resolve(); +function runCli(argv, options = {}) { + const run = runQueue.then(() => runCliOnce(argv, options)); + runQueue = run.then(() => { + return; + }, () => { + return; + }); + return run; +} +async function runCliOnce(argv, options) { + const stdout = []; + const stderr = []; + const originalLog = console.log; + const originalError = console.error; + const runtime = { + appRoot: options.appRoot ?? DEFAULT_APP_ROOT, + entryFile: options.entryFile ?? join9(options.appRoot ?? DEFAULT_APP_ROOT, "src", "cli.ts"), + launcher: options.launcher + }; + console.log = (...values) => { + stdout.push(formatConsoleOutput(values)); + }; + console.error = (...values) => { + stderr.push(formatConsoleOutput(values)); + }; + try { + await dispatch(argv, runtime); + return { + stdout: joinOutput(stdout), + stderr: joinOutput(stderr), + isError: false, + exitCode: 0 + }; + } catch (error51) { + stderr.push(redactSensitiveText(error51 instanceof Error ? error51.message : String(error51))); + return { + stdout: joinOutput(stdout), + stderr: joinOutput(stderr), + isError: true, + exitCode: 1 + }; + } finally { + console.log = originalLog; + console.error = originalError; + } +} +async function dispatch(argv, runtime) { + const args = parseArgs(argv); + const [area, action, maybeName] = args.command; + if (area === "version" || area === "v" || Boolean(args.options.version) || Boolean(args.options.v) || Boolean(args.options.V)) { + printJson({ + name: "seal-home", + version: VERSION + }); + return; + } + if (!area || area === "help" || args.options.help) { + printHelp(); + return; + } + if (!KNOWN_AREAS.has(area)) { + throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); + } + if (area === "mcp-config") { + printMcpConfig(); + return; + } + if (area === "skill") { + handleSkillCommand(action, maybeName, args); + return; + } + if (area === "mcp" || area === "server") { + await handleMcpCommand(action, args); + return; + } + if (area === "probe") { + await handleProbeCommand(action, maybeName, args); + return; + } + if (area === "config") { + handleConfigCommand(action, maybeName, args); + return; + } + if (area === "service") { + await handleServiceCommand(action, runtime); + return; + } + if (area === "update") { + const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? (action && !action.startsWith("-") ? action : undefined); + await handleUpdateCommand(runtime, { + checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"]), + force: booleanOption(args.options.force), + targetVersion, + repo: stringOption(args.options.repo) + }); + return; + } + if (area === "tools" && action === "list") { + handleToolsListCommand(); + return; + } + if (area === "corps") { + await handleCorpsCommand(action, maybeName, args); + return; + } + const corp = selectCorp(stringOption(args.options.corp)); + if (area === "source") { + await handleSourceCommand(action, corp); + return; + } + if (area === "auth") { + await handleAuthCommand(action, corp, args); + return; + } + const client = await createSealClient(corp); + if (area === "delegation") { + await handleDelegationCommand(action, maybeName, client, corp, args); + return; + } + if (area === "users") { + await handleUsersCommand(action, maybeName, client, corp, args); + return; + } + if (area === "llm") { + await handleLlmCommand(action, client, corp, args); + return; + } + if (area === "permissions") { + await handlePermissionsCommand(action, client, corp, args); + return; + } + if (area === "billing") { + await handleBillingCommand(action, client, corp, args); + return; + } + if (area === "webhook" || area === "webhooks") { + await handleWebhookCommand(action, maybeName, client, corp, args); + return; + } + if (area === "context") { + await handleContextCommand(client, corp, args); + return; + } + if (area === "rules") { + await handleRulesCommand(action, maybeName, client, corp, args); + return; + } + if (area === "approval-runs") { + await handleApprovalRunsCommand(action, maybeName, client, corp, args); + return; + } + if (area === "simulation") { + await handleSimulationCommand(action, maybeName, client, corp, args); + return; + } + if (area === "tool") { + await handleToolCommand(action, client, corp, args); + return; + } + throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); } // src/server.ts var serverEntryFile = fileURLToPath2(import.meta.url); -var pluginRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\") ? dirname4(dirname4(dirname4(serverEntryFile))) : dirname4(dirname4(serverEntryFile)); +var pluginRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\") ? dirname6(dirname6(dirname6(serverEntryFile))) : dirname6(dirname6(serverEntryFile)); var SEAL_CLI_TOOL_NAME = "seal_cli"; var SEAL_MCP_ENABLED_ENV = "SEAL_HOME_MCP_ENABLED"; function resolveMcpEnabled(value = process.env[SEAL_MCP_ENABLED_ENV]) { @@ -30202,7 +31856,7 @@ async function runEmbeddedCli() { `}`); process.exitCode = result.exitCode; } -var isMainModule = process.argv[1] ? resolve(process.argv[1]) === resolve(serverEntryFile) : false; +var isMainModule = Boolean(__require.main == __require.module || !import.meta.url.includes("$bunfs") && process.argv[1] && resolve(process.argv[1]) === resolve(serverEntryFile)); if (isMainModule) { if (process.argv[2] === "--seal-home-cli") { await runEmbeddedCli(); diff --git a/package.json b/package.json index 8358eb0..bfc2e26 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seal-home", - "version": "0.6.0", + "version": "0.7.0", "type": "module", "module": "src/server.ts", "bin": { diff --git a/skills/seal-home/SKILL.md b/skills/seal-home/SKILL.md index 98d6a51..9d12aab 100644 --- a/skills/seal-home/SKILL.md +++ b/skills/seal-home/SKILL.md @@ -1,12 +1,12 @@ --- name: seal-home -description: "v0.6.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search." +description: "v0.7.0: Use when working with Seal Home tenant operations: packaged customer feedback from WeChat or screenshots, target-enterprise discovery, approval-run and Langfuse diagnosis, simulation test batch creation and publishing, minimal approval-rule remediation and publishing, delegation links, Hose/合思 authorization, LLM config, permissions, billing, users, rules, documents, and search." metadata: - version: 0.6.0 - short-description: Seal tenant and Hose approval automation (v0.6.0) + version: 0.7.0 + short-description: Seal tenant and Hose approval automation (v0.7.0) --- -# Seal Home (v0.6.0) +# Seal Home (v0.7.0) Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-home` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail. diff --git a/src/cli.test.ts b/src/cli.test.ts index 517fc2b..bb4886a 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -120,6 +120,42 @@ describe("CLI version & help handling", () => { expect(parsed.mode).toBe("source"); expect(parsed.version).toBe(VERSION); }); + + test("mcp-config outputs valid mcp configuration json", () => { + const result = runCli(["mcp-config"]); + expect(result.status).toBe(0); + const parsed = JSON.parse(result.stdout.trim()); + expect(parsed.mcpServers["seal-home"]).toMatchObject({ + command: "seal-home", + args: ["mcp"] + }); + }); + + test("skill dump outputs embedded skill markdown", () => { + const result = runCli(["skill", "dump"]); + expect(result.status).toBe(0); + expect(result.stdout).toContain("name: seal-home"); + expect(result.stdout).toContain("# Seal Home"); + }); + + test("skill status outputs installation directories", () => { + const result = runCli(["skill", "status"]); + expect(result.status).toBe(0); + const parsed = JSON.parse(result.stdout.trim()); + expect(parsed.global).toHaveProperty("dir"); + expect(parsed.local).toHaveProperty("dir"); + }); + + test("skill install writes files to specified directory", () => { + const tmp = mkdtempSync(join(tmpdir(), "cli-skill-install-")); + tempDirs.push(tmp); + const result = runCli(["skill", "install", "--dir", tmp]); + expect(result.status).toBe(0); + const parsed = JSON.parse(result.stdout.trim()); + expect(parsed.installed).toBe(true); + expect(parsed.targetDir).toBe(tmp); + expect(parsed.fileCount).toBeGreaterThan(5); + }); }); function makeConfigEnv(): Record { diff --git a/src/cli/commands/mcp.ts b/src/cli/commands/mcp.ts index a0cc342..4cfced7 100644 --- a/src/cli/commands/mcp.ts +++ b/src/cli/commands/mcp.ts @@ -1,5 +1,27 @@ import { startServer } from "../../server.js"; +import { printJson } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleMcpCommand(action: string | undefined, args: ParsedArgs) { + if (action === "config" || action === "json") { + printMcpConfig(); + return; + } -export async function handleMcpCommand() { await startServer(); } + +export function printMcpConfig() { + printJson({ + mcpServers: { + "seal-home": { + type: "stdio", + command: "seal-home", + args: ["mcp"], + env: { + SEAL_HOME_MCP_ENABLED: "true" + } + } + } + }); +} diff --git a/src/cli/commands/skill.ts b/src/cli/commands/skill.ts new file mode 100644 index 0000000..508d761 --- /dev/null +++ b/src/cli/commands/skill.ts @@ -0,0 +1,54 @@ +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { + getDefaultGlobalSkillDir, + getSkillContent, + installSkillFiles +} from "../../core/embedded-skill.js"; +import { booleanOption, stringOption } from "../parser.js"; +import { printJson } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export function handleSkillCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { + if (action === "dump" || action === "cat" || action === "show") { + process.stdout.write(`${getSkillContent()}\n`); + return; + } + + if (action === "install" || action === "init" || action === "sync") { + const isLocal = booleanOption(args.options.local) || booleanOption(args.options.workspace); + const customDir = stringOption(args.options.dir) ?? stringOption(args.options.target) ?? maybeName; + const targetDir = customDir + ? customDir + : isLocal + ? join(process.cwd(), ".agents", "skills", "seal-home") + : getDefaultGlobalSkillDir(); + + const result = installSkillFiles(targetDir); + printJson({ + installed: true, + targetDir: result.targetDir, + fileCount: result.files.length, + files: result.files + }); + return; + } + + if (action === "status" || action === "get" || !action) { + const globalDir = getDefaultGlobalSkillDir(); + const localDir = join(process.cwd(), ".agents", "skills", "seal-home"); + printJson({ + global: { + dir: globalDir, + installed: existsSync(join(globalDir, "SKILL.md")) + }, + local: { + dir: localDir, + installed: existsSync(join(localDir, "SKILL.md")) + } + }); + return; + } + + throw new Error(`Unknown skill command: ${action}. Run 'seal-home help' for available commands.`); +} diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts index 160c204..a7ed425 100644 --- a/src/cli/commands/update.ts +++ b/src/cli/commands/update.ts @@ -2,6 +2,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, unl import { dirname, join } from "node:path"; import { spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; +import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js"; import { VERSION } from "../../version.js"; import { runServiceCommand, serviceStatus } from "../service.js"; import { printJson } from "../printer.js"; @@ -147,11 +148,14 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp if (wasRunning) await runServiceCommand("start", serviceConfig); + const skillSync = syncGlobalSkillIfPresent(); + printJson({ updated: true, fromVersion: VERSION, toVersion: latestVersion, serviceRestarted: wasRunning, + skillSynced: skillSync.synced ? skillSync.targetDir : false, mode: "binary" }); } finally { diff --git a/src/cli/printer.ts b/src/cli/printer.ts index 15708d3..56ef73c 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -75,6 +75,11 @@ export function printHelp() { Usage: seal-home version seal-home mcp + seal-home mcp config + seal-home mcp-config + seal-home skill dump + seal-home skill install [--dir |--local] + seal-home skill status seal-home probe [] seal-home config paths seal-home config get diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 3442752..830878a 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -12,12 +12,13 @@ import { handleContextCommand } from "./commands/context.js"; import { handleCorpsCommand } from "./commands/corps.js"; import { handleDelegationCommand } from "./commands/delegation.js"; import { handleLlmCommand } from "./commands/llm.js"; -import { handleMcpCommand } from "./commands/mcp.js"; +import { handleMcpCommand, printMcpConfig } from "./commands/mcp.js"; import { handlePermissionsCommand } from "./commands/permissions.js"; import { handleProbeCommand } from "./commands/probe.js"; import { handleRulesCommand } from "./commands/rules.js"; import { handleServiceCommand } from "./commands/service.js"; import { handleSimulationCommand } from "./commands/simulation.js"; +import { handleSkillCommand } from "./commands/skill.js"; import { handleSourceCommand } from "./commands/source.js"; import { handleToolCommand } from "./commands/tool.js"; import { handleToolsListCommand } from "./commands/tools.js"; @@ -58,6 +59,8 @@ const KNOWN_AREAS = new Set([ "simulation", "mcp", "server", + "mcp-config", + "skill", "probe" ]); @@ -141,8 +144,18 @@ async function dispatch(argv: string[], runtime: CliRuntime) { throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); } + if (area === "mcp-config") { + printMcpConfig(); + return; + } + + if (area === "skill") { + handleSkillCommand(action, maybeName, args); + return; + } + if (area === "mcp" || area === "server") { - await handleMcpCommand(); + await handleMcpCommand(action, args); return; } diff --git a/src/core/embedded-skill.test.ts b/src/core/embedded-skill.test.ts new file mode 100644 index 0000000..3ad7c47 --- /dev/null +++ b/src/core/embedded-skill.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js"; + +describe("embedded-skill", () => { + test("embeds SKILL.md and reference files", () => { + expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined(); + expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: seal-home"); + expect(EMBEDDED_SKILL_FILES["references/cli.md"]).toBeDefined(); + expect(getSkillContent()).toContain("name: seal-home"); + }); + + test("installSkillFiles writes all embedded files to target directory", () => { + const tmp = mkdtempSync(join(tmpdir(), "skill-test-")); + try { + const res = installSkillFiles(tmp); + expect(res.targetDir).toBe(tmp); + expect(res.files.length).toBeGreaterThan(5); + expect(existsSync(join(tmp, "SKILL.md"))).toBe(true); + expect(existsSync(join(tmp, "references", "cli.md"))).toBe(true); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/src/core/embedded-skill.ts b/src/core/embedded-skill.ts new file mode 100644 index 0000000..d67cbbe --- /dev/null +++ b/src/core/embedded-skill.ts @@ -0,0 +1,59 @@ +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +import skillMain from "../../skills/seal-home/SKILL.md" with { type: "text" }; +import agentOpenAi from "../../skills/seal-home/agents/openai.yaml" with { type: "text" }; +import refRuleLightweight from "../../skills/seal-home/references/rule-lightweight.md" with { type: "text" }; +import refApprovalBadCases from "../../skills/seal-home/references/approval-bad-cases.md" with { type: "text" }; +import refCli from "../../skills/seal-home/references/cli.md" with { type: "text" }; +import refApprovalRunLightweight from "../../skills/seal-home/references/approval-run-lightweight.md" with { type: "text" }; +import refApprovalAttachmentTrace from "../../skills/seal-home/references/approval-attachment-trace.md" with { type: "text" }; +import refCustomerFeedbackRuleRemediation from "../../skills/seal-home/references/customer-feedback-rule-remediation.md" with { type: "text" }; +import refHoseEnterpriseAuth from "../../skills/seal-home/references/hose-enterprise-auth.md" with { type: "text" }; + +export const EMBEDDED_SKILL_FILES: Record = { + "SKILL.md": skillMain, + "agents/openai.yaml": agentOpenAi, + "references/rule-lightweight.md": refRuleLightweight, + "references/approval-bad-cases.md": refApprovalBadCases, + "references/cli.md": refCli, + "references/approval-run-lightweight.md": refApprovalRunLightweight, + "references/approval-attachment-trace.md": refApprovalAttachmentTrace, + "references/customer-feedback-rule-remediation.md": refCustomerFeedbackRuleRemediation, + "references/hose-enterprise-auth.md": refHoseEnterpriseAuth +}; + +export function getSkillContent(): string { + return EMBEDDED_SKILL_FILES["SKILL.md"] || ""; +} + +export function getDefaultGlobalSkillDir(): string { + return join(homedir(), ".agents", "skills", "seal-home"); +} + +export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): { targetDir: string; files: string[] } { + mkdirSync(targetDir, { recursive: true }); + const installed: string[] = []; + + for (const [relPath, content] of Object.entries(EMBEDDED_SKILL_FILES)) { + const fullPath = join(targetDir, relPath); + mkdirSync(dirname(fullPath), { recursive: true }); + writeFileSync(fullPath, content, "utf8"); + installed.push(relPath); + } + + return { + targetDir, + files: installed + }; +} + +export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string } { + const globalDir = getDefaultGlobalSkillDir(); + if (existsSync(globalDir)) { + installSkillFiles(globalDir); + return { synced: true, targetDir: globalDir }; + } + return { synced: false }; +} diff --git a/src/declarations.d.ts b/src/declarations.d.ts new file mode 100644 index 0000000..495d98f --- /dev/null +++ b/src/declarations.d.ts @@ -0,0 +1,14 @@ +declare module "*.md" { + const content: string; + export default content; +} + +declare module "*.yaml" { + const content: string; + export default content; +} + +declare module "*.yml" { + const content: string; + export default content; +}