From 85ca31f4adc1ae733e66293f269ad0e88f0829e5 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 25 Aug 2026 13:50:44 +0800 Subject: [PATCH] Refactor CLI runner into modular command handlers --- src/cli/commands/approval-runs.ts | 180 ++++ src/cli/commands/auth.ts | 280 ++++++ src/cli/commands/billing.ts | 29 + src/cli/commands/config.ts | 56 ++ src/cli/commands/context.ts | 23 + src/cli/commands/corps.ts | 297 ++++++ src/cli/commands/delegation.ts | 34 + src/cli/commands/llm.ts | 24 + src/cli/commands/mcp.ts | 5 + src/cli/commands/permissions.ts | 24 + src/cli/commands/probe.ts | 8 + src/cli/commands/rules.ts | 144 +++ src/cli/commands/service.ts | 19 + src/cli/commands/simulation.ts | 107 ++ src/cli/commands/source.ts | 12 + src/cli/commands/tool.ts | 16 + src/cli/commands/tools.ts | 6 + src/cli/commands/update.ts | 47 + src/cli/commands/users.ts | 68 ++ src/cli/commands/webhook.ts | 142 +++ src/cli/helpers.ts | 58 ++ src/cli/parser.ts | 196 ++++ src/cli/printer.ts | 145 +++ src/cli/runner.ts | 1556 ++--------------------------- src/cli/types.ts | 36 + 25 files changed, 2027 insertions(+), 1485 deletions(-) create mode 100644 src/cli/commands/approval-runs.ts create mode 100644 src/cli/commands/auth.ts create mode 100644 src/cli/commands/billing.ts create mode 100644 src/cli/commands/config.ts create mode 100644 src/cli/commands/context.ts create mode 100644 src/cli/commands/corps.ts create mode 100644 src/cli/commands/delegation.ts create mode 100644 src/cli/commands/llm.ts create mode 100644 src/cli/commands/mcp.ts create mode 100644 src/cli/commands/permissions.ts create mode 100644 src/cli/commands/probe.ts create mode 100644 src/cli/commands/rules.ts create mode 100644 src/cli/commands/service.ts create mode 100644 src/cli/commands/simulation.ts create mode 100644 src/cli/commands/source.ts create mode 100644 src/cli/commands/tool.ts create mode 100644 src/cli/commands/tools.ts create mode 100644 src/cli/commands/update.ts create mode 100644 src/cli/commands/users.ts create mode 100644 src/cli/commands/webhook.ts create mode 100644 src/cli/helpers.ts create mode 100644 src/cli/parser.ts create mode 100644 src/cli/printer.ts create mode 100644 src/cli/types.ts diff --git a/src/cli/commands/approval-runs.ts b/src/cli/commands/approval-runs.ts new file mode 100644 index 0000000..8cb5959 --- /dev/null +++ b/src/cli/commands/approval-runs.ts @@ -0,0 +1,180 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { booleanOption, numberOption, stringOption } from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleApprovalRunsCommand( + action: string | undefined, + maybeName: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + 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; + } + + 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; + } + + 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.`); +} diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts new file mode 100644 index 0000000..71dfa47 --- /dev/null +++ b/src/cli/commands/auth.ts @@ -0,0 +1,280 @@ +import { getHoseProvisionalAuthLink } from "../../core/auth/hose.js"; +import { clearCorpTokenCache } from "../../core/auth/token-store.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import { createSealClient } from "../../core/http/factory.js"; +import { getMe } from "../../domains/seal/api.js"; +import { numberOption } from "../parser.js"; +import { printJson, redactSensitiveText } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleAuthCommand(action: string | undefined, corp: CorpConfig, args: ParsedArgs) { + 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.`); +} + +export async function diagnoseAuth(corp: CorpConfig) { + if (corp.source.type !== "hose") { + const client = await createSealClient(corp); + const me = await getMe(client); + return { + corp: { + id: corp.id, + name: corp.name, + sourceType: corp.source.type + }, + ok: true, + stages: [ + { + name: "seal.whoami", + ok: true, + user: me.user, + tenant: me.tenant + } + ] + }; + } + + clearCorpTokenCache(corp.id); + const source = corp.source; + const appKey = source.appKey ?? source.key; + const appSecurity = source.appSecurity ?? source.password; + const sealUrl = (corp.seal.url ?? source.sealUrl ?? `https://${source.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); + const uid = source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`; + const stages: Array> = []; + + if (!appKey || !appSecurity) { + return { + corp: { + id: corp.id, + name: corp.name, + sourceType: corp.source.type + }, + ok: false, + stages: [ + { + name: "hose.openapi", + ok: false, + error: "Hose source requires appKey/key and appSecurity/password" + } + ] + }; + } + + const openapi = await runDiagnoseStage("hose.openapi", async () => { + const json = await postJson(`${source.domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, { + appKey, + appSecurity + }); + const value = objectValue(json.value); + const token = stringValue(value.accessToken) ?? stringValue(json.accessToken) ?? stringValue(json.token); + if (!token) throw new Error("Hose login did not return an access token"); + return { + token, + public: { + corporationId: stringValue(value.corporationId) ?? stringValue(objectValue(value.corporation).id), + expireTime: numberValue(value.expireTime) + } + }; + }); + stages.push(openapi.public); + + const openapiToken = openapi.private?.token; + const provisional = openapiToken + ? await runDiagnoseStage("hose.provisional", async () => { + const json = await postJson( + `${source.domain.replace(/\/+$/, "")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(openapiToken)}`, + { + uid, + pageType: "home", + expireDate: 7200 + } + ); + const url = stringValue(objectValue(json.value).message); + if (!url) throw new Error("Hose CloseAPI did not return a provisional auth URL"); + const token = new URL(url).searchParams.get("accessToken"); + if (!token) throw new Error("Hose provisional auth URL did not include accessToken"); + return { + token, + public: { + uid, + enterpriseUrl: redactSensitiveText(url) + } + }; + }) + : skippedStage("hose.provisional"); + stages.push(provisional.public); + + const provisionalToken = provisional.private?.token; + const sealSession = provisionalToken + ? await runDiagnoseStage("seal.sso", async () => { + const json = await getJson( + `${sealUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&returnToken=1` + ); + const data = objectValue(json.data); + const token = + stringValue(json.token) ?? + stringValue(json.accessToken) ?? + stringValue(data.token) ?? + stringValue(data.accessToken); + if (!token) throw new Error("Seal SSO did not return a bearer token"); + return { + token, + public: { + sealUrl, + expiresIn: numberValue(json.expiresIn) ?? numberValue(json.expires_in) ?? numberValue(data.expiresIn) ?? numberValue(data.expires_in) + } + }; + }) + : skippedStage("seal.sso"); + stages.push(sealSession.public); + + const sealToken = sealSession.private?.token; + const whoami = sealToken + ? await runDiagnoseStage("seal.whoami", async () => { + const json = await getJson(`${sealUrl}/api/v1/auth/me`, { + authorization: `Bearer ${sealToken}` + }); + const data = objectValue(json.data); + const user = objectValue(data.user ?? json.user); + const tenant = objectValue(data.tenant ?? json.tenant); + return { + public: { + user: { + id: stringValue(user.id), + name: stringValue(user.name), + isAdmin: booleanValue(user.isAdmin), + providerUserId: stringValue(user.providerUserId) + }, + tenant: { + id: stringValue(tenant.id), + name: stringValue(tenant.name), + tenantSlug: stringValue(tenant.tenantSlug), + hoseCorpConfig: summarizeHoseCorpConfig(tenant.hoseCorpConfig) + } + } + }; + }) + : skippedStage("seal.whoami"); + stages.push(whoami.public); + + return { + corp: { + id: corp.id, + name: corp.name, + sourceType: corp.source.type + }, + ok: stages.every((stage) => stage.ok === true), + stages + }; +} + +type DiagnoseStageResult = { + public: Record; + private?: { + token?: string; + }; +}; + +async function runDiagnoseStage( + name: string, + action: () => Promise<{ public: Record; token?: string }> +): Promise { + try { + const result = await action(); + return { + public: { + name, + ok: true, + ...compactObject(result.public) + }, + private: result.token ? { token: result.token } : undefined + }; + } catch (error) { + return { + public: { + name, + ok: false, + error: redactSensitiveText(error instanceof Error ? error.message : String(error)) + } + }; + } +} + +function skippedStage(name: string): DiagnoseStageResult { + return { + public: { + name, + ok: false, + skipped: true + } + }; +} + +async function postJson(url: string, body: Record): Promise> { + const response = await fetch(url, { + method: "POST", + headers: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }); + return parseJsonResponse(response); +} + +async function getJson(url: string, headers: Record = {}): Promise> { + const response = await fetch(url, { + headers + }); + return parseJsonResponse(response); +} + +async function parseJsonResponse(response: Response): Promise> { + const body = await response.text(); + if (!response.ok) { + throw new Error(`${response.status} ${body}`); + } + const json = JSON.parse(body) as unknown; + return objectValue(json); +} + +function objectValue(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +function stringValue(value: unknown): string | undefined { + return typeof value === "string" && value ? value : undefined; +} + +function numberValue(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function booleanValue(value: unknown): boolean | undefined { + return typeof value === "boolean" ? value : undefined; +} + +function summarizeHoseCorpConfig(value: unknown) { + const config = objectValue(value); + return compactObject({ + corporationId: stringValue(config.corporationId), + corporationName: stringValue(config.corporationName) + }); +} + +function compactObject>(value: T): T { + return Object.fromEntries( + Object.entries(value).filter(([, item]) => item !== undefined) + ) as T; +} diff --git a/src/cli/commands/billing.ts b/src/cli/commands/billing.ts new file mode 100644 index 0000000..f9527ce --- /dev/null +++ b/src/cli/commands/billing.ts @@ -0,0 +1,29 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleBillingCommand( + action: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + if (action === "status" || action === "get") { + await runTool("seal_billing_status_get", client, corp, {}, outputOptions(args.options)); + return; + } + + 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.`); +} diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts new file mode 100644 index 0000000..057b775 --- /dev/null +++ b/src/cli/commands/config.ts @@ -0,0 +1,56 @@ +import { + getEnterprisesDirCandidates, + loadCorpConfigs, + loadGlobalConfig, + resolveGlobalConfigFile, + saveGlobalConfig +} from "../../core/config/loader.js"; +import { resolveCorpConfig } from "../../core/config/manager.js"; +import { globalConfigSummary } from "../helpers.js"; +import { parseStateMode, stringOption } from "../parser.js"; +import { printJson } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export function handleConfigCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { + 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 config = saveGlobalConfig({ + stateful, + ...(defaultCorpId ? { defaultCorpId } : {}) + }); + printJson(globalConfigSummary(config)); + return; + } + + throw new Error(`Unknown config command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} diff --git a/src/cli/commands/context.ts b/src/cli/commands/context.ts new file mode 100644 index 0000000..79ef278 --- /dev/null +++ b/src/cli/commands/context.ts @@ -0,0 +1,23 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { numberOption, ruleVersionContextOptions, stringOption } from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleContextCommand( + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + await runTool( + "seal_approval_context_get", + client, + corp, + { + documentLimit: numberOption(args.options.documentLimit), + ...ruleVersionContextOptions(stringOption(args.options.ruleVersion)) + }, + outputOptions(args.options) + ); +} diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts new file mode 100644 index 0000000..a7b26ad --- /dev/null +++ b/src/cli/commands/corps.ts @@ -0,0 +1,297 @@ +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { clearCorpTokenCache } from "../../core/auth/token-store.js"; +import { + loadCorpConfigs, + loadGlobalConfig, + resolveWritableEnterprisesDir, + saveGlobalConfig +} from "../../core/config/loader.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js"; +import { selectCorp } from "../helpers.js"; +import { + inferCorpIdFromStaffId, + jsonObject, + optionalNumber, + optionalString, + requiredString, + requiredStringAlias, + safeFileName, + stringOption +} from "../parser.js"; +import { printJson } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleCorpsCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { + if (action === "list") { + const corpId = stringOption(args.options.corp); + const corps = loadCorpConfigs(); + const globalConfig = loadGlobalConfig(); + const currentCorpId = corpId ?? ( + globalConfig.stateful + ? globalConfig.defaultCorpId ?? corps[0]?.id + : undefined + ); + printJson(corps.map((item) => ({ + id: item.id, + name: item.name, + sourceType: item.source.type, + provider: (item.source as any).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 as any).provider ?? corp.source.type + }); + return; + } + + if (action === "switch") { + const corpId = maybeName; + if (!corpId) throw new Error("Usage: seal-home corps switch "); + const globalConfig = loadGlobalConfig(); + if (!globalConfig.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({ ...globalConfig, 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: Record) { + 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 domain = optionalString(input, "domain") ?? "https://app.ekuaibao.com"; + const verify = input.force === true || input.verify === false ? false : true; + const remote = corpIdInput && !verify + ? undefined + : await resolveHoseCorporation(domain, 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 config: CorpConfig = { + id, + name, + seal: { + url: sealUrl, + endpoints: { + approvalStylePreferences: "api/v1/agent/ai-approval/config" + } + }, + source: { + type: "hose", + domain, + appKey, + appSecurity, + corpId, + staffId + }, + auth: { + refreshTtl: 300 + } + }; + + if (verify) { + clearCorpTokenCache(id); + await resolveLiveSealEnterpriseConfig(config); + } + + const enterprisesDir = resolveWritableEnterprisesDir(); + mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 }); + const file = join(enterprisesDir, `${safeFileName(id)}.json`); + if (existsSync(file) && input.overwrite !== true) { + throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`); + } + + writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); + printJson({ + id, + name, + corpId, + verified: verify, + path: file + }); +} + +async function addSealCorp(input: Record) { + 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."); + } + const staffId = optionalString(input, "staffId") ?? + stringValue(remoteUser?.providerUserId) ?? + stringValue(remoteUser?.id) ?? + "seal"; + + const provider = optionalString(input, "provider") ?? + stringValue(remoteUser?.provider) ?? + stringValue((remoteTenant as any)?.providerConfig?.provider); + + const config: CorpConfig = { + 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(); + mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 }); + const file = join(enterprisesDir, `${safeFileName(id)}.json`); + if (existsSync(file) && input.overwrite !== true) { + throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`); + } + + writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); + printJson({ + id, + name: config.name, + tenantId, + tenantSlug, + verified: verify, + path: file + }); +} + +async function resolveHoseCorporation(domain: string, appKey: string, appSecurity: string) { + const response = await fetch(`${domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, { + method: "POST", + headers: { + "content-type": "application/json" + }, + body: JSON.stringify({ + appKey, + appSecurity + }) + }); + + if (!response.ok) { + const body = await response.text().catch(() => ""); + throw new Error(`Hose login failed: ${response.status}${body ? ` ${body}` : ""}`); + } + + const data = (await response.json()) as { + value?: { + corporationId?: string; + corporation?: { + id?: string; + name?: string; + }; + }; + }; + const corporationId = data.value?.corporationId ?? data.value?.corporation?.id; + return corporationId + ? { + id: corporationId, + name: data.value?.corporation?.name + } + : undefined; +} + +async function resolveSealWhoami(sealUrl: string, token: string) { + const json = await getJson(`${sealUrl}/api/v1/auth/me`, { + authorization: `Bearer ${token}` + }); + const data = objectValue(json.data); + return { + user: objectValue(data.user ?? json.user), + tenant: objectValue(data.tenant ?? json.tenant) + }; +} + +async function getJson(url: string, headers: Record = {}): Promise> { + const response = await fetch(url, { + headers + }); + const body = await response.text(); + if (!response.ok) { + throw new Error(`${response.status} ${body}`); + } + const json = JSON.parse(body) as unknown; + return objectValue(json); +} + +function objectValue(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +function stringValue(value: unknown): string | undefined { + return typeof value === "string" && value ? value : undefined; +} diff --git a/src/cli/commands/delegation.ts b/src/cli/commands/delegation.ts new file mode 100644 index 0000000..9e6f6bd --- /dev/null +++ b/src/cli/commands/delegation.ts @@ -0,0 +1,34 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { stringOption } from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleDelegationCommand( + action: string | undefined, + maybeName: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + if (action === "list") { + await runTool("seal_delegation_list", client, corp, {}, outputOptions(args.options)); + return; + } + + 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.`); +} diff --git a/src/cli/commands/llm.ts b/src/cli/commands/llm.ts new file mode 100644 index 0000000..cd1e891 --- /dev/null +++ b/src/cli/commands/llm.ts @@ -0,0 +1,24 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleLlmCommand( + action: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + 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.`); +} diff --git a/src/cli/commands/mcp.ts b/src/cli/commands/mcp.ts new file mode 100644 index 0000000..a0cc342 --- /dev/null +++ b/src/cli/commands/mcp.ts @@ -0,0 +1,5 @@ +import { startServer } from "../../server.js"; + +export async function handleMcpCommand() { + await startServer(); +} diff --git a/src/cli/commands/permissions.ts b/src/cli/commands/permissions.ts new file mode 100644 index 0000000..b14347b --- /dev/null +++ b/src/cli/commands/permissions.ts @@ -0,0 +1,24 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handlePermissionsCommand( + action: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + 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.`); +} diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts new file mode 100644 index 0000000..4432061 --- /dev/null +++ b/src/cli/commands/probe.ts @@ -0,0 +1,8 @@ +import { runProbe } from "../../probe.js"; +import { stringOption } from "../parser.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleProbeCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { + const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined); + await runProbe({ corpId }); +} diff --git a/src/cli/commands/rules.ts b/src/cli/commands/rules.ts new file mode 100644 index 0000000..a4420ed --- /dev/null +++ b/src/cli/commands/rules.ts @@ -0,0 +1,144 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool, runToolResult } from "../helpers.js"; +import { + booleanOption, + numberOption, + parseRuleVersionSelector, + ruleVersionGetOptions, + ruleVersionSearchOptions, + splitOption, + stringOption +} from "../parser.js"; +import { + outputOptions, + printJson, + protectLargeRuleListOutput, + RULE_SUMMARY_FIELDS +} from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleRulesCommand( + action: string | undefined, + maybeName: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + 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 version = maybeName ?? stringOption(args.options.version); + if (!version) throw new Error("Usage: seal-home rules version "); + await runTool( + "seal_approval_rule_version_get", + client, + corp, + parseRuleVersionSelector(version), + 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.`); +} diff --git a/src/cli/commands/service.ts b/src/cli/commands/service.ts new file mode 100644 index 0000000..f865d03 --- /dev/null +++ b/src/cli/commands/service.ts @@ -0,0 +1,19 @@ +import { homedir } from "node:os"; +import { join } from "node:path"; +import { VERSION } from "../../version.js"; +import { runServiceCommand } from "../service.js"; +import { printJson } from "../printer.js"; +import type { CliRuntime } from "../types.js"; + +export const STATE_DIR = join(homedir(), ".config", "seal-home"); + +export async function handleServiceCommand(action: string | undefined, runtime: CliRuntime) { + const result = await runServiceCommand(action, { + appRoot: runtime.appRoot, + entryFile: runtime.entryFile, + stateDir: STATE_DIR, + version: VERSION, + launcher: runtime.launcher + }); + if (result !== undefined) printJson(result); +} diff --git a/src/cli/commands/simulation.ts b/src/cli/commands/simulation.ts new file mode 100644 index 0000000..8239e33 --- /dev/null +++ b/src/cli/commands/simulation.ts @@ -0,0 +1,107 @@ +import { existsSync, readFileSync } from "node:fs"; +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { + booleanOption, + jsonObject, + numberOption, + splitOption, + stringOption +} from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleSimulationCommand( + action: string | undefined, + maybeName: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + 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; + } + + 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(readFileSync(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 (!existsSync(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.`); +} diff --git a/src/cli/commands/source.ts b/src/cli/commands/source.ts new file mode 100644 index 0000000..4917334 --- /dev/null +++ b/src/cli/commands/source.ts @@ -0,0 +1,12 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js"; +import { printJson } from "../printer.js"; + +export async function handleSourceCommand(action: string | undefined, corp: CorpConfig) { + if (action === "config") { + printJson(await resolveLiveSealEnterpriseConfig(corp)); + return; + } + + throw new Error(`Unknown source command: ${action ?? ""}. Run 'seal-home help' for available commands.`); +} diff --git a/src/cli/commands/tool.ts b/src/cli/commands/tool.ts new file mode 100644 index 0000000..82e62a7 --- /dev/null +++ b/src/cli/commands/tool.ts @@ -0,0 +1,16 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { jsonObject } from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleToolCommand( + action: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + if (!action) throw new Error("Usage: seal-home tool [--json '{...}']"); + await runTool(action, client, corp, jsonObject(args.json), outputOptions(args.options)); +} diff --git a/src/cli/commands/tools.ts b/src/cli/commands/tools.ts new file mode 100644 index 0000000..c798c1b --- /dev/null +++ b/src/cli/commands/tools.ts @@ -0,0 +1,6 @@ +import { sealTools } from "../../domains/seal/tools.js"; +import { printJson } from "../printer.js"; + +export function handleToolsListCommand() { + printJson(sealTools.map((tool) => ({ name: tool.name, description: tool.description }))); +} diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts new file mode 100644 index 0000000..3372a3d --- /dev/null +++ b/src/cli/commands/update.ts @@ -0,0 +1,47 @@ +import { spawnSync } from "node:child_process"; +import { isCompiledBinary } from "../../core/runtime.js"; +import { VERSION } from "../../version.js"; +import { runServiceCommand, serviceStatus } from "../service.js"; +import { printJson } from "../printer.js"; +import { STATE_DIR } from "./service.js"; +import type { CliRuntime } from "../types.js"; + +export async function handleUpdateCommand(runtime: CliRuntime) { + 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); + + if (!isCompiledBinary()) { + 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: string, args: string[], options: { cwd?: string } = {}) { + 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}`); + } +} diff --git a/src/cli/commands/users.ts b/src/cli/commands/users.ts new file mode 100644 index 0000000..c23721a --- /dev/null +++ b/src/cli/commands/users.ts @@ -0,0 +1,68 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { stringOption } from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleUsersCommand( + action: string | undefined, + maybeName: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + 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.`); +} diff --git a/src/cli/commands/webhook.ts b/src/cli/commands/webhook.ts new file mode 100644 index 0000000..f07252e --- /dev/null +++ b/src/cli/commands/webhook.ts @@ -0,0 +1,142 @@ +import type { CorpConfig } from "../../core/config/types.js"; +import type { createSealClient } from "../../core/http/factory.js"; +import { runTool } from "../helpers.js"; +import { + booleanOption, + parseWebhookMode, + stringOption, + webhookRateOption, + webhookShowSecretOption +} from "../parser.js"; +import { outputOptions } from "../printer.js"; +import type { ParsedArgs } from "../types.js"; + +export async function handleWebhookCommand( + action: string | undefined, + maybeName: string | undefined, + client: Awaited>, + corp: CorpConfig, + args: ParsedArgs +) { + 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.`); +} diff --git a/src/cli/helpers.ts b/src/cli/helpers.ts new file mode 100644 index 0000000..390d05b --- /dev/null +++ b/src/cli/helpers.ts @@ -0,0 +1,58 @@ +import { getEnterprisesDirCandidates, loadCorpConfigs, loadGlobalConfig, resolveGlobalConfigFile } from "../core/config/loader.js"; +import { resolveCorpConfig } from "../core/config/manager.js"; +import { createSealClient } from "../core/http/factory.js"; +import { sealTools, type SealTool } from "../domains/seal/tools.js"; +import type { CorpConfig, GlobalConfig } from "../core/config/types.js"; +import { printJson } from "./printer.js"; +import type { OutputOptions } from "./types.js"; + +export function selectCorp(corpId?: string): CorpConfig { + const corps = loadCorpConfigs(); + const globalConfig = loadGlobalConfig(); + return resolveCorpConfig( + corps, + { + stateful: globalConfig.stateful, + defaultCorpId: globalConfig.defaultCorpId, + corpId + }, + getEnterprisesDirCandidates() + ); +} + +export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) { + return { + mode: config.stateful ? "stateful" : "stateless", + stateful: config.stateful, + ...(config.stateful && config.defaultCorpId + ? { defaultCorpId: config.defaultCorpId } + : {}), + configFile: resolveGlobalConfigFile() + }; +} + +export async function runTool( + name: string, + client: Awaited>, + corp: CorpConfig, + params: Record, + options: OutputOptions = {} +) { + printJson(await runToolResult(name, client, corp, params), options); +} + +export async function runToolResult( + name: string, + client: Awaited>, + corp: CorpConfig, + params: Record +) { + 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 as SealTool["handler"]; + return handler(client, compactParams as never, { corp }); +} diff --git a/src/cli/parser.ts b/src/cli/parser.ts new file mode 100644 index 0000000..97b41fe --- /dev/null +++ b/src/cli/parser.ts @@ -0,0 +1,196 @@ +import type { WebhookMode } from "../domains/seal/types.js"; +import type { ParsedArgs } from "./types.js"; + +export function parseArgs(argv: string[]): ParsedArgs { + const command: string[] = []; + const options: Record = {}; + let json: unknown; + + 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"); + json = 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 }; +} + +export function jsonObject(value: unknown): Record { + if (value === undefined) return {}; + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("--json must be an object"); + } + return value as Record; +} + +export function stringOption(value: string | boolean | undefined): string | undefined { + return typeof value === "string" ? value : undefined; +} + +export function numberOption(value: string | boolean | undefined): number | undefined { + if (typeof value !== "string") return undefined; + const number = Number(value); + if (!Number.isFinite(number)) throw new Error(`Invalid number: ${value}`); + return number; +} + +export function splitOption(value: string | boolean | undefined): string[] | undefined { + if (typeof value !== "string") return undefined; + const items = value.split(",").map((item) => item.trim()).filter(Boolean); + return items.length ? items : undefined; +} + +export function booleanOption(value: string | boolean | undefined): boolean | undefined { + if (value === undefined) return undefined; + if (typeof value === "boolean") return value; + if (value === "true") return true; + if (value === "false") return false; + throw new Error(`Invalid boolean: ${value}`); +} + +export function requiredString(input: Record, key: string): string { + const value = optionalString(input, key); + if (!value) throw new Error(`Missing required JSON field: ${key}`); + return value; +} + +export function requiredStringAlias(input: Record, keys: string[]): string { + for (const key of keys) { + const value = optionalString(input, key); + if (value) return value; + } + throw new Error(`Missing required JSON field: ${keys.join(" or ")}`); +} + +export function optionalString(input: Record, key: string): string | undefined { + const value = input[key]; + return typeof value === "string" && value.trim() ? value.trim() : undefined; +} + +export function optionalNumber(input: Record, key: string): number | undefined { + const value = input[key]; + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +export function inferCorpIdFromStaffId(staffId: string): string | undefined { + const [corpId] = staffId.split(":", 1); + return corpId || undefined; +} + +export function safeFileName(value: string): string { + return value.replace(/[^a-zA-Z0-9._-]/g, "_"); +} + +export function parseStateMode(value: string): boolean { + const normalized = value.trim().toLowerCase(); + if (["stateful", "state", "有状态"].includes(normalized)) return true; + if (["stateless", "无状态"].includes(normalized)) return false; + throw new Error("Invalid config mode. Use stateful or stateless."); +} + +export function parseRuleVersionSelector(value: string) { + if (value === "latest") return { latest: true }; + const versionNumber = Number(value); + if (Number.isInteger(versionNumber) && versionNumber > 0) { + return { versionNumber }; + } + return { versionId: value }; +} + +export function ruleVersionSearchOptions(value?: string) { + 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 { + ruleVersionScope: "version", + ruleVersionId: selector.versionId + }; +} + +export function ruleVersionContextOptions(value?: string) { + 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 }; +} + +export function ruleVersionGetOptions(value?: string) { + 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 }; +} + +export function parseWebhookMode(value?: string): WebhookMode | undefined { + if (!value) return undefined; + const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_"); + const aliases: Record = { + 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; +} + +export function webhookRateOption(options: Record): number | undefined { + 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; +} + +export function webhookShowSecretOption(options: Record): boolean | undefined { + return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]); +} diff --git a/src/cli/printer.ts b/src/cli/printer.ts new file mode 100644 index 0000000..15708d3 --- /dev/null +++ b/src/cli/printer.ts @@ -0,0 +1,145 @@ +import { writeFileSync } from "node:fs"; +import { booleanOption, stringOption } from "./parser.js"; +import type { OutputOptions } from "./types.js"; + +export const RULE_LIST_FULL_COUNT_LIMIT = 100; +export const RULE_LIST_FULL_BYTES_LIMIT = 120_000; +export const RULE_SUMMARY_FIELDS = ["id", "code", "status", "strictness", "scope", "createdAt", "updatedAt"]; +export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000; + +export function formatConsoleOutput(values: unknown[]): string { + return values.map((value) => (typeof value === "string" ? value : String(value))).join(" "); +} + +export function joinOutput(lines: string[]): string { + if (!lines.length) return ""; + return `${lines.join("\n")}\n`; +} + +export function redactSensitiveText(value: string): string { + return value + .replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi, "$1") + .replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1"); +} + +export function printJson(value: unknown, options: OutputOptions = {}) { + protectLargeOutput(value, options); + const json = `${JSON.stringify(value, null, 2)}\n`; + if (options.outputFile) { + writeFileSync(options.outputFile, json); + console.log(JSON.stringify({ outputFile: options.outputFile, bytes: Buffer.byteLength(json, "utf-8") }, null, 2)); + return; + } + console.log(json.trimEnd()); +} + +export function protectLargeOutput(result: unknown, options: OutputOptions = {}) { + 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.` + ); + } +} + +export function protectLargeRuleListOutput(result: unknown, allowFull: boolean) { + if (allowFull) return; + + const data = result && typeof result === "object" ? (result as { + count?: unknown; + rules?: unknown; + }) : {}; + const count = typeof data.count === "number" ? data.count : undefined; + const rulesCount = Array.isArray(data.rules) ? data.rules.length : undefined; + const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); + const effectiveCount = count ?? rulesCount ?? 0; + + if (effectiveCount > RULE_LIST_FULL_COUNT_LIMIT || bodyBytes > RULE_LIST_FULL_BYTES_LIMIT) { + 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.` + ); + } +} + +export function outputOptions(options: Record): OutputOptions { + return { + allowFull: booleanOption(options.full) === true, + outputFile: stringOption(options.outputFile) ?? stringOption(options["output-file"]) + }; +} + +export function printHelp() { + console.log(`seal-home CLI + +Usage: + seal-home version + seal-home mcp + 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 ] +`); +} diff --git a/src/cli/runner.ts b/src/cli/runner.ts index dc4cb27..8c18d23 100755 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -1,38 +1,41 @@ #!/usr/bin/env bun -import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import { - getEnterprisesDirCandidates, - loadCorpConfigs, - loadGlobalConfig, - resolveGlobalConfigFile, - resolveWritableEnterprisesDir, - saveGlobalConfig -} from "../core/config/loader.js"; -import { resolveCorpConfig } from "../core/config/manager.js"; import { createSealClient } from "../core/http/factory.js"; -import { resolveLiveSealEnterpriseConfig } from "../domains/seal/source.js"; -import { getMe } from "../domains/seal/api.js"; -import { sealTools, type SealTool } from "../domains/seal/tools.js"; -import { CorpConfig } from "../core/config/types.js"; -import type { WebhookMode } from "../domains/seal/types.js"; -import { clearCorpTokenCache } from "../core/auth/token-store.js"; -import { getHoseProvisionalAuthLink } from "../core/auth/hose.js"; import { VERSION } from "../version.js"; -import { runServiceCommand, serviceStatus, type ServiceConfig } from "./service.js"; -import { startServer } from "../server.js"; -import { runProbe } from "../probe.js"; +import { handleApprovalRunsCommand } from "./commands/approval-runs.js"; +import { handleAuthCommand } from "./commands/auth.js"; +import { handleBillingCommand } from "./commands/billing.js"; +import { handleConfigCommand } from "./commands/config.js"; +import { handleContextCommand } from "./commands/context.js"; +import { handleCorpsCommand } from "./commands/corps.js"; +import { handleDelegationCommand } from "./commands/delegation.js"; +import { handleLlmCommand } from "./commands/llm.js"; +import { handleMcpCommand } 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 { handleSourceCommand } from "./commands/source.js"; +import { handleToolCommand } from "./commands/tool.js"; +import { handleToolsListCommand } from "./commands/tools.js"; +import { handleUpdateCommand } from "./commands/update.js"; +import { handleUsersCommand } from "./commands/users.js"; +import { handleWebhookCommand } from "./commands/webhook.js"; +import { selectCorp } from "./helpers.js"; +import { parseArgs, stringOption } from "./parser.js"; +import { + formatConsoleOutput, + joinOutput, + printHelp, + printJson, + redactSensitiveText +} from "./printer.js"; +import type { CliResult, CliRunOptions, CliRuntime } from "./types.js"; const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url)))); -const STATE_DIR = join(homedir(), ".config", "seal-home"); -const RULE_LIST_FULL_COUNT_LIMIT = 100; -const RULE_LIST_FULL_BYTES_LIMIT = 120_000; -const RULE_SUMMARY_FIELDS = ["id", "code", "status", "strictness", "scope", "createdAt", "updatedAt"]; -const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000; const KNOWN_AREAS = new Set([ "config", "service", @@ -58,41 +61,16 @@ const KNOWN_AREAS = new Set([ "probe" ]); -type ParsedArgs = { - command: string[]; - options: Record; - json?: unknown; -}; - -type OutputOptions = { - allowFull?: boolean; - outputFile?: string; -}; - -export type CliResult = { - stdout: string; - stderr: string; - isError: boolean; - exitCode: number; -}; - -export type CliRunOptions = { - appRoot?: string; - entryFile?: string; - launcher?: ServiceConfig["launcher"]; -}; - -type CliRuntime = { - appRoot: string; - entryFile: string; - launcher?: ServiceConfig["launcher"]; -}; +export type { CliResult, CliRunOptions } from "./types.js"; let runQueue = Promise.resolve(); export function runCli(argv: string[], options: CliRunOptions = {}): Promise { const run = runQueue.then(() => runCliOnce(argv, options)); - runQueue = run.then(() => undefined, () => undefined); + runQueue = run.then( + () => undefined, + () => undefined + ); return run; } @@ -163,1501 +141,109 @@ async function dispatch(argv: string[], runtime: CliRuntime) { 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 config = saveGlobalConfig({ - stateful, - ...(defaultCorpId ? { defaultCorpId } : {}) - }); - printJson(globalConfigSummary(config)); - return; - } - if (area === "mcp" || area === "server") { - await startServer(); + await handleMcpCommand(); return; } if (area === "probe") { - const corpId = maybeName ?? stringOption(args.options.corp) ?? (action && action !== "--corp" ? action : undefined); - await runProbe({ corpId }); + await handleProbeCommand(action, maybeName, args); + return; + } + + if (area === "config") { + handleConfigCommand(action, maybeName, args); 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); + await handleServiceCommand(action, runtime); return; } if (area === "update") { - await updateAndRestart(runtime); + await handleUpdateCommand(runtime); return; } if (area === "tools" && action === "list") { - printJson(sealTools.map((tool) => ({ name: tool.name, description: tool.description }))); + handleToolsListCommand(); return; } - if (area === "corps" && action === "list") { - const corpId = stringOption(args.options.corp); - const corps = loadCorpConfigs(); - const globalConfig = loadGlobalConfig(); - const currentCorpId = corpId ?? ( - globalConfig.stateful - ? globalConfig.defaultCorpId ?? corps[0]?.id - : undefined - ); - printJson(corps.map((item) => ({ - id: item.id, - name: item.name, - sourceType: item.source.type, - provider: (item.source as any).provider ?? item.source.type, - current: item.id === currentCorpId - }))); - return; - } - - if (area === "corps" && action === "current") { - const corp = selectCorp(stringOption(args.options.corp)); - printJson({ - id: corp.id, - name: corp.name, - sourceType: corp.source.type, - provider: (corp.source as any).provider ?? corp.source.type - }); - return; - } - - if (area === "corps" && action === "switch") { - const corpId = maybeName; - if (!corpId) throw new Error("Usage: seal-home corps switch "); - const globalConfig = loadGlobalConfig(); - if (!globalConfig.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({ ...globalConfig, stateful: true, defaultCorpId: corp.id }); - printJson({ - current: true, - id: corp.id, - name: corp.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)); + if (area === "corps") { + await handleCorpsCommand(action, maybeName, args); return; } const corp = selectCorp(stringOption(args.options.corp)); - if (area === "source" && action === "config") { - printJson(await resolveLiveSealEnterpriseConfig(corp)); + if (area === "source") { + await handleSourceCommand(action, 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)); + if (area === "auth") { + await handleAuthCommand(action, corp, args); return; } const client = await createSealClient(corp); - if (area === "delegation" && action === "list") { - await runTool("seal_delegation_list", client, corp, {}, outputOptions(args.options)); + if (area === "delegation") { + await handleDelegationCommand(action, maybeName, client, corp, args); 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)); + if (area === "users") { + await handleUsersCommand(action, maybeName, client, corp, args); 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)); + if (area === "llm") { + await handleLlmCommand(action, client, corp, args); 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)); + if (area === "permissions") { + await handlePermissionsCommand(action, client, corp, args); 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)); + if (area === "billing") { + await handleBillingCommand(action, client, corp, args); 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)); + if (area === "webhook" || area === "webhooks") { + await handleWebhookCommand(action, maybeName, client, corp, args); 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)); + await handleContextCommand(client, corp, args); return; } - if (area === "rules" && action === "count") { - await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options)); + if (area === "rules") { + await handleRulesCommand(action, maybeName, client, corp, args); 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); + if (area === "approval-runs") { + await handleApprovalRunsCommand(action, maybeName, client, corp, args); 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 version = maybeName ?? stringOption(args.options.version); - if (!version) throw new Error("Usage: seal-home rules version "); - await runTool("seal_approval_rule_version_get", client, corp, parseRuleVersionSelector(version), 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)); + if (area === "simulation") { + await handleSimulationCommand(action, maybeName, client, corp, args); 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(readFileSync(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 (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`); - await runTool("seal_simulation_material_package_upload", client, corp, { filePath }, outputOptions(args.options)); + await handleToolCommand(action, client, corp, args); return; } throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-home help' for available commands.`); } - -async function updateAndRestart(runtime: CliRuntime) { - 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: string, args: string[], options: { cwd?: string } = {}) { - 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}`); - } -} - -async function runTool( - name: string, - client: Awaited>, - corp: CorpConfig, - params: Record, - options: OutputOptions = {} -) { - printJson(await runToolResult(name, client, corp, params), options); -} - -async function runToolResult( - name: string, - client: Awaited>, - corp: CorpConfig, - params: Record -) { - 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 as SealTool["handler"]; - return handler(client, compactParams as never, { corp }); -} - -function protectLargeRuleListOutput(result: unknown, allowFull: boolean) { - if (allowFull) return; - - const data = result && typeof result === "object" ? result as { - count?: unknown; - rules?: unknown; - } : {}; - const count = typeof data.count === "number" ? data.count : undefined; - const rulesCount = Array.isArray(data.rules) ? data.rules.length : undefined; - const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); - const effectiveCount = count ?? rulesCount ?? 0; - - if (effectiveCount > RULE_LIST_FULL_COUNT_LIMIT || bodyBytes > RULE_LIST_FULL_BYTES_LIMIT) { - 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: unknown, options: OutputOptions = {}) { - 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: Record): OutputOptions { - return { - allowFull: booleanOption(options.full) === true, - outputFile: stringOption(options.outputFile) ?? stringOption(options["output-file"]) - }; -} - -function selectCorp(corpId?: string): CorpConfig { - const corps = loadCorpConfigs(); - const globalConfig = loadGlobalConfig(); - return resolveCorpConfig( - corps, - { - stateful: globalConfig.stateful, - defaultCorpId: globalConfig.defaultCorpId, - corpId - }, - getEnterprisesDirCandidates() - ); -} - -function globalConfigSummary(config = loadGlobalConfig()) { - return { - mode: config.stateful ? "stateful" : "stateless", - stateful: config.stateful, - ...(config.stateful && config.defaultCorpId - ? { defaultCorpId: config.defaultCorpId } - : {}), - configFile: resolveGlobalConfigFile() - }; -} - -function parseStateMode(value: string): boolean { - const normalized = value.trim().toLowerCase(); - if (["stateful", "state", "有状态"].includes(normalized)) return true; - if (["stateless", "无状态"].includes(normalized)) return false; - throw new Error("Invalid config mode. Use stateful or stateless."); -} - -async function addHoseCorp(input: Record) { - 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 domain = optionalString(input, "domain") ?? "https://app.ekuaibao.com"; - const verify = input.force === true || input.verify === false ? false : true; - const remote = corpIdInput && !verify - ? undefined - : await resolveHoseCorporation(domain, 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 config: CorpConfig = { - id, - name, - seal: { - url: sealUrl, - endpoints: { - approvalStylePreferences: "api/v1/agent/ai-approval/config" - } - }, - source: { - type: "hose", - domain, - appKey, - appSecurity, - corpId, - staffId - }, - auth: { - refreshTtl: 300 - } - }; - - if (verify) { - clearCorpTokenCache(id); - await resolveLiveSealEnterpriseConfig(config); - } - - const enterprisesDir = resolveWritableEnterprisesDir(); - mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 }); - const file = join(enterprisesDir, `${safeFileName(id)}.json`); - if (existsSync(file) && input.overwrite !== true) { - throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`); - } - - writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); - printJson({ - id, - name, - corpId, - verified: verify, - path: file - }); -} - -async function addSealCorp(input: Record) { - 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."); - } - const staffId = optionalString(input, "staffId") ?? - stringValue(remoteUser?.providerUserId) ?? - stringValue(remoteUser?.id) ?? - "seal"; - - const provider = optionalString(input, "provider") ?? - stringValue(remoteUser?.provider) ?? - stringValue((remoteTenant as any)?.providerConfig?.provider); - - const config: CorpConfig = { - 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(); - mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 }); - const file = join(enterprisesDir, `${safeFileName(id)}.json`); - if (existsSync(file) && input.overwrite !== true) { - throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`); - } - - writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); - printJson({ - id, - name: config.name, - tenantId, - tenantSlug, - verified: verify, - path: file - }); -} - -async function diagnoseAuth(corp: CorpConfig) { - if (corp.source.type !== "hose") { - const client = await createSealClient(corp); - const me = await getMe(client); - return { - corp: { - id: corp.id, - name: corp.name, - sourceType: corp.source.type - }, - ok: true, - stages: [ - { - name: "seal.whoami", - ok: true, - user: me.user, - tenant: me.tenant - } - ] - }; - } - - clearCorpTokenCache(corp.id); - const source = corp.source; - const appKey = source.appKey ?? source.key; - const appSecurity = source.appSecurity ?? source.password; - const sealUrl = (corp.seal.url ?? source.sealUrl ?? `https://${source.corpId.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); - const uid = source.staffId.includes(":") ? source.staffId : `${source.corpId}:${source.staffId}`; - const stages: Array> = []; - - if (!appKey || !appSecurity) { - return { - corp: { - id: corp.id, - name: corp.name, - sourceType: corp.source.type - }, - ok: false, - stages: [ - { - name: "hose.openapi", - ok: false, - error: "Hose source requires appKey/key and appSecurity/password" - } - ] - }; - } - - const openapi = await runDiagnoseStage("hose.openapi", async () => { - const json = await postJson(`${source.domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, { - appKey, - appSecurity - }); - const value = objectValue(json.value); - const token = stringValue(value.accessToken) ?? stringValue(json.accessToken) ?? stringValue(json.token); - if (!token) throw new Error("Hose login did not return an access token"); - return { - token, - public: { - corporationId: stringValue(value.corporationId) ?? stringValue(objectValue(value.corporation).id), - expireTime: numberValue(value.expireTime) - } - }; - }); - stages.push(openapi.public); - - const openapiToken = openapi.private?.token; - const provisional = openapiToken - ? await runDiagnoseStage("hose.provisional", async () => { - const json = await postJson( - `${source.domain.replace(/\/+$/, "")}/api/openapi/v1.1/provisional/getProvisionalAuth?accessToken=${encodeURIComponent(openapiToken)}`, - { - uid, - pageType: "home", - expireDate: 7200 - } - ); - const url = stringValue(objectValue(json.value).message); - if (!url) throw new Error("Hose CloseAPI did not return a provisional auth URL"); - const token = new URL(url).searchParams.get("accessToken"); - if (!token) throw new Error("Hose provisional auth URL did not include accessToken"); - return { - token, - public: { - uid, - enterpriseUrl: redactSensitiveText(url) - } - }; - }) - : skippedStage("hose.provisional"); - stages.push(provisional.public); - - const provisionalToken = provisional.private?.token; - const sealSession = provisionalToken - ? await runDiagnoseStage("seal.sso", async () => { - const json = await getJson( - `${sealUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&returnToken=1` - ); - const data = objectValue(json.data); - const token = - stringValue(json.token) ?? - stringValue(json.accessToken) ?? - stringValue(data.token) ?? - stringValue(data.accessToken); - if (!token) throw new Error("Seal SSO did not return a bearer token"); - return { - token, - public: { - sealUrl, - expiresIn: numberValue(json.expiresIn) ?? numberValue(json.expires_in) ?? numberValue(data.expiresIn) ?? numberValue(data.expires_in) - } - }; - }) - : skippedStage("seal.sso"); - stages.push(sealSession.public); - - const sealToken = sealSession.private?.token; - const whoami = sealToken - ? await runDiagnoseStage("seal.whoami", async () => { - const json = await getJson(`${sealUrl}/api/v1/auth/me`, { - authorization: `Bearer ${sealToken}` - }); - const data = objectValue(json.data); - const user = objectValue(data.user ?? json.user); - const tenant = objectValue(data.tenant ?? json.tenant); - return { - public: { - user: { - id: stringValue(user.id), - name: stringValue(user.name), - isAdmin: booleanValue(user.isAdmin), - providerUserId: stringValue(user.providerUserId) - }, - tenant: { - id: stringValue(tenant.id), - name: stringValue(tenant.name), - tenantSlug: stringValue(tenant.tenantSlug), - hoseCorpConfig: summarizeHoseCorpConfig(tenant.hoseCorpConfig) - } - } - }; - }) - : skippedStage("seal.whoami"); - stages.push(whoami.public); - - return { - corp: { - id: corp.id, - name: corp.name, - sourceType: corp.source.type - }, - ok: stages.every((stage) => stage.ok === true), - stages - }; -} - -type DiagnoseStageResult = { - public: Record; - private?: { - token?: string; - }; -}; - -async function runDiagnoseStage( - name: string, - action: () => Promise<{ public: Record; token?: string }> -): Promise { - try { - const result = await action(); - return { - public: { - name, - ok: true, - ...compactObject(result.public) - }, - private: result.token ? { token: result.token } : undefined - }; - } catch (error) { - return { - public: { - name, - ok: false, - error: redactSensitiveText(error instanceof Error ? error.message : String(error)) - } - }; - } -} - -function skippedStage(name: string): DiagnoseStageResult { - return { - public: { - name, - ok: false, - skipped: true - } - }; -} - -async function postJson(url: string, body: Record): Promise> { - const response = await fetch(url, { - method: "POST", - headers: { - "content-type": "application/json" - }, - body: JSON.stringify(body) - }); - return parseJsonResponse(response); -} - -async function getJson(url: string, headers: Record = {}): Promise> { - const response = await fetch(url, { - headers - }); - return parseJsonResponse(response); -} - -async function resolveSealWhoami(sealUrl: string, token: string) { - const json = await getJson(`${sealUrl}/api/v1/auth/me`, { - authorization: `Bearer ${token}` - }); - const data = objectValue(json.data); - return { - user: objectValue(data.user ?? json.user), - tenant: objectValue(data.tenant ?? json.tenant) - }; -} - -async function parseJsonResponse(response: Response): Promise> { - const body = await response.text(); - if (!response.ok) { - throw new Error(`${response.status} ${body}`); - } - const json = JSON.parse(body) as unknown; - return objectValue(json); -} - -function objectValue(value: unknown): Record { - return value && typeof value === "object" && !Array.isArray(value) - ? value as Record - : {}; -} - -function stringValue(value: unknown): string | undefined { - return typeof value === "string" && value ? value : undefined; -} - -function numberValue(value: unknown): number | undefined { - return typeof value === "number" && Number.isFinite(value) ? value : undefined; -} - -function booleanValue(value: unknown): boolean | undefined { - return typeof value === "boolean" ? value : undefined; -} - -function summarizeHoseCorpConfig(value: unknown) { - const config = objectValue(value); - return compactObject({ - corporationId: stringValue(config.corporationId), - corporationName: stringValue(config.corporationName) - }); -} - -function compactObject>(value: T): T { - return Object.fromEntries( - Object.entries(value).filter(([, item]) => item !== undefined) - ) as T; -} - -function requiredString(input: Record, key: string): string { - const value = optionalString(input, key); - if (!value) throw new Error(`Missing required JSON field: ${key}`); - return value; -} - -function requiredStringAlias(input: Record, keys: string[]): string { - 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: Record, key: string): string | undefined { - const value = input[key]; - return typeof value === "string" && value.trim() ? value.trim() : undefined; -} - -function optionalNumber(input: Record, key: string): number | undefined { - const value = input[key]; - return typeof value === "number" && Number.isFinite(value) ? value : undefined; -} - -function inferCorpIdFromStaffId(staffId: string): string | undefined { - const [corpId] = staffId.split(":", 1); - return corpId || undefined; -} - -async function resolveHoseCorporation(domain: string, appKey: string, appSecurity: string) { - const response = await fetch(`${domain.replace(/\/+$/, "")}/api/openapi/v1/auth/getAccessToken`, { - method: "POST", - headers: { - "content-type": "application/json" - }, - body: JSON.stringify({ - appKey, - appSecurity - }) - }); - - if (!response.ok) { - const body = await response.text().catch(() => ""); - throw new Error(`Hose login failed: ${response.status}${body ? ` ${body}` : ""}`); - } - - const data = await response.json() as { - value?: { - corporationId?: string; - corporation?: { - id?: string; - name?: string; - }; - }; - }; - const corporationId = data.value?.corporationId ?? data.value?.corporation?.id; - return corporationId - ? { - id: corporationId, - name: data.value?.corporation?.name - } - : undefined; -} - -function safeFileName(value: string): string { - return value.replace(/[^a-zA-Z0-9._-]/g, "_"); -} - -function parseRuleVersionSelector(value: string) { - if (value === "latest") return { latest: true }; - const versionNumber = Number(value); - if (Number.isInteger(versionNumber) && versionNumber > 0) { - return { versionNumber }; - } - return { versionId: value }; -} - -function ruleVersionSearchOptions(value?: string) { - 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 { - ruleVersionScope: "version", - ruleVersionId: selector.versionId - }; -} - -function ruleVersionContextOptions(value?: string) { - 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?: string) { - 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: string[]): ParsedArgs { - const command: string[] = []; - const options: Record = {}; - let json: unknown; - - 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"); - json = 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 }; -} - -function jsonObject(value: unknown): Record { - if (value === undefined) return {}; - if (!value || typeof value !== "object" || Array.isArray(value)) { - throw new Error("--json must be an object"); - } - return value as Record; -} - -function stringOption(value: string | boolean | undefined): string | undefined { - return typeof value === "string" ? value : undefined; -} - -function numberOption(value: string | boolean | undefined): number | undefined { - if (typeof value !== "string") return undefined; - const number = Number(value); - if (!Number.isFinite(number)) throw new Error(`Invalid number: ${value}`); - return number; -} - -function splitOption(value: string | boolean | undefined): string[] | undefined { - if (typeof value !== "string") return undefined; - const items = value.split(",").map((item) => item.trim()).filter(Boolean); - return items.length ? items : undefined; -} - -function parseWebhookMode(value?: string): WebhookMode | undefined { - if (!value) return undefined; - const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_"); - const aliases: Record = { - 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 webhookRateOption(options: Record): number | undefined { - 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 webhookShowSecretOption(options: Record): boolean | undefined { - return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]); -} - -function booleanOption(value: string | boolean | undefined): boolean | undefined { - if (value === undefined) return undefined; - if (typeof value === "boolean") return value; - if (value === "true") return true; - if (value === "false") return false; - throw new Error(`Invalid boolean: ${value}`); -} - -function printJson(value: unknown, options: OutputOptions = {}) { - protectLargeOutput(value, options); - const json = `${JSON.stringify(value, null, 2)}\n`; - if (options.outputFile) { - writeFileSync(options.outputFile, json); - console.log(JSON.stringify({ outputFile: options.outputFile, bytes: Buffer.byteLength(json, "utf-8") }, null, 2)); - return; - } - console.log(json.trimEnd()); -} - -function printHelp() { - console.log(`seal-home CLI - -Usage: - seal-home version - seal-home mcp - 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 ] -`); -} - -function formatConsoleOutput(values: unknown[]): string { - return values.map((value) => typeof value === "string" ? value : String(value)).join(" "); -} - -function joinOutput(lines: string[]): string { - if (!lines.length) return ""; - return `${lines.join("\n")}\n`; -} - -function redactSensitiveText(value: string): string { - return value - .replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi, "$1") - .replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1"); -} diff --git a/src/cli/types.ts b/src/cli/types.ts new file mode 100644 index 0000000..74f112d --- /dev/null +++ b/src/cli/types.ts @@ -0,0 +1,36 @@ +import type { ServiceConfig } from "./service.js"; + +export type ParsedArgs = { + command: string[]; + options: Record; + json?: unknown; +}; + +export type OutputOptions = { + allowFull?: boolean; + outputFile?: string; +}; + +export type CliResult = { + stdout: string; + stderr: string; + isError: boolean; + exitCode: number; +}; + +export type CliRunOptions = { + appRoot?: string; + entryFile?: string; + launcher?: ServiceConfig["launcher"]; +}; + +export type CliRuntime = { + appRoot: string; + entryFile: string; + launcher?: ServiceConfig["launcher"]; +}; + +export type CommandContext = { + runtime: CliRuntime; + args: ParsedArgs; +};