import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import { randomBytes } from "node:crypto"; import { join } from "node:path"; import { assertHoseAssistTenantMatches, defaultSealUrl, exchangeHoseAssistLink, fetchHoseRoleDefGroups, fetchHoseRoleStaffs, fetchHoseStaffDetails, probeHoseDomain } from "../../core/auth/hose.js"; import { clearCorpTokenCache } from "../../core/auth/token-store.js"; import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js"; import { resolveSealCustomHeaders } from "../../core/http/request-headers.js"; import { findCorpConfigFile, loadCorpConfigs, loadGlobalConfig, resolveWritableEnterprisesDir, saveGlobalConfig, updateCorpConfig } from "../../core/config/loader.js"; import { filterCorpsFuzzy } from "../../core/search/fuzzy.js"; import { sortCorpsByUsageAndRecency } from "../../core/stats/usage-tracker.js"; import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js"; import type { CorpConfig, CorpEnvironment, SealSource } from "../../core/config/types.js"; import * as api from "../../domains/seal/api.js"; import { getMe } from "../../domains/seal/api.js"; import { computeNextSyncIteration, formatSyncVersionName, saveRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js"; import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../domains/seal/webhook-replay.js"; import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js"; import { selectCorp } from "../helpers.js"; import { confirmationRequired, usageError } from "../errors.js"; import { inferCorpIdFromStaffId, booleanOption, jsonObject, numberOption, optionalNumber, optionalString, requiredString, requiredStringAlias, safeFileName, stringOption } from "../parser.js"; import { printJson } from "../printer.js"; import type { ParsedArgs } from "../types.js"; function maskSecret(value: string | undefined): string | undefined { if (!value) return undefined; if (value.length <= 8) return "****"; return `${value.slice(0, 4)}...${value.slice(-4)}`; } function resolveCorpSealUrl(corp: CorpConfig): string | undefined { if (corp.source.type === "hose") { return defaultSealUrl(corp, corp.source); } return corp.seal.url ?? (corp.source as any).sealUrl; } function formatSafeSourceDetail(source: SealSource) { if (source.type === "hose") { const key = source.appKey ?? source.key; return { type: "hose", provider: "hosecloud", domain: source.domain, corpId: source.corpId, staffId: source.staffId, appKey: maskSecret(key), hasAppSecurity: Boolean(source.appSecurity ?? source.password), sealUrl: source.sealUrl }; } if (source.type === "seal") { return { type: "seal", provider: source.provider ?? "seal", tenantId: source.tenantId, tenantSlug: source.tenantSlug, tenantName: source.tenantName, providerUserId: source.providerUserId, staffId: source.staffId, corpId: source.corpId, sealUrl: source.sealUrl, hasToken: Boolean(source.token), tokenMasked: maskSecret(source.token), expiresIn: source.expiresIn }; } return { type: "direct", provider: "direct", staffId: source.staffId, corpId: source.corpId, sealUrl: source.sealUrl, hasToken: Boolean(source.token), tokenMasked: maskSecret(source.token), expiresIn: source.expiresIn }; } export async function handleCorpsCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) { if (!action || action === "list" || action === "search" || action === "find") { const rawQuery = ( maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.q) )?.trim(); const isStrict = booleanOption(args.options.strict) === true; const envFilter = ( stringOption(args.options.env) ?? stringOption(args.options.environment) )?.trim().toLowerCase(); if ((action === "search" || action === "find") && !rawQuery && !envFilter) { throw usageError("Usage: seal-use corps search [--env ] [--strict]"); } const corpId = stringOption(args.options.corp); const allCorps = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); const currentCorpId = corpId ?? ( globalConfig.stateful ? globalConfig.defaultCorpId ?? allCorps[0]?.id : undefined ); let filtered = allCorps; if (envFilter) { filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter); } if (rawQuery) { filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict }); } if (allCorps.length === 0) { console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose 或 seal-use corps add-seal 添加企业,或运行 seal-use help 查看说明。"); } else if (isStrict && filtered.length === 0 && (action === "search" || action === "find") && rawQuery) { console.error(`提示:未在严格模式下匹配到企业 "${rawQuery}"。可以尝试省略 --strict 进行智能软搜索。`); } const sorted = sortCorpsByUsageAndRecency(filtered, currentCorpId); const isList = !action || action === "list"; const isAll = booleanOption(args.options.all) === true; const limitOpt = numberOption(args.options.limit); const defaultLimit = 10; const effectiveLimit = limitOpt !== undefined ? Math.max(1, limitOpt) : (isList && !isAll ? defaultLimit : undefined); let displayList = sorted; if (effectiveLimit !== undefined && sorted.length > effectiveLimit) { displayList = sorted.slice(0, effectiveLimit); if (isList && !isAll && limitOpt === undefined) { console.error( `ℹ️ 当前共有 ${sorted.length} 家企业,已按最近 7 天使用频次展示前 ${effectiveLimit} 家。\n` + `👉 查看全部请添加: seal-use corps list --all\n` + `👉 检索指定企业请使用: seal-use corps search ` ); } } printJson(displayList.map((item) => ({ id: item.id, name: item.name, environment: item.environment ?? "production", sourceType: item.source.type, provider: (item.source as any).provider ?? item.source.type, staffId: item.source.staffId, testCorpId: item.testCorpId, prodCorpId: item.prodCorpId, current: item.id === currentCorpId }))); return; } if (action === "get" || action === "show") { const targetCorpId = maybeName ?? stringOption(args.options.corp); if (!targetCorpId) { throw usageError("Usage: seal-use corps get "); } const corp = selectCorp(targetCorpId); const configFile = findCorpConfigFile(corp.id); const sealUrl = resolveCorpSealUrl(corp); printJson({ id: corp.id, name: corp.name, environment: corp.environment ?? "production", configFile, seal: { url: sealUrl, tenantSlug: corp.seal.tenantSlug ?? (corp.source as any).tenantSlug, customHeaderNames: corp.seal.headers ? Object.keys(corp.seal.headers) : [], customCookieNames: corp.seal.cookies ? Object.keys(corp.seal.cookies) : [], endpoints: corp.seal.endpoints }, source: formatSafeSourceDetail(corp.source), relations: { testCorpId: corp.testCorpId, prodCorpId: corp.prodCorpId }, auth: { refreshTtl: corp.auth.refreshTtl } }); return; } if (action === "current") { const corp = selectCorp(stringOption(args.options.corp)); printJson({ id: corp.id, name: corp.name, environment: corp.environment ?? "production", sourceType: corp.source.type, provider: (corp.source as any).provider ?? corp.source.type, staffId: corp.source.staffId, testCorpId: corp.testCorpId, prodCorpId: corp.prodCorpId }); return; } if (action === "mark" || action === "mark-test" || action === "mark-prod") { const corpId = maybeName ?? stringOption(args.options.corp); if (!corpId) { throw usageError("Usage: seal-use corps mark --env [--confirm]"); } const corp = selectCorp(corpId); const targetEnv = ( action === "mark-test" ? "test" : action === "mark-prod" ? "production" : (stringOption(args.options.env) ?? stringOption(args.options.environment)) ) as CorpEnvironment | undefined; if (targetEnv !== "production" && targetEnv !== "test") { throw usageError("Usage: seal-use corps mark --env [--confirm]"); } const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true; if (!confirmed) { throw confirmationRequired( `Refusing to change environment tag of enterprise '${corp.name}' (${corp.id}) to '${targetEnv}' without --confirm. Marking alters synchronization safety guards.`, `seal-use corps mark ${corp.id} --env ${targetEnv} --confirm` ); } const updated = updateCorpConfig(corp.id, { environment: targetEnv }); printJson({ id: updated.id, name: updated.name, environment: updated.environment, testCorpId: updated.testCorpId, prodCorpId: updated.prodCorpId }); return; } if (action === "bind-test") { let prodId: string | undefined; let testId: string | undefined; if (maybeName && args.command[3]) { prodId = maybeName; testId = args.command[3]; } else if (maybeName) { const corpOption = stringOption(args.options.corp); const testCorpOption = stringOption(args.options["test-corp"]) ?? stringOption(args.options.testCorp); if (corpOption) { prodId = corpOption; testId = maybeName; } else if (testCorpOption) { prodId = maybeName; testId = testCorpOption; } } if (!prodId || !testId) { throw usageError( "Usage: seal-use corps bind-test [--confirm] [--force]\n" + " or: seal-use corps bind-test --corp [--confirm] [--force]" ); } const prodCorp = selectCorp(prodId); const testCorp = selectCorp(testId); if (prodCorp.id === testCorp.id) { throw usageError(`Cannot bind enterprise '${prodCorp.id}' to itself.`); } if (prodCorp.prodCorpId && prodCorp.prodCorpId !== testCorp.id) { throw usageError( `Cannot use '${prodCorp.id}' as a production enterprise because it is already registered as a test enterprise for '${prodCorp.prodCorpId}'. Multi-tier chaining is not permitted.` ); } if (testCorp.testCorpId && testCorp.testCorpId !== prodCorp.id) { throw usageError( `Cannot bind '${testCorp.id}' as a test enterprise because it already has a bound test enterprise '${testCorp.testCorpId}'. Multi-tier chaining is not permitted.` ); } const force = booleanOption(args.options.force) === true; if ( (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) || (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) ) { if (!force) { throw confirmationRequired( `Enterprise binding conflict: production enterprise '${prodCorp.id}' is bound to '${prodCorp.testCorpId ?? "none"}', and test enterprise '${testCorp.id}' is bound to '${testCorp.prodCorpId ?? "none"}'. Overwriting an existing binding requires --force and --confirm.`, `seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm --force` ); } } const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true; if (!confirmed) { const forceFlag = force ? " --force" : ""; throw confirmationRequired( `Refusing to bind test enterprise '${testCorp.name}' (${testCorp.id}) to production enterprise '${prodCorp.name}' (${prodCorp.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${testCorp.id}' as a test environment.`, `seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm${forceFlag}` ); } if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) { try { updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined }); } catch {} } if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) { try { updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined }); } catch {} } const updatedProd = updateCorpConfig(prodCorp.id, { environment: "production", testCorpId: testCorp.id }); const updatedTest = updateCorpConfig(testCorp.id, { environment: "test", prodCorpId: prodCorp.id }); printJson({ success: true, productionEnterprise: { id: updatedProd.id, name: updatedProd.name, environment: updatedProd.environment, testCorpId: updatedProd.testCorpId }, testEnterprise: { id: updatedTest.id, name: updatedTest.name, environment: updatedTest.environment, prodCorpId: updatedTest.prodCorpId } }); return; } if (action === "unbind-test") { const targetId = maybeName ?? stringOption(args.options.corp); const corp = selectCorp(targetId); if (!corp.testCorpId && !corp.prodCorpId) { printJson({ unbound: false, message: `Enterprise '${corp.name}' (${corp.id}) does not have an active test enterprise binding.` }); return; } const prodId = corp.testCorpId ? corp.id : corp.prodCorpId!; const testId = corp.testCorpId ? corp.testCorpId : corp.id; const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true; if (!confirmed) { throw confirmationRequired( `Refusing to unbind production enterprise '${prodId}' and test enterprise '${testId}' without --confirm.`, `seal-use corps unbind-test ${corp.id} --confirm` ); } updateCorpConfig(prodId, { testCorpId: undefined }); try { updateCorpConfig(testId, { prodCorpId: undefined }); } catch {} printJson({ success: true, unboundProduction: prodId, unboundTest: testId }); return; } if (action === "sync-test") { const targetCorpId = maybeName ?? stringOption(args.options.corp); const prodCorp = selectCorp(targetCorpId); if (!prodCorp.testCorpId) { throw usageError( `Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` + `Run 'seal-use corps bind-test ${prodCorp.id} --confirm' first to establish a verified 1-to-1 association.` ); } const testCorp = selectCorp(prodCorp.testCorpId); if (testCorp.environment !== "test") { throw new Error( `Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting sync to protect non-test environments.` ); } const prodClient = await createSealClient(prodCorp); const testClient = await createSealClient(testCorp); const [ prodPref, testPref, prodRules, testRules, prodVersions, testVersions, prodDocsRes, testDocsRes ] = await Promise.all([ api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)), api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)), api.listApprovalRules(prodClient), api.listApprovalRules(testClient), api.listApprovalRuleVersions(prodClient).catch(() => []), api.listApprovalRuleVersions(testClient).catch(() => []), api.listApprovalDocuments(prodClient, { limit: 100 }).catch(() => ({ articles: [] })), api.listApprovalDocuments(testClient, { limit: 100 }).catch(() => ({ articles: [] })) ]); const prodDocs = (prodDocsRes.articles || []).filter((d) => !d.isDeleted); const testDocs = (testDocsRes.articles || []).filter((d) => !d.isDeleted); const testDocsByTitle = new Map(testDocs.map((d) => [d.title.trim(), d])); const docsToCreate = []; const docsToUpdate = []; const prodTitles = new Set(prodDocs.map((d) => d.title.trim())); for (const prodDoc of prodDocs) { const title = prodDoc.title.trim(); const existing = testDocsByTitle.get(title); if (!existing) { docsToCreate.push(prodDoc); } else { const contentChanged = existing.content !== prodDoc.content; const purposeChanged = (existing.purpose ?? "") !== (prodDoc.purpose ?? ""); const enabledChanged = existing.enabled !== prodDoc.enabled; const contentTypeChanged = existing.contentType !== prodDoc.contentType; const statusChanged = (existing.status ?? "") !== (prodDoc.status ?? ""); const scenariosChanged = JSON.stringify([...(existing.scenarios ?? [])].sort()) !== JSON.stringify([...(prodDoc.scenarios ?? [])].sort()); const tagsChanged = JSON.stringify([...(existing.tags ?? [])].sort()) !== JSON.stringify([...(prodDoc.tags ?? [])].sort()); if (contentChanged || purposeChanged || enabledChanged || contentTypeChanged || statusChanged || scenariosChanged || tagsChanged) { docsToUpdate.push({ testId: existing.id, prodDoc, reasons: [ ...(contentChanged ? ["content"] : []), ...(purposeChanged ? ["purpose"] : []), ...(enabledChanged ? ["enabled"] : []), ...(contentTypeChanged ? ["contentType"] : []), ...(statusChanged ? ["status"] : []), ...(scenariosChanged ? ["scenarios"] : []), ...(tagsChanged ? ["tags"] : []) ] }); } } } const docsToDelete = testDocs.filter( (td) => !prodTitles.has(td.title.trim()) ); const sortedProdVersions = [...prodVersions].sort((a, b) => b.versionNumber - a.versionNumber); const latestProd = sortedProdVersions[0]; const prodVersionNumber = latestProd?.versionNumber; const sortedTestVersions = [...testVersions].sort((a, b) => b.versionNumber - a.versionNumber); const targetTestExpectedVersionNumber = (sortedTestVersions[0]?.versionNumber ?? 0) + 1; const nextIteration = computeNextSyncIteration(prodCorp.name, prodVersionNumber, testVersions); const customVersionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName); const versionName = customVersionName ?? formatSyncVersionName(prodCorp.name, prodVersionNumber, nextIteration, targetTestExpectedVersionNumber); const updatedTestPref = { ...testPref, tone: prodPref.tone, language: prodPref.language, detailLevel: prodPref.detailLevel, outputFormat: prodPref.outputFormat, examples: prodPref.examples ?? [], prohibitedPhrases: prodPref.prohibitedPhrases ?? [], customInstructions: prodPref.customInstructions, decisionPreferences: prodPref.decisionPreferences, thinkingDepthPreference: prodPref.thinkingDepthPreference }; const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true; if (dryRun) { printJson({ dryRun: true, source: { id: prodCorp.id, name: prodCorp.name, environment: prodCorp.environment, latestPublishedVersion: latestProd ? { versionNumber: latestProd.versionNumber, versionName: latestProd.versionName } : null, documentsCount: prodDocs.length }, target: { id: testCorp.id, name: testCorp.name, environment: testCorp.environment }, versionMappingPlan: { sourceProdVersionNumber: prodVersionNumber ?? null, sourceProdVersionName: latestProd?.versionName ?? null, targetTestExpectedVersionNumber, targetTestPublishVersionName: versionName, iteration: nextIteration }, preferencesDiff: { decisionPreferences: { before: testPref.decisionPreferences, after: prodPref.decisionPreferences }, thinkingDepthPreference: { before: testPref.thinkingDepthPreference, after: prodPref.thinkingDepthPreference } }, rulesPlan: { sourceDraftRuleCount: prodRules.rules.length, targetExistingDraftRuleCount: testRules.rules.length, toDeleteCount: testRules.rules.length, toCreateCount: prodRules.rules.length, rulesToSync: prodRules.rules.map((r, idx) => ({ index: idx + 1, sourceRuleId: r.id, sourceRuleCode: r.code ?? idx + 1, expectedTargetCode: `rule-${idx + 1}`, description: r.description, scope: r.scope, strictness: r.strictness })) }, documentsPlan: { sourceDocumentCount: prodDocs.length, targetExistingDocumentCount: testDocs.length, toCreateCount: docsToCreate.length, toCreate: docsToCreate.map((d) => ({ title: d.title, purpose: d.purpose, contentType: d.contentType, scenarios: d.scenarios })), toUpdateCount: docsToUpdate.length, toUpdate: docsToUpdate.map((d) => ({ targetDocumentId: d.testId, title: d.prodDoc.title, reasons: d.reasons })), toDeleteCount: docsToDelete.length, toDelete: docsToDelete.map((d) => ({ targetDocumentId: d.id, title: d.title })) }, publishingPlan: { targetCorpId: testCorp.id, publishVersionName: versionName, publishTarget: "test" }, hosecloudSyncPlan: (() => { if (prodCorp.source.type !== "hose") { return { sourceType: prodCorp.source.type, skipped: true, reason: "prod source is not hose; no hosecloud credentials available" }; } const rawHose = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud"); const seen = new Set(); const distinct = rawHose.filter((i: any) => { const cid = i.corporationId ?? prodCorp.id; if (seen.has(cid)) return false; seen.add(cid); return true; }); return { sourceType: "hose", outboundName: buildTestHosecloudOutboundName(prodCorp.name), targetMode: "assisted", integrationsCount: distinct.length, integrations: distinct.map((i: any) => ({ corporationId: i.corporationId, apiOrigin: i.apiOrigin, customApiUrl: i.customApiUrl })) }; })(), productionGuarantees: { prodRulesStayDraft: true, prodVersionPublished: false } }); return; } const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true; if (!confirmed) { throw confirmationRequired( `Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${prodRules.rules.length} draft rules, and ${prodDocs.length} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`, `seal-use corps sync-test ${prodCorp.id} --yes` ); } // 1. Update style & decision preferences in test enterprise await api.updateApprovalStylePreferences(testClient, updatedTestPref, testCorp.seal.endpoints.approvalStylePreferences); // 2. Synchronize knowledge documents in test enterprise (full coverage, delete redundant test documents) const deletedDocs: Array<{ id: string; title: string }> = []; for (const doc of docsToDelete) { await api.deleteApprovalDocument(testClient, doc.id); deletedDocs.push({ id: doc.id, title: doc.title }); } const updatedDocs: Array<{ id: string; title: string; reasons: string[] }> = []; for (const item of docsToUpdate) { await api.updateApprovalDocument(testClient, item.testId, { title: item.prodDoc.title, purpose: item.prodDoc.purpose, content: item.prodDoc.content, contentType: item.prodDoc.contentType, status: item.prodDoc.status, enabled: item.prodDoc.enabled, scenarios: item.prodDoc.scenarios && item.prodDoc.scenarios.length > 0 ? item.prodDoc.scenarios : ["audit"], tags: item.prodDoc.tags }); updatedDocs.push({ id: item.testId, title: item.prodDoc.title, reasons: item.reasons }); } const createdDocs: Array<{ id: string; title: string }> = []; for (const doc of docsToCreate) { const created = await api.createApprovalDocument(testClient, { title: doc.title, purpose: doc.purpose, content: doc.content, contentType: doc.contentType, status: doc.status, enabled: doc.enabled, scenarios: doc.scenarios && doc.scenarios.length > 0 ? doc.scenarios : ["audit"], tags: doc.tags }); createdDocs.push({ id: created.id, title: created.title }); } // 3. Clear old draft rules in test enterprise for (const rule of testRules.rules) { await api.deleteApprovalRule(testClient, rule.id); } // 4. Create new draft rules in test enterprise const createdRules: any[] = []; for (const rule of prodRules.rules) { const created = await api.createApprovalRule(testClient, { description: rule.description, scope: rule.scope, strictness: rule.strictness }); createdRules.push(created); } // 5. Batch recode rules in test enterprise await api.recodeApprovalRules(testClient).catch(() => undefined); // 6. Publish new version in test enterprise const published = await api.publishApprovalRuleVersion(testClient, versionName); const publishedRules = published.version.rules ?? []; const ruleMapping = prodRules.rules.map((prodRule, idx) => { const testDraft = createdRules[idx]; const publishedRule = publishedRules[idx]; return { index: idx + 1, sourceRuleId: prodRule.id, sourceRuleCode: prodRule.code ?? idx + 1, targetRuleId: testDraft?.id ?? "", targetRuleCode: publishedRule?.code ?? `rule-${idx + 1}`, description: prodRule.description, scope: prodRule.scope, strictness: prodRule.strictness }; }); const versionMapping = { sourceProdVersionNumber: prodVersionNumber ?? null, sourceProdVersionName: latestProd?.versionName ?? null, targetTestVersionNumber: published.version.versionNumber, targetTestVersionName: published.version.versionName ?? null }; let mappingSavedTo: string | undefined; try { mappingSavedTo = saveRuleMappingSnapshot({ syncedAt: new Date().toISOString(), source: { id: prodCorp.id, name: prodCorp.name, latestPublishedVersionNumber: prodVersionNumber ?? null, latestPublishedVersionName: latestProd?.versionName ?? null }, target: { id: testCorp.id, name: testCorp.name, publishedVersionNumber: published.version.versionNumber, publishedVersionName: published.version.versionName, rulesCount: published.rulesCount }, versionMapping, ruleMapping }); } catch {} // 7. Sync hosecloud integrations from prod to test (hose-source corps only) const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient).catch( (err) => ({ skipped: true, reason: `error: ${err?.message ?? String(err)}` } as HosecloudSyncResult) ); printJson({ success: true, syncedAt: new Date().toISOString(), source: { id: prodCorp.id, name: prodCorp.name, environment: prodCorp.environment, latestPublishedVersion: latestProd ? { versionNumber: latestProd.versionNumber, versionName: latestProd.versionName } : null, draftRulesCount: prodRules.rules.length, documentsCount: prodDocs.length }, target: { id: testCorp.id, name: testCorp.name, environment: testCorp.environment, deletedDraftRulesCount: testRules.rules.length, createdDraftRulesCount: createdRules.length, publishedVersion: { id: published.version.id, versionNumber: published.version.versionNumber, versionName: published.version.versionName, rulesCount: published.rulesCount } }, documents: { sourceCount: prodDocs.length, targetExistingCount: testDocs.length, createdCount: createdDocs.length, created: createdDocs, updatedCount: updatedDocs.length, updated: updatedDocs, deletedCount: deletedDocs.length, deleted: deletedDocs }, versionMapping, ruleMapping, ...(mappingSavedTo ? { mappingSavedTo } : {}), hosecloudSync, productionGuarantees: { prodRulesStayDraft: true, prodVersionPublished: false } }); return; } if (action === "replay-test") { const targetCorpId = maybeName ?? stringOption(args.options.corp) ?? stringOption(args.options.prodCorp) ?? stringOption(args.options["prod-corp"]); const prodCorp = selectCorp(targetCorpId); const force = booleanOption(args.options.force) === true; let testCorp: CorpConfig; if (!prodCorp.testCorpId) { if (!force) { throw usageError( `Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` + `Run 'seal-use corps bind-test ${prodCorp.id} --confirm' first to establish a verified 1-to-1 association,\n` + `or add '--force' (or use 'seal-use webhook replay --force') if you explicitly intend to replay directly within production.` ); } testCorp = prodCorp; } else { testCorp = selectCorp(prodCorp.testCorpId); if (testCorp.environment !== "test" && !force) { throw new Error( `Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).` ); } } const recordId = stringOption(args.options.recordId) ?? stringOption(args.options["record-id"]) ?? stringOption(args.options.id); const recordIdsRaw = stringOption(args.options.recordIds) ?? stringOption(args.options["record-ids"]); const recordIds = recordIdsRaw ? recordIdsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined; const sn = stringOption(args.options.sn) ?? stringOption(args.options.documentSn) ?? stringOption(args.options["document-sn"]); const snsRaw = stringOption(args.options.sns) ?? stringOption(args.options["document-sns"]); const sns = snsRaw ? snsRaw.split(",").map((s) => s.trim()).filter(Boolean) : undefined; const limit = numberOption(args.options.limit) ?? (!recordId && !recordIds && !sn && !sns ? 1 : undefined); const status = stringOption(args.options.status); const startDate = stringOption(args.options.startDate) ?? stringOption(args.options["start-date"]); const endDate = stringOption(args.options.endDate) ?? stringOption(args.options["end-date"]); const prodClient = await createSealClient(prodCorp); const testClient = prodCorp.id === testCorp.id ? prodClient : await createSealClient(testCorp); const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector); const snSuffix = stringOption(args.options.snSuffix) ?? stringOption(args.options["sn-suffix"]); const snPrefix = stringOption(args.options.snPrefix) ?? stringOption(args.options["sn-prefix"]); const docIdSuffix = stringOption(args.options.docIdSuffix) ?? stringOption(args.options["doc-id-suffix"]); const docIdPrefix = stringOption(args.options.docIdPrefix) ?? stringOption(args.options["doc-id-prefix"]); const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); const query: ReplayRecordsQuery = { recordId, recordIds, sn, sns, limit, status, startDate, endDate }; console.error( `[corps-replay-test] 正式企业「${prodCorp.name}」(${prodCorp.id}) -> 测试企业「${testCorp.name}」(${testCorp.id})` ); const result = await executeApprovalRunsReplay({ query, sourceClient: prodClient, targetClient: testClient, sourceCorp: prodCorp, targetCorp: testCorp, webhookSelector: selector, snPrefix, snSuffix, docIdPrefix, docIdSuffix, dryRun }); if (dryRun) { console.error( `[corps-replay-test] 预览模式:已成功从 ${prodCorp.name} 提取单据并转换为 Webhook Payload(未实际推送)。` ); console.log(JSON.stringify(result, null, 2)); return; } if (result.success) { if (result.totalCount === 1 && result.replayedDocument) { console.error( `🟢 成功重放单据「${result.replayedDocument.documentSN}」至 ${testCorp.name} (${result.targetWebhook?.name ?? "Webhook 通道"})` ); } else { console.error( `🟢 成功重放 ${result.successCount} 条单据(来自「${prodCorp.name}」)至「${testCorp.name}」(${result.targetWebhook?.name ?? "Webhook 通道"})` ); } } else { console.error( `🔴 单据重放部分或全部失败(成功 ${result.successCount} 条,失败 ${result.failureCount} 条)至「${testCorp.name}」` ); } console.error(`👉 Next action: seal-use approval-runs list --corp ${testCorp.id} --limit ${result.totalCount}`); console.log(JSON.stringify(result, null, 2)); if (!result.success) { process.exitCode = 1; } return; } if (action === "switch") { const corpId = maybeName; if (!corpId) throw new Error("Usage: seal-use corps switch "); const globalConfig = loadGlobalConfig(); if (!globalConfig.stateful) { throw new Error( "Cannot switch the default enterprise while stateless mode is enabled. " + "Use `seal-use 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 === "probe-hose") { await probeHoseCorp(jsonObject(args.json)); return; } if (action === "hose-staffs") { await queryHoseStaffs(jsonObject(args.json)); return; } if (action === "add-hose") { await addHoseCorp(jsonObject(args.json)); return; } if (action === "add-seal") { await addSealCorp(jsonObject(args.json)); return; } if (action === "add-link") { const link = maybeName ?? stringOption(args.options.link) ?? stringOption(args.options.url); if (!link) { throw new Error( "Usage: seal-use corps add-link [--name ] [--overwrite]" ); } await addLinkCorp(link, stringOption(args.options.name), booleanOption(args.options.overwrite) === true); return; } throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`); } // --------------------------------------------------------------------------- // Hosecloud integration sync helpers // --------------------------------------------------------------------------- /** * Build the outboundName for a test-env hosecloud integration. * Format: {企业名前7字}(Seal测) — capped at 13 chars total. */ export function buildTestHosecloudOutboundName(corpName: string): string { // "(Seal测)" is 7 chars; leave 6 chars for the corp name prefix. const suffix = "(Seal测)" const maxPrefix = 13 - suffix.length // 6 const prefix = [...corpName].slice(0, maxPrefix).join("") return prefix + suffix } interface HosecloudSyncResult { skipped: boolean reason?: string synced?: Array<{ signKey: string; outboundName: string; corporationId: string; action: "created" | "updated" }> } /** * Sync hosecloud integrations from the production Seal enterprise into the * test Seal enterprise. Rules: * - Only runs when prodCorp.source.type === "hose" (credentials available locally) * - outboundName: buildTestHosecloudOutboundName(prodCorp.name) * - mode: always "assisted" * - apiKey/apiSecret: from prodCorp.source.appKey / appSecurity * - apiOrigin/customApiUrl: copied verbatim from the production integration config * - signKey: existing test integration keeps its key; new ones get a fresh random key * - Does NOT call syncHosecloudOutbound (no sync to 合思) */ async function syncHosecloudIntegrationsToTest( prodCorp: import("../../core/config/types.js").CorpConfig, testCorp: import("../../core/config/types.js").CorpConfig, prodClient: import("ky").KyInstance, testClient: import("ky").KyInstance ): Promise { if (prodCorp.source.type !== "hose") { return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" } } const appKey = (((prodCorp.source as any).appKey ?? (prodCorp.source as any).key) as string | undefined)?.trim() const appSecurity = (((prodCorp.source as any).appSecurity ?? (prodCorp.source as any).password) as string | undefined)?.trim() if (!appKey || !appSecurity) { return { skipped: true, reason: "prod hose source missing appKey/appSecurity (or key/password)" } } const [prodPref, testPref] = await Promise.all([ api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)), api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)) ]) const prodIntegrations: any[] = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud") if (prodIntegrations.length === 0) { return { skipped: true, reason: "prod Seal enterprise has no hosecloud integrations configured" } } // Deduplicate prod integrations by corporationId: // Production enterprises may have multiple integrations (e.g. "assisted" + "fully_automatic") // with the same corporationId. For the test environment, exactly one assisted integration per // corporationId is needed. const seenCorpIds = new Set() const distinctProdIntegrations: any[] = [] for (const item of prodIntegrations) { const cid = item.corporationId ?? prodCorp.id if (!seenCorpIds.has(cid)) { seenCorpIds.add(cid) distinctProdIntegrations.push(item) } } const testIntegrations: any[] = (testPref.integrations ?? []) const testByCorpId = new Map( testIntegrations.filter((i: any) => i.type === "hosecloud").map((i: any) => [i.corporationId, i]) ) const outboundName = buildTestHosecloudOutboundName(prodCorp.name) const synced: HosecloudSyncResult["synced"] = [] const nextHosecloudIntegrations: any[] = distinctProdIntegrations.map((prodInt: any) => { const existing = testByCorpId.get(prodInt.corporationId) const signKey = existing?.signKey ?? randomBytes(6).toString("hex") synced!.push({ signKey, outboundName, corporationId: prodInt.corporationId, action: existing ? "updated" : "created" }) return { type: "hosecloud", signKey, outboundName, mode: "assisted", apiKey: appKey, apiSecret: appSecurity, apiOrigin: prodInt.apiOrigin, ...(prodInt.customApiUrl ? { customApiUrl: prodInt.customApiUrl } : {}), corporationId: prodInt.corporationId } }) // Merge: keep non-hosecloud entries + newly built hosecloud entries const otherIntegrations = testIntegrations.filter((i: any) => i.type !== "hosecloud") const nextConfig = { ...testPref, integrations: [...otherIntegrations, ...nextHosecloudIntegrations] } await api.updateApprovalStylePreferences(testClient, nextConfig, testCorp.seal.endpoints.approvalStylePreferences) return { skipped: false, synced } } async function probeHoseCorp(input: Record) { const appKey = requiredString(input, "appKey"); const appSecurity = requiredString(input, "appSecurity"); const explicitDomain = optionalString(input, "domain"); const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []); const totalRoles = roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0); printJson({ domain: probe.domain, corpId: probe.corpId, name: probe.corpName ?? probe.corpId, roleCount: totalRoles, roleGroups: roleGroups.map((g) => ({ id: g.id, name: g.name, roleDefs: g.roleDefs.map((r) => ({ id: r.id, name: r.name, sourceType: r.sourceType })) })) }); } async function queryHoseStaffs(input: Record) { const appKey = requiredString(input, "appKey"); const appSecurity = requiredString(input, "appSecurity"); const explicitDomain = optionalString(input, "domain"); const roleQuery = optionalString(input, "role") ?? optionalString(input, "roleDefId") ?? "admin"; const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken); let targetRoleDefId: string | undefined; let targetRoleName: string | undefined; // 1. Direct match by id for (const g of roleGroups) { for (const r of g.roleDefs) { if (r.id === roleQuery || r.id === `${probe.corpId}:${roleQuery}`) { targetRoleDefId = r.id; targetRoleName = r.name; break; } } if (targetRoleDefId) break; } // 2. Admin match default if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) { for (const g of roleGroups) { for (const r of g.roleDefs) { if (r.id.endsWith(":admin") || r.name === "主管理员") { targetRoleDefId = r.id; targetRoleName = r.name; break; } } if (targetRoleDefId) break; } } // 3. Match by role name substring if (!targetRoleDefId) { for (const g of roleGroups) { for (const r of g.roleDefs) { if (r.name.toLowerCase().includes(roleQuery.toLowerCase())) { targetRoleDefId = r.id; targetRoleName = r.name; break; } } if (targetRoleDefId) break; } } if (!targetRoleDefId) { throw new Error( `Role not found matching query: '${roleQuery}'. Run 'seal-use corps probe-hose' to view all available roles.` ); } const roleStaffs = await fetchHoseRoleStaffs(probe.domain, probe.openapiToken, targetRoleDefId); const staffDetails = await fetchHoseStaffDetails(probe.domain, probe.openapiToken, roleStaffs.staffs); printJson({ domain: probe.domain, corpId: probe.corpId, corpName: probe.corpName ?? probe.corpId, roleId: targetRoleDefId, roleName: targetRoleName, count: staffDetails.length, staffs: staffDetails.map((s) => ({ id: s.id, name: s.name, cellphone: s.cellphone, active: s.active, authState: s.authState, userId: s.userId, email: s.email })) }); } async function addHoseCorp(input: Record) { const nameInput = optionalString(input, "name"); const appKey = requiredString(input, "appKey"); const appSecurity = requiredString(input, "appSecurity"); const explicitDomain = optionalString(input, "domain"); const explicitStaffId = optionalString(input, "staffId") ?? optionalString(input, "proxyStaffBizId"); const staffName = optionalString(input, "staffName"); const staffPhone = optionalString(input, "staffPhone"); const roleQuery = optionalString(input, "role") ?? "admin"; const force = input.force === true; const verify = force || input.verify === false ? false : true; let domain = explicitDomain; let corpId = optionalString(input, "corpId") ?? optionalString(input, "corporationId"); let corpName = nameInput; let openapiToken: string | undefined; if (!domain || !corpId || !explicitStaffId) { const probe = await probeHoseDomain(appKey, appSecurity, explicitDomain); domain = probe.domain; corpId = corpId ?? probe.corpId; corpName = corpName ?? probe.corpName; openapiToken = probe.openapiToken; } let finalStaffId = explicitStaffId; if (!finalStaffId && openapiToken && domain) { const roleGroups = await fetchHoseRoleDefGroups(domain, openapiToken).catch(() => []); let targetRoleId: string | undefined; for (const g of roleGroups) { for (const r of g.roleDefs) { if (r.id.endsWith(`:${roleQuery}`) || r.name === roleQuery || r.id === roleQuery) { targetRoleId = r.id; break; } } if (targetRoleId) break; } if (!targetRoleId) { targetRoleId = roleGroups .find((g) => g.roleDefs.some((r) => r.id.endsWith(":admin"))) ?.roleDefs.find((r) => r.id.endsWith(":admin"))?.id; } if (targetRoleId) { const roleStaffs = await fetchHoseRoleStaffs(domain, openapiToken, targetRoleId).catch(() => ({ staffs: [] })); const staffDetails = await fetchHoseStaffDetails(domain, openapiToken, roleStaffs.staffs).catch(() => []); if (staffName || staffPhone) { const matches = staffDetails.filter((s) => { if (staffName && s.name !== staffName && !s.name.includes(staffName)) return false; if (staffPhone && (!s.cellphone || !s.cellphone.includes(staffPhone))) return false; return true; }); if (matches.length === 1 && matches[0]) { finalStaffId = matches[0].id; } else if (matches.length > 1) { throw new Error( `Multiple staff members matched '${staffName ?? staffPhone}': ${matches.map((m) => `${m.name}(${m.id})`).join(", ")}. Please specify exact staffId.` ); } else { throw new Error( `No staff member found matching '${staffName ?? staffPhone}' under role ${targetRoleId}. Run 'seal-use corps hose-staffs' to view candidates.` ); } } else if (!force) { const candidates = staffDetails .map((s) => `${s.name} (${s.cellphone || "no-phone"}, id: ${s.id}, active: ${s.active})`) .join("\n - "); throw new Error( `Missing required parameter: staffId. Found ${staffDetails.length} candidate administrators:\n - ${candidates}\n` + `Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).` ); } } } if (!finalStaffId) { if (!verify && explicitStaffId) { finalStaffId = explicitStaffId; } else { throw new Error( "Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators." ); } } const id = optionalString(input, "id") ?? corpId; const name = corpName ?? corpId; const sealUrl = optionalString(input, "sealUrl") ?? `https://${corpId.toLowerCase()}.sealai.cc`; const config: CorpConfig = { id, name, environment: "production", seal: { url: sealUrl, endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } }, source: { type: "hose", domain: domain!, appKey, appSecurity, corpId: corpId!, staffId: finalStaffId }, 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, domain, staffId: finalStaffId, 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 custom = sealCustomHeadersFromInput(input); const remote = verify ? await resolveSealWhoami(sealUrl, token, resolveSealCustomHeaders(custom)) : undefined; writeSealCorpConfig(input, { token, sealUrl, expiresIn, verify, remote, custom }); } // Validates extra headers/cookies up front so a malformed name fails here // rather than on the next config load. function sealCustomHeadersFromInput(input: Record) { return { headers: SealHeaderMapSchema.parse(input.headers), cookies: SealCookieMapSchema.parse(input.cookies) }; } async function addLinkCorp(link: string, name: string | undefined, overwrite: boolean) { const session = await exchangeHoseAssistLink(link); const client = createSealClientForUrl(session.sealUrl, session.token); const me = await getMe(client); const identity = { user: me.user as unknown as Record, tenant: me.tenant as unknown as Record }; assertHoseAssistTenantMatches(session.corpId, identity.tenant); writeSealCorpConfig( { id: session.corpId, corpId: session.corpId, name, provider: "hosecloud", overwrite }, { token: session.token, sealUrl: session.sealUrl, expiresIn: session.expiresIn, verify: true, remote: identity } ); } type RemoteSealIdentity = { user: Record; tenant: Record; }; function writeSealCorpConfig( input: Record, auth: { token: string; sealUrl: string; expiresIn: number; verify: boolean; remote?: RemoteSealIdentity; custom?: { headers?: Record; cookies?: Record }; } ) { const { token, sealUrl, expiresIn, verify, remote } = auth; const custom = auth.custom ?? sealCustomHeadersFromInput(input); 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") ?? 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 corpId = optionalString(input, "corpId") ?? tenantSlug ?? tenantId ?? id; const config: CorpConfig = { id, name: optionalString(input, "name") ?? tenantName ?? id, environment: "production", seal: { url: sealUrl, tenantSlug, headers: custom.headers, cookies: custom.cookies, endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } }, source: { type: "seal", token, sealUrl, expiresIn, staffId, corpId, 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, customHeaders: Record = {}) { const client = createSealClientForUrl(sealUrl, token, customHeaders); const me = await getMe(client); return { user: (me.user ?? {}) as Record, tenant: (me.tenant ?? {}) as Record }; } 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; }