diff --git a/dist/mcp/server.js b/dist/mcp/server.js index 6cbf54a..855a346 100644 --- a/dist/mcp/server.js +++ b/dist/mcp/server.js @@ -315,7 +315,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs. `)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${G.document.documentId} `);let z=ph(G.document,H,W),Z=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/document`,{method:"POST",headers:{"Content-Type":"application/json",...ry({webhookId:Q,...z},U.secret)},body:JSON.stringify(z)});if(!Z.ok)throw Error(`Webhook 单据推送失败 ${Z.status}: ${await Z.text()}`);K.push({documentId:z.documentId,document:z,pushResult:await Z.json()}),process.stderr.write(`✓ 单据推送成功: ${z.documentId} `)}return{warnings:[],results:K}}function UI($){return{fileBuffer:qq1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}import{existsSync as Vq1}from"node:fs";async function aL($,I,U={}){let J=L4().stateful?"stateful":"stateless",Q="ok",K,q,G;try{let A=await N$($);G={id:A.user.id,name:A.user.name,isAdmin:A.user.isAdmin},q={id:A.tenant.id,name:A.tenant.name,tenantSlug:A.tenant.tenantSlug,corporationName:A.tenant.hoseCorpConfig?.corporationName}}catch(A){Q="error",K=A instanceof Error?A.message:String(A)}let H=[];if(Q==="ok")try{H=await Z9($,I.seal.endpoints.approvalStylePreferences)}catch(A){Q="error",K=`读取 Webhook 配置失败: ${A instanceof Error?A.message:String(A)}`}let W=H.length===1,V=H.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...W?{isDefault:!0}:{}})),z=W?{id:H[0].id,name:H[0].name,mode:H[0].mode}:null,Z=U.webhook?z9(H,U.webhook):W?H[0]:void 0,w;if(U.filePath)if(!Vq1(U.filePath))w={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在: ${U.filePath}`]};else try{let A=UI(U.filePath),v=await II(A.fileBuffer,A.fileName,Z?.materialPackFilePolicy);w={valid:!0,filePath:U.filePath,fileName:A.fileName,documentCount:v.documents.length,warnings:v.warnings}}catch(A){w={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let L=w?w.valid:!0,D=Q==="ok"&&V.length>0&&L,N=J==="stateful"?"":` --corp ${I.id}`,E="",T="";if(Q!=="ok")T=`凭证鉴权异常: ${K}`,E=`seal-use auth diagnose${N}`;else if(V.length===0)T="当前企业尚未配置任何 Webhook 集成通道",E=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${N}`;else if(w&&!w.valid)T=`材料包预检失败: ${w.errors?.join("; ")}`,E=`seal-use webhook material-pack preview ${w.filePath}${N}`;else{T=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${V.length} 个 Webhook 通道,等待载入`;let A=w?.filePath??"<材料包.zip>",v=W?"":` --webhook ${z?z.id:""}`;E=`seal-use webhook material-pack push ${A}${v}${N}`}return{ready:D,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:q,user:G},stateMode:J,authStatus:Q,authError:K,activeWebhooks:V,defaultWebhook:z,materialPack:w,statusMessage:T,nextAction:E}}var JG=[{name:"seal_whoami",description:"查询当前 Seal 用户身份及租户信息",parameters:X.object({}),handler:async($)=>N$($)},{name:"seal_session_get",description:"查询当前 Seal Bearer session、用户和过期时间",parameters:X.object({}),handler:async($)=>ud($)},{name:"seal_delegation_list",description:"查询当前 Seal 租户下的授权链接 (Delegation) 列表",parameters:X.object({}),handler:async($)=>Gm($)},{name:"seal_delegation_create",description:"创建新的 Seal 授权链接 (Delegation)",parameters:X.object({note:X.string().optional().describe("授权链接的备注或说明信息")}),handler:async($,I)=>wU($,I)},{name:"seal_delegation_revoke",description:"撤销/废除指定的 Seal 授权链接 (Delegation)",parameters:X.object({tokenId:X.string().describe("授权链接 ID (delegation record ID)")}),handler:async($,I)=>Hm($,I.tokenId)},{name:"seal_user_create",description:"创建本地 Seal 用户,生成并返回初始随机密码",parameters:X.object({name:X.string().describe("用户姓名"),phone:X.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),permissions:X.array(X.string()).optional().describe("权限列表,默认为 []"),departmentIds:X.array(X.string()).optional().describe("关联部门 ID 数组")}),handler:async($,I)=>Wm($,I)},{name:"seal_user_reset_password",description:"重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>EE($,I.userId)},{name:"seal_user_get",description:"获取指定 Seal 用户的详细信息",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>CV($,I.userId)},{name:"seal_user_search",description:"按姓名、手机号或邮箱搜索 Seal 成员用户列表",parameters:X.object({keyword:X.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")}),handler:async($,I)=>jV($,I.keyword??"")},{name:"seal_user_delete",description:"删除指定 Seal 本地用户",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>Vm($,I.userId)},{name:"seal_user_activate",description:"启用/激活已离职的 Seal 用户账号",parameters:X.object({userId:X.string().describe("用户 ID (_id)")}),handler:async($,I)=>BE($,I.userId)},{name:"seal_user_delegation_create",description:"为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",parameters:X.object({userIdOrPhone:X.string().describe("目标用户 ID、手机号或姓名"),note:X.string().optional().describe("授权链接备注信息")}),handler:async($,I,U)=>Zm($,I,(Y)=>Gd(U.corp,Y),U.corp)},{name:"seal_llm_config_get",description:"查询当前 Seal 租户的大模型 (LLM) 配置",parameters:X.object({}),handler:async($)=>zm($)},{name:"seal_llm_providers_list",description:"查询支持的大模型 (LLM) 供应商与配置属性字段",parameters:X.object({}),handler:async($)=>Xm($)},{name:"seal_permissions_available_list",description:"查询系统可选权限清单(如超级管理员、智能审核管理、数据管理等)",parameters:X.object({}),handler:async($)=>wm($)},{name:"seal_permissions_configs_list",description:"查询当前租户已绑定的权限配置",parameters:X.object({}),handler:async($)=>Lm($)},{name:"seal_billing_status_get",description:"查询当前 Seal 租户的订阅状态与各功能额度(AI审批、审核规则、知识文档等)",parameters:X.object({}),handler:async($)=>Dm($)},{name:"seal_billing_plans_list",description:"查询系统支持的订阅套餐列表",parameters:X.object({}),handler:async($)=>Om($)},{name:"seal_billing_features_list",description:"查询系统支持的功能特性定义列表",parameters:X.object({}),handler:async($)=>Nm($)},{name:"seal_approval_rules_list",description:"列出 Seal 当前草稿审批规则;支持 countOnly、fields、limit 以避免返回规则正文",parameters:X.object({countOnly:X.boolean().optional().describe("只返回规则数量,不返回规则列表"),fields:X.array(X.enum(["id","code","tenantId","status","strictness","scope","createdAt","updatedAt","description"])).optional().describe("只返回指定字段;不传则返回完整规则"),limit:X.number().int().nonnegative().optional().describe("最多返回多少条规则;0 可配合 fields 或 countOnly 只取数量"),offset:X.number().int().nonnegative().optional().describe("跳过前多少条规则")}),handler:async($,I)=>{let U=await F$($);return Lq1(U,I)}},{name:"seal_approval_rules_clear",description:"清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",parameters:X.object({dryRun:X.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),recode:X.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")}),handler:async($,I,U)=>{let Y=await F$($);if(I.dryRun)return{corpId:U.corp.id,corpName:U.corp.name,dryRun:!0,beforeCount:Y.rules.length,deleted:0,afterCount:Y.rules.length,hasPendingDeletes:Y.hasPendingDeletes};let J=[],Q=0;for(let H of Y.rules)try{await SV($,H.id),Q+=1}catch(W){J.push({ruleId:H.id,error:W instanceof Error?W.message:String(W)})}let K=[],q;if(Q>0&&I.recode!==!1){if(q=await OE($),q&&typeof q==="object"&&"ok"in q&&q.ok!==!0)K.push("batch-recode did not complete; current rules were still deleted")}let G=await F$($);return{corpId:U.corp.id,corpName:U.corp.name,dryRun:!1,beforeCount:Y.rules.length,deleted:Q,failed:J,afterCount:G.rules.length,hasPendingDeletes:G.hasPendingDeletes,warnings:K,recode:q}}},{name:"seal_approval_rule_create",description:"新建 Seal 草稿审批规则",parameters:X.object({description:X.string().describe("规则描述"),scope:X.string().describe("适用场景"),strictness:X.enum(["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]).describe("严格程度")}),handler:async($,I)=>DE($,I)},{name:"seal_approval_rule_update",description:"更新 Seal 草稿审批规则",parameters:X.object({ruleId:X.string().describe("规则 ID"),description:X.string().optional(),scope:X.string().optional(),strictness:X.enum(["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]).optional()}),handler:async($,I)=>{let{ruleId:U,...Y}=I,J=await fd($,U,Y);if(I.description)try{let Q=L4();if(Q.lint?.enabled){let K=await my(Q.lint.activeLinter),q=await ly({id:U,description:I.description},K);if(q.issues.length>0){console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${q.score}/100 (发现 ${q.issues.length} 处潜在风险):`);for(let G of q.issues)if(console.error(` • [${G.level.toUpperCase()}] ${G.message}${G.snippet?` ("${G.snippet}")`:""}`),G.suggestion)console.error(` \uD83D\uDC49 建议: ${G.suggestion}`)}}}catch{}return J}},{name:"seal_approval_rule_delete",description:"删除 Seal 草稿审批规则",parameters:X.object({ruleId:X.string().describe("规则 ID")}),handler:async($,I)=>{return await SV($,I.ruleId),{success:!0}}},{name:"seal_approval_rule_versions_list",description:"列出 Seal 已发布审批规则版本摘要,不展开每个版本的规则快照",parameters:X.object({}),handler:async($)=>{let I=await Y5($);return{count:I.length,latest:I[0]?ch(I[0]):void 0,versions:I.map(ch)}}},{name:"seal_approval_rule_version_get",description:"获取指定 Seal 已发布审批规则版本详情,包含该版本的规则快照",parameters:X.object({versionId:X.string().optional().describe("规则版本 ID"),versionNumber:X.number().int().positive().optional().describe("规则版本号"),latest:X.boolean().optional().describe("为 true 时获取最新版本")}),handler:async($,I)=>{if(I.versionId)return W2($,I.versionId);let U=await Y5($),Y=I.versionNumber?U.find((J)=>J.versionNumber===I.versionNumber):U[0];if(!Y)throw Error(I.versionNumber?`Rule version not found: ${I.versionNumber}`:"No rule versions found");return Y}},{name:"seal_approval_rule_version_publish",description:"发布 Seal 草稿审批规则为新版本",parameters:X.object({versionName:X.string().describe("版本名称")}),handler:async($,I)=>NE($,I.versionName)},{name:"seal_approval_rule_get",description:"按版本号/code/runtime-id/record-id 定位单条规则,避免拉取整版规则快照",parameters:X.object({versionId:X.string().optional().describe("规则版本 ID"),versionNumber:X.number().int().positive().optional().describe("规则版本号"),latest:X.boolean().optional().describe("为 true 时取最新版本"),code:X.string().optional().describe("规则展示编号,如 #0038;没有后端 code 时按版本内序号匹配"),runtimeId:X.string().optional().describe("运行时规则 ID,如 rule-205;按版本内序号匹配"),recordId:X.string().optional().describe("从运行记录推断 ruleSetVersionNumber")}),handler:async($,I)=>{let U=await Rq1($,I),Y=vq1(U,{code:I.code,runtimeId:I.runtimeId});if(!Y)throw Error(`Rule not found in version ${U.versionNumber}`);return Y}},{name:"seal_approval_rules_lint",description:"对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",parameters:X.object({file:X.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),linter:X.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),version:X.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),code:X.string().optional().describe("按规则展示编号过滤(如 #0038)"),ruleId:X.string().optional().describe("按规则 ID 过滤"),minScore:X.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),level:X.enum(["all","error","warning"]).default("all").describe("问题报告等级过滤"),summary:X.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")}),handler:async($,I,U)=>{let Y=[],J;if(I.file){let H=oy(I.file);Y=zV0(H.rules),J=H.meta.versionNumber}else if(I.version){let H=await Y5($),W=Number(I.version),V=isNaN(W)?I.version==="latest"?H[0]:H.find((z)=>z.id===I.version):H.find((z)=>z.versionNumber===W);if(!V)throw Error(`未找到指定的规则版本: ${I.version}`);J=V.versionNumber,Y=(V.rules??[]).map((z,Z)=>({id:z.id??z.runtimeId,code:z.code??`#${String(Z+1).padStart(4,"0")}`,name:z.name??z.title,description:z.description??"",scope:z.scope,strictness:z.strictness}))}else Y=((await F$($)).rules??[]).map((W,V)=>({id:W.id,code:W.code??`#${String(V+1).padStart(4,"0")}`,name:W.name??W.title,description:W.description??"",scope:W.scope,strictness:W.strictness}));if(I.code)Y=Y.filter((H)=>H.code===I.code||H.code?.replace(/[#\s]/g,"")===I.code?.replace(/[#\s]/g,""));if(I.ruleId)Y=Y.filter((H)=>H.id===I.ruleId||H.code===I.ruleId);let Q=L4(),K=I.linter??Q.lint?.activeLinter??"builtin",q=await my(K),G=await HV0(Y,q,{corpId:U?.corp?.id,versionNumber:J,allRules:Y},{minScore:I.minScore,level:I.level,summary:I.summary});if(I.minScore&&G.overallScore{let Y=I.out??"./rules.local.json",J=[],Q="draft",K;if(I.version){let G=await Y5($),H=Number(I.version),W=isNaN(H)?I.version==="latest"?G[0]:G.find((V)=>V.id===I.version):G.find((V)=>V.versionNumber===H);if(!W)throw Error(`未找到指定的规则版本: ${I.version}`);K=W.versionNumber,Q=`version:${K}`,J=(W.rules??[]).map((V,z)=>({code:V.code?Number(String(V.code).replace(/^#/,""))||z+1:z+1,name:V.name??V.title,description:V.description??"",scope:V.scope??"ALL",strictness:V.strictness??"MUST_FOLLOW"}))}else J=((await F$($)).rules??[]).map((H,W)=>({id:H.id,code:H.code??W+1,name:H.name??H.title,description:H.description??"",scope:H.scope??"ALL",strictness:H.strictness??"MUST_FOLLOW",status:H.status}));return{saved:!0,path:ZV0(Y,{corpId:U.corp.id,source:Q,versionNumber:K,exportedAt:new Date().toISOString(),rulesCount:J.length,rules:J}),rulesCount:J.length,corpId:U.corp.id,source:Q,versionNumber:K}}},{name:"seal_approval_rules_push",description:"将本地规则文件推送到远端草稿(本地调优通过后一键应用,支持直接发布为正式版本)",parameters:X.object({file:X.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),dryRun:X.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),confirm:X.boolean().optional().describe("确认覆盖写入远端草稿"),publish:X.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),versionName:X.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")}),handler:async($,I,U)=>{let Y=I.file??"./rules.local.json",J=oy(Y),Q=I.confirm===!0,K=I.dryRun??!Q,q=await F$($);if(K)return{corpId:U.corp.id,dryRun:!0,localFile:J.resolvedPath,localRulesCount:J.rules.length,remoteDraftCount:q.rules.length,willPublish:Boolean(I.publish),message:"Preview mode. Use --yes or confirm=true to apply local rules to remote draft."};let G=0;for(let V of q.rules)await SV($,V.id),G+=1;let H=[];for(let V of J.rules){let z=V.strictness?.toUpperCase()?.includes("SHOULD")?"SHOULD_FOLLOW":V.strictness?.toUpperCase()?.includes("SUGGEST")?"SUGGESTION":"MUST_FOLLOW",Z=await DE($,{description:V.description,scope:V.scope??"ALL",strictness:z});H.push({id:Z.id,description:Z.description,code:Z.code})}await OE($);let W=void 0;if(I.publish){let V=new Date().toISOString().slice(0,10).replace(/-/g,""),z=I.versionName||`v-local-${V}-${Date.now().toString().slice(-4)}`;W=await NE($,z)}return{corpId:U.corp.id,dryRun:!1,localFile:J.resolvedPath,clearedDraftRules:G,createdRules:H.length,published:W??!1}}},{name:"seal_approval_documents_list",description:"列出 Seal 审批知识文档",parameters:X.object({scenarios:X.array(X.string()).optional().describe("场景过滤"),offset:X.number().int().nonnegative().optional(),limit:X.number().int().positive().optional()}),handler:async($,I)=>V2($,I)},{name:"seal_approval_document_get",description:"获取 Seal 审批知识文档详情",parameters:X.object({documentId:X.string().describe("文档 ID")}),handler:async($,I)=>bd($,I.documentId)},{name:"seal_approval_document_create",description:"新建 Seal 审批知识文档",parameters:X.object({title:X.string(),purpose:X.string(),content:X.string().describe("正文,通常为 Markdown"),contentType:X.string().optional(),status:X.string().optional(),scenarios:X.array(X.string()).optional(),tags:X.array(X.string()).optional()}),handler:async($,I)=>id($,I)},{name:"seal_approval_document_update",description:"更新 Seal 审批知识文档",parameters:X.object({documentId:X.string(),title:X.string().optional(),purpose:X.string().optional(),content:X.string().optional(),contentType:X.string().optional(),status:X.string().optional(),enabled:X.boolean().optional(),scenarios:X.array(X.string()).optional(),tags:X.array(X.string()).optional()}),handler:async($,I)=>{let{documentId:U,...Y}=I;return nd($,U,Y)}},{name:"seal_approval_search",description:"按关键词组检索 Seal 审批规则、审批文档和审批偏好配置,返回命中位置、字段、行号和前后三行上下文",parameters:X.object({keywords:X.array(X.string()).min(1).describe("关键词组"),matchMode:X.enum(["any","all"]).optional().describe("any 命中任一关键词,all 要求同一行命中全部关键词"),areas:X.array(X.enum(["rules","documents","preferences"])).optional().describe("检索范围"),caseSensitive:X.boolean().optional().describe("是否大小写敏感"),contextLines:X.number().int().nonnegative().optional().describe("返回命中行前后几行,默认 3"),documentLimit:X.number().int().positive().optional().describe("缓存刷新时最多拉取文档数,默认 100"),maxResults:X.number().int().positive().optional().describe("最多返回命中数,默认 50"),refresh:X.boolean().optional().describe("是否跳过 5 分钟内存缓存并强制刷新"),ruleVersionScope:X.enum(["current","all","version"]).optional().describe("规则检索范围,默认 current;all 会检索所有已发布历史版本"),ruleVersionId:X.string().optional().describe("ruleVersionScope=version 时指定版本 ID"),ruleVersionNumber:X.number().int().positive().optional().describe("ruleVersionScope=version 时指定版本号"),latestRuleVersion:X.boolean().optional().describe("ruleVersionScope=version 时取最新已发布版本"),snippetOnly:X.boolean().optional().describe("只返回命中行,不返回前后文"),maxChars:X.number().int().positive().optional().describe("每个文本片段最多返回字符数"),fields:X.array(X.string()).optional().describe("只搜索指定字段,如 history.description、description、scope")}),handler:async($,I,U)=>qV0($,U.corp,I)},{name:"seal_approval_context_get",description:"聚合获取 Seal 现有审批规则、审批文档和审批风格偏好",parameters:X.object({documentLimit:X.number().int().positive().optional().describe("最多返回的审批文档数量"),ruleVersionId:X.string().optional().describe("指定已发布规则版本 ID;指定后 rules 返回该版本快照"),ruleVersionNumber:X.number().int().positive().optional().describe("指定已发布规则版本号;指定后 rules 返回该版本快照"),latestRuleVersion:X.boolean().optional().describe("为 true 时 rules 返回最新已发布版本快照")}),handler:async($,I,U)=>{let Y=await gV($,{documentLimit:I.documentLimit,stylePreferencesEndpoint:U.corp.seal.endpoints.approvalStylePreferences});if(!I.ruleVersionId&&!I.ruleVersionNumber&&!I.latestRuleVersion)return Y;let J=await lh($,I);return{...Y,rules:{version:ch(J),rules:J.rules}}}},{name:"seal_approval_style_preferences_get",description:"获取 Seal 审批风格偏好配置",parameters:X.object({}),handler:async($,I,U)=>q4($,U.corp.seal.endpoints.approvalStylePreferences)},{name:"seal_approval_style_preferences_update",description:"更新 Seal 审批风格偏好配置",parameters:X.object({tone:X.string().optional(),language:X.string().optional(),detailLevel:X.string().optional(),outputFormat:X.string().optional(),examples:X.array(X.string()).optional(),prohibitedPhrases:X.array(X.string()).optional(),customInstructions:X.string().optional()}),handler:async($,I,U)=>y7($,I,U.corp.seal.endpoints.approvalStylePreferences)},{name:"seal_webhook_list",description:"列出当前 Seal 租户的 Webhook 集成,可按 ID、名称或 URL 查找",parameters:X.object({query:X.string().optional().describe("按集成 ID、名称或 URL 做本地包含匹配"),includeSecret:X.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")}),handler:async($,I,U)=>{let Y=md(await Z9($,U.corp.seal.endpoints.approvalStylePreferences),I.query);return{count:Y.length,integrations:Y.map((J)=>YG(J,I.includeSecret===!0))}}},{name:"seal_webhook_get",description:"按 Webhook 集成 ID 或名称精确查找一条集成",parameters:X.object({selector:X.string().min(1).describe("Webhook 集成 ID 或名称"),includeSecret:X.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")}),handler:async($,I,U)=>{let Y=z9(await Z9($,U.corp.seal.endpoints.approvalStylePreferences),I.selector);return YG(Y,I.includeSecret===!0)}},{name:"seal_webhook_add",description:"新增 Webhook 集成并通过 AI 审批配置保存接口持久化",parameters:X.object({name:X.string().min(1).describe("集成名称"),mode:X.enum(["assisted","semi_automatic","fully_automatic"]).optional(),outgoingResultWebhook:X.string().url().describe("Seal 完成 AI 审核后回调的外部地址"),autoApprovalRate:X.number().int().min(0).max(100).optional(),secret:X.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret"),materialPackFilePolicy:WE.describe("材料包附件文件策略:大小和后缀白名单")}),handler:async($,I,U)=>{let Y=wq1(U.corp),J=await pd($,Y,I,U.corp.seal.endpoints.approvalStylePreferences);return{saved:!0,integration:YG(J,!0)}}},{name:"seal_webhook_update",description:"更新现有 Webhook 集成并通过 AI 审批配置保存接口持久化",parameters:X.object({selector:X.string().min(1).describe("Webhook 集成 ID 或名称"),name:X.string().min(1).optional(),mode:X.enum(["assisted","semi_automatic","fully_automatic"]).optional(),outgoingResultWebhook:X.string().url().optional(),autoApprovalRate:X.number().int().min(0).max(100).optional(),secret:X.string().min(1).optional(),rotateSecret:X.boolean().optional().describe("生成新 secret;与 secret 二选一"),materialPackFilePolicy:WE.describe("材料包附件文件策略:大小和后缀白名单")}),handler:async($,I,U)=>{if(I.secret!==void 0&&I.rotateSecret)throw Error("Webhook secret and rotateSecret cannot be used together");let Y=await cd($,I.selector,I,U.corp.seal.endpoints.approvalStylePreferences);return{saved:!0,integration:YG(Y,I.secret!==void 0||I.rotateSecret===!0)}}},{name:"seal_webhook_delete",description:"删除指定 Webhook 集成并通过 AI 审批配置保存接口持久化",parameters:X.object({selector:X.string().min(1).describe("Webhook 集成 ID 或名称"),confirm:X.boolean().describe("必须明确传 true 才执行删除")}),handler:async($,I,U)=>{if(!I.confirm)throw Error("Refusing to delete Webhook integration without confirm=true");let Y=await dd($,I.selector,U.corp.seal.endpoints.approvalStylePreferences);return{deleted:!0,integration:YG(Y,!1)}}},{name:"seal_approval_runs_search",description:"查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段",parameters:X.object({offset:X.number().int().nonnegative().optional(),limit:X.number().int().positive().max(100).optional(),fromTimestamp:X.string().optional(),toTimestamp:X.string().optional(),startDate:X.string().optional().describe("运行记录创建开始时间戳(毫秒),对应前端 startDate"),endDate:X.string().optional().describe("运行记录创建结束时间戳(毫秒),对应前端 endDate"),status:X.string().optional(),taskMode:X.string().optional(),manualApprovalStatus:X.union([X.string(),X.array(X.string())]).optional().describe("人工审核状态,如 TERMINATED 对应已驳回"),sourceDocumentSN:X.string().optional(),sourceDocumentId:X.string().optional(),humanResult:X.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),query:X.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配"),includeBridge:X.boolean().optional().describe("是否返回完整 bridge 数组;默认 false,避免长输出")}),handler:async($,I)=>{let U=I.query?.trim(),Y=await X8($,hq1({...I,search:U})),J=await bZ0($,Y.records,{humanResult:I.humanResult});return{...Y,records:J.map(YI),...I.includeBridge?{bridge:$D(J)}:{}}}},{name:"seal_approval_runs_summary",description:"按本地日期/时区汇总 Seal 审批运行记录,返回状态、模式统计和精简记录,避免长 JSON 输出",parameters:X.object({date:X.string().optional().describe("本地日期,格式 YYYY-MM-DD;默认使用 timezone 下的今天"),timezone:X.string().optional().describe("IANA 时区,默认 Asia/Shanghai"),offset:X.number().int().nonnegative().optional(),limit:X.number().int().positive().max(100).optional(),startDate:X.string().optional().describe("运行记录创建开始时间戳(毫秒),对应前端 startDate"),endDate:X.string().optional().describe("运行记录创建结束时间戳(毫秒),对应前端 endDate"),status:X.string().optional(),taskMode:X.string().optional(),manualApprovalStatus:X.union([X.string(),X.array(X.string())]).optional().describe("人工审核状态,如 TERMINATED 对应已驳回"),sourceDocumentSN:X.string().optional(),sourceDocumentId:X.string().optional(),humanResult:X.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),query:X.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,I)=>{let U=I.timezone??"Asia/Shanghai",Y=I.date??pZ0(Date.now(),U)??"",J=await X8($,{offset:I.offset,limit:I.limit??100,startDate:I.startDate,endDate:I.endDate,status:I.status,taskMode:I.taskMode,manualApprovalStatus:rZ0(I.manualApprovalStatus,I.humanResult),sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId}),Q=(await bZ0($,J.records,{query:I.query,humanResult:I.humanResult})).filter((K)=>pZ0(K.createdAt,U)===Y);return Fq1(Q,{date:Y,timezone:U,fetched:J.records.length,total:J.total})}},{name:"seal_approval_runs_export",description:"将企业的审批审核记录导出为高保真 Excel 报表(包含单据模板、AI决策、人工审核结论、驳回原因及企业规则列细分结果)",parameters:X.object({startDate:X.string().optional().describe("起始时间,支持 YYYY-MM-DD 或毫秒时间戳"),endDate:X.string().optional().describe("截止时间,支持 YYYY-MM-DD 或毫秒时间戳"),limit:X.number().int().positive().optional().describe("最大拉取记录条数"),status:X.string().optional().describe("单据状态过滤,如 completed, processing, failed"),manualApprovalStatus:X.union([X.string(),X.array(X.string())]).optional().describe("人工审核状态过滤,如 APPROVED, TERMINATED, PROCESSING"),includeCompletedOnly:X.boolean().optional().describe("是否仅导出已完成单据"),outputFile:X.string().optional().describe("输出 Excel 文件的自定义绝对或相对路径"),toDownloads:X.boolean().optional().describe("是否直接保存到用户的系统下载目录")}),handler:async($,I,U)=>TL($,U.corp,I)},{name:"seal_approval_run_get",description:"获取 Seal 单条审批/审核运行记录详情;可用 fields 只取 metadata、document.fields、result.summary 等局部字段",parameters:X.object({recordId:X.string().describe("Seal approval run record ID"),fields:X.union([X.string(),X.array(X.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary"),summary:X.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号")}),handler:async($,I)=>{let U=await f4($,I.recordId);if(I.summary)return Mq1(U);let Y={...U,aliases:xq1(U),humanResult:JI(U)},J=xZ0(I.fields);return J.length>0?dZ0(Y,J):Y}},{name:"seal_approval_run_cited_rules_get",description:"从审批运行结果中抽取 AI 引用或命中的规则及应用分析",parameters:X.object({recordId:X.string().describe("Seal approval run record ID")}),handler:async($,I)=>{let U=await f4($,I.recordId);return Aq1(U)}},{name:"seal_approval_run_document_summary_get",description:"返回单据关键字段、附件摘要、AI/人工结果,避免拉取完整原始单据",parameters:X.object({recordId:X.string().describe("Seal approval run record ID")}),handler:async($,I)=>{let U=await f4($,I.recordId);return lZ0(U)}},{name:"seal_approval_run_attachments_get",description:"从审批运行记录中抽取附件、发票附件和字段位置,不返回完整单据正文和规则结果",parameters:X.object({recordId:X.string().describe("Seal approval run record ID"),summary:X.boolean().optional().describe("只返回附件列表摘要")}),handler:async($,I)=>{let U=await f4($,I.recordId);return WJ(U,{summary:I.summary})}},{name:"seal_approval_run_result_get",description:"返回审批运行结果摘要;summary=true 时只返回 decision、summary、风险点数量、命中规则数量、traceId 等",parameters:X.object({recordId:X.string().describe("Seal approval run record ID"),summary:X.boolean().optional()}),handler:async($,I)=>{let U=await f4($,I.recordId);if(I.summary)return YD(U);return{recordId:U.id,result:U.result}}},{name:"seal_approval_run_url_get",description:"获取合思企业协助链接,按需附带单据链接;支持只取企业协助链接,或按 Seal recordId/合思 sourceDocumentSN 查询单据链接",parameters:X.object({recordId:X.string().optional().describe("Seal approval run record ID"),sourceDocumentSN:X.string().optional().describe("合思/易快报单号"),sourceDocumentId:X.string().optional().describe("合思/易快报源单据 ID")}),handler:async($,I,U)=>{let Y=Boolean(I.recordId||I.sourceDocumentSN||I.sourceDocumentId),J=Y?await _q1($,I):void 0,Q=U.corp.source,K=Q.type==="hose"?await Ud(U.corp):void 0,q=$4(J?.sourceExtendData?.hosecloudViewUrl);return{enterpriseAssistUrl:K,enterpriseUrl:K,hoseDomain:Q.type==="hose"?Sq1(Q.domain):void 0,documentUrl:q,recordId:J?.id,sourceDocumentSN:J?.sourceDocumentSN,sourceDocumentId:J?.sourceDocumentId,sourceSystem:J?.sourceSystem,missing:{enterpriseAssistUrl:K?void 0:"Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",documentUrl:Y&&!q?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:X.object({query:X.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:X.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:X.string().optional().describe("模拟批次 ID"),latest:X.boolean().optional().describe("只返回最新一条匹配记录"),fields:X.union([X.string(),X.array(X.string())]).optional().describe("限制返回字段"),limit:X.number().int().positive().max(100).optional(),maxScan:X.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:X.boolean().optional()}),handler:async($,I)=>{let U=I.sn??I.query;if(!U)throw Error("query or sn is required");let Y=await gq1($,{query:U,sn:I.sn,batchId:I.batchId,latest:I.latest,limit:I.latest?1:I.limit??20,maxScan:I.maxScan??1000}),J=await Promise.all(Y.records.map((q)=>f4($,q.id))),Q=xZ0(I.fields),K=J.map((q)=>jq1(q,Q));return{query:U,sourceDocumentSN:I.sn,simulationBatchId:I.batchId,latest:I.latest??!1,total:Y.total,scanned:Y.scanned,matched:K.length,records:K,next:{getSummary:"seal-home approval-runs get --summary",getRuleVersion:"seal-home rules version ",searchRuleVersion:`seal-home tool seal_approval_search --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version","ruleVersionNumber":14}'`,getVersionContext:`seal-home tool seal_approval_context_get --json '{"ruleVersionNumber":14}'`},...I.includeBridge?{bridge:$D(J)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:X.object({batchId:X.string().describe("simulation batch ID"),query:X.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,I)=>{let U=sh(await ME($,I.batchId),I.query);return{batchId:I.batchId,count:U.length,records:U.map(YI),bridge:$D(U)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:X.object({mode:X.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:X.array(X.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:X.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:X.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:X.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:X.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:X.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:X.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:X.array(X.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:X.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:X.record(X.string(),X.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),rawParams:X.record(X.string(),X.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,I)=>{let U=I.mode??"hosecloud",Y=I.signKey;if(U==="hosecloud"&&!Y){if(Y=(await TE($)).find((q)=>q.signKey)?.signKey,!Y)throw Error("未找到合思集成 signKey, 请通过 signKey 参数提供")}let J=Oq1({mode:U,flowIds:I.flowIds,rejectNodeName:I.rejectNodeName,thinkingDepthOverride:I.thinkingDepthOverride,skipInvoiceGeneration:I.skipInvoiceGeneration,skipExpenseExtraction:I.skipExpenseExtraction,disableAttachmentCache:I.disableAttachmentCache,signKey:Y,packageIds:I.packageIds,templateId:I.templateId,schemaConfig:I.schemaConfig,rawParams:I.rawParams});return{...U==="material_pack"?await $m($,J):await ed($,J),created:!0,next:{getBatch:"seal-home simulation get ",getRecords:"seal-home simulation batch-records ",listBatches:"seal-home simulation list"}}}},{name:"seal_simulation_batches_list",description:"列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",parameters:X.object({limit:X.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")}),handler:async($,I)=>{let U=await Im($,{limit:I.limit??50});return{count:U.length,batches:U.map(Nq1),next:{getBatch:"seal-home simulation get ",getRecords:"seal-home simulation batch-records "}}}},{name:"seal_simulation_batch_get",description:"获取某一次 Seal 模拟测试批次的详情,包含服务端回显的创建参数、展示摘要和任务统计",parameters:X.object({batchId:X.string().describe("simulation batch ID")}),handler:async($,I)=>{return{batch:await AE($,I.batchId),next:{getRecords:"seal-home simulation batch-records "}}}},{name:"seal_simulation_templates_get",description:"列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)",parameters:X.object({}),handler:async($)=>{let I=await Um($);return{count:I.length,templates:I.map((U)=>({id:U.id,name:U.name,description:U.description,approvalSystem:U.approvalSystem,hosecloudConfig:U.hosecloudConfig,updatedAt:U.updatedAt})),next:{createBatch:"seal-home simulation create --mode hosecloud --flow-ids ..."}}}},{name:"seal_simulation_integrations_get",description:"查询模拟测试可用的来源集成状态与合思集成选项(signKey 等)",parameters:X.object({}),handler:async($)=>{let[I,U]=await Promise.all([PE($),TE($)]);return{status:I,hosecloudIntegrations:U}}},{name:"seal_simulation_material_package_upload",description:"上传材料包 ZIP 到 Seal 模拟测试;服务端解析 Excel/AI 推断配置并返回材料包 id 与 schemaConfig(字段映射确认后用于创建模拟批次)",parameters:X.object({filePath:X.string().describe("材料包 ZIP 文件路径(含 信息表.xlsx 与附件)")}),handler:async($,I)=>{if(!I.filePath)throw Error("filePath is required");let U=Zq1(I.filePath),Y=I.filePath.split(/[\\/]/).pop()??"material-pack.zip",J=await qm($,{fileName:Y,fileBuffer:U});return{materialPackage:J,next:{createBatch:`seal-home simulation create --mode material_pack --package-ids ${J.id} --schema-config schema.json`}}}},{name:"seal_webhook_ready",description:"检查当前企业的 Webhook 就绪状态看板(包括企业环境、租户身份、凭证连通性、已激活 Webhook 通道及材料包预检)",parameters:X.object({filePath:X.string().optional().describe("可选的材料包路径(ZIP 或 信息表.xlsx),用于同步做本地预检")}),handler:async($,I,U)=>{return aL($,U.corp,{filePath:I.filePath})}},{name:"seal_webhook_material_pack",description:"将官方材料包格式本地校验、解析并通过 Seal 入站 Webhook 触发 AI 审批;preview 模式不联网,push 模式单通道自动选择",parameters:X.object({filePath:X.string().describe("材料包 ZIP 或 信息表.xlsx 文件路径"),mode:X.enum(["preview","push"]).default("preview"),webhook:X.string().optional().describe("Webhook ID 或名称;当租户仅配置 1 个通道时可省略")}),handler:async($,I)=>{let U=UI(I.filePath);if(I.mode!=="push")return II(U.fileBuffer,U.fileName);let Y=await Z9($),J;if(I.webhook)J=z9(Y,I.webhook);else if(Y.length===1)J=Y[0];else if(Y.length>1){let Q=Y.map((K)=>`"${K.name}" (${K.id})`).join(", ");throw Error(`当前租户存在多个 Webhook 通道 [${Q}],请通过 webhook 参数指定目标通道。`)}else throw Error("当前租户未配置任何 Webhook 集成通道。");return tL(U.fileBuffer,U.fileName,{webhookUrl:J.incomingDocumentWebhook.url,secret:J.secret,materialPackFilePolicy:J.materialPackFilePolicy})}},{name:"seal_approval_run_langfuse_bridge_get",description:"从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",parameters:X.object({recordId:X.string().optional(),sourceDocumentSN:X.string().optional(),sourceDocumentId:X.string().optional(),simulationBatchId:X.string().optional(),limit:X.number().int().positive().max(100).optional()}),handler:async($,I)=>{let Y=(I.simulationBatchId?await ME($,I.simulationBatchId):(await X8($,{limit:I.limit??50,search:I.sourceDocumentSN??I.sourceDocumentId,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId})).records).filter((J)=>kq1(J,{recordId:I.recordId,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId}));return{count:Y.length,records:Y.map(YI),bridge:$D(Y)}}},{name:"seal_simulation_batch_wait",description:"等待 Seal 模拟测试批次完成(轮询状态直到 completed/failed/canceled 或超时)",parameters:X.object({batchId:X.string().describe("模拟批次 ID"),timeout:X.string().default("10m").describe("最长等待时间, 默认 10m"),pollInterval:X.string().default("2s").describe("轮询间隔, 默认 2s")}),handler:async($,I)=>{let U=hZ0(I.timeout??"10m"),Y=hZ0(I.pollInterval??"2s"),J=Date.now();while(!0){let Q=await AE($,I.batchId),K=(Q.status??"").toLowerCase();if(["completed","failed","cancelled","canceled"].includes(K))return{batch:Q,completed:!0,status:K,elapsedMs:Date.now()-J,next:{getRecords:`seal-home simulation batch-records ${I.batchId}`}};if(Date.now()-J>=U)throw Error(`等待模拟批次 ${I.batchId} 超时(已等待 ${(Date.now()-J)/1000}s)。可稍后执行 seal-home simulation get ${I.batchId} 查看状态`);await new Promise((q)=>setTimeout(q,Y))}}},{name:"seal_simulation_batch_clean",description:"删除模拟测试批次产生的测试数据",parameters:X.object({batchId:X.string().describe("模拟批次 ID")}),handler:async($,I)=>{let U=await Ym($,I.batchId);return{batchId:I.batchId,cleaned:!0,result:U}}},{name:"seal_simulation_specifications_list",description:"列出指定合思集成可用的单据模板列表",parameters:X.object({signKey:X.string().optional().describe("合思集成 sign-key")}),handler:async($,I)=>{let U=await Jm($,I.signKey);return{count:U.length,specifications:U}}},{name:"seal_deploy_hosecloud_requirements",description:"获取 Seal AI 审批发布到合思费控所需配置字段与说明",parameters:X.object({}),handler:async()=>{return{input:`JSON via --json '{"apiKey":"...","apiSecret":"...","mode":"assisted"}'`,questions:[{field:"apiOrigin",prompt:"使用哪一种合思版本或 API 环境?(production/custom,未指定时自动探测)",required:!1,default:"production"},{field:"customApiUrl",prompt:"自定义环境的 API 地址是什么?(如专属私有云域名)",requiredWhen:"apiOrigin=custom"},{field:"apiKey",prompt:"合思 API Key(appKey)是什么?",required:!0,secret:!0},{field:"apiSecret",prompt:"合思 API Secret(appSecurity)是什么?",required:!0,secret:!0},{field:"mode",prompt:"使用全自动、半自动还是辅助审核?(fully_automatic/semi_automatic/assisted)",required:!0,default:"assisted"},{field:"autoApprovalRate",prompt:"自动审批比例是多少?(0-100)",requiredWhen:"mode!=assisted"},{field:"rejectResubmitMethod",prompt:"驳回重提后从哪个节点继续?(node_default/to_ebot/from_start)"},{field:"autoApproveNodeNames",prompt:"哪些节点允许自动审批?(string[])"},{field:"outboundName",prompt:"合思审批流节点消息名称是什么?",default:"SealAI 审批"}]}}},{name:"seal_deploy_hosecloud_list",description:"列出当前企业【Seal AI 审批发布到合思费控】的集成配置列表",parameters:X.object({}),handler:async($)=>{let U=((await q4($)).integrations??[]).filter((Y)=>Y.type==="hosecloud");return{count:U.length,integrations:U.map(sL)}}},{name:"seal_deploy_hosecloud_get",description:"查询【Seal AI 审批发布到合思费控】的单项配置详情",parameters:X.object({signKey:X.string().describe("合思集成 sign-key")}),handler:async($,I)=>{let Y=((await q4($)).integrations??[]).find((J)=>J.type==="hosecloud"&&J.signKey===I.signKey);if(!Y)throw Error(`未找到合思配置:${I.signKey}`);return sL(Y)}},{name:"seal_deploy_hosecloud_status",description:"检查【Seal AI 审批发布到合思费控】与多平台集成状态",parameters:X.object({}),handler:async($)=>{let I=await PE($),Y=((await q4($)).integrations??[]).filter((J)=>J.type==="hosecloud");return{status:I,integrations:Y.map(sL)}}},{name:"seal_deploy_hosecloud_configure",description:"自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置",parameters:X.object({apiKey:X.string().describe("合思 API Key (appKey)"),apiSecret:X.string().describe("合思 API Secret (appSecurity)"),signKey:X.string().optional().describe("集成 signKey,不提供则自动生成"),outboundName:X.string().optional().describe("出站消息名称(合思审批流节点中显示)"),specificationId:X.string().optional(),specificationName:X.string().optional(),mode:X.enum(["fully_automatic","semi_automatic","assisted"]).default("assisted"),autoApprovalRate:X.number().min(0).max(100).optional(),rejectResubmitMethod:X.enum(["node_default","to_ebot","from_start"]).optional(),autoApproveNodeNames:X.array(X.string()).optional(),apiOrigin:X.string().default("production"),customApiUrl:X.string().optional()}),handler:async($,I,U)=>{let Y=I.apiKey??I.appKey,J=I.apiSecret??I.appSecurity;if(!Y||!J)throw Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");let Q={...I,apiKey:Y,apiSecret:J},K=Q.apiOrigin??"production",q=Q.customApiUrl;if(!q&&K!=="custom")try{let Z=await zU(Q.apiKey,Q.apiSecret);if(Z?.domain)if(Z.domain==="https://app.ekuaibao.com")K="production",q=void 0;else K="custom",q=Z.domain}catch{}if(K==="custom"&&!q)throw Error("自定义合思环境必须提供 customApiUrl");let G=await Qm($,{apiKey:Q.apiKey,apiSecret:Q.apiSecret,apiOrigin:K,customApiUrl:q}),H=await q4($),W=Q.signKey??zq1(6).toString("hex"),V={type:"hosecloud",...Q,apiOrigin:K,...q?{customApiUrl:q}:{},signKey:W,corporationId:G.corporationId},z=(H.integrations??[]).filter((Z)=>Z.type!=="hosecloud"||Z.signKey!==W);return z.push(V),await y7($,{...H,integrationSystem:"hosecloud",integrations:z}),console.error(`✓ 配置已保存 (signKey: ${W})`),console.error(`\uD83D\uDC49 下一步操作:运行 \`seal-use deploy hosecloud sync ${W} --corp ${U.corp.id}\` 一键同步发布到合思审批流`),{integration:sL(V)}}},{name:"seal_deploy_hosecloud_sync",description:"一键将 Seal AI 审核配置同步发布到合思费控审批流",parameters:X.object({signKey:X.string().describe("合思集成 sign-key")}),handler:async($,I,U)=>{let J=((await q4($)).integrations??[]).find((G)=>G.type==="hosecloud"&&G.signKey===I.signKey);if(!J)throw Error(`未找到合思配置:${I.signKey}`);let Q=(U.corp.seal.url??`https://${U.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,""),K=J.outboundName??"SealAI 审批",q=await Km($,{signKey:I.signKey,webhookUrl:`${Q}/api/hosecloud/outbound?config_id=${encodeURIComponent(I.signKey)}`,completionWebhookUrl:`${Q}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(I.signKey)}`,messageName:K,mode:J.mode??"assisted"});return console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${K}"`),console.error(`\uD83D\uDC49 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${K}"。`),{signKey:I.signKey,synced:!0,result:q}}},{name:"seal_preference_get",description:"获取当前决策偏好、思考深度偏好与绑定的规则版本",parameters:X.object({}),handler:async($)=>{let I=await q4($);return{decisionPreferences:I.decisionPreferences,thinkingDepthPreference:I.thinkingDepthPreference,ruleSetVersionId:I.ruleSetVersionId}}},{name:"seal_preference_decision_update",description:"修改审核决策偏好(立即影响当前运行中的审核智能体及后续决策)",parameters:X.object({explicitApprove:X.string().optional(),explicitReject:X.string().optional(),exemptApprove:X.string().optional(),review:X.string().optional()}),handler:async($,I)=>{let U=await q4($),Y={...U,decisionPreferences:{...U.decisionPreferences,...I}};return await y7($,Y),{decisionPreferences:Y.decisionPreferences}}},{name:"seal_preference_thinking_depth_set",description:"修改默认思考深度(medium 或 high)",parameters:X.object({defaultLevel:X.enum(["medium","high"]).describe("默认思考深度")}),handler:async($,I)=>{let U=await q4($),Y={...U,thinkingDepthPreference:{defaultLevel:I.defaultLevel,routingPolicies:U.thinkingDepthPreference?.routingPolicies??[]}};return await y7($,Y),{thinkingDepthPreference:Y.thinkingDepthPreference}}},{name:"seal_preference_thinking_depth_policies_list",description:"列出思考深度路由策略列表",parameters:X.object({}),handler:async($)=>{return{policies:(await q4($)).thinkingDepthPreference?.routingPolicies??[]}}},{name:"seal_preference_thinking_depth_policies_upsert",description:"新增或修改思考深度路由策略",parameters:LE,handler:async($,I)=>{let U=await q4($),J=(U.thinkingDepthPreference?.routingPolicies??[]).filter((K)=>K.id!==I.id);J.push(I);let Q={...U,thinkingDepthPreference:{defaultLevel:U.thinkingDepthPreference?.defaultLevel??"medium",routingPolicies:J}};return await y7($,Q),{policy:I,policies:J}}},{name:"seal_preference_thinking_depth_policies_remove",description:"删除一条思考深度路由策略",parameters:X.object({policyId:X.string().describe("路由策略 ID")}),handler:async($,I)=>{let U=await q4($),Y=U.thinkingDepthPreference?.routingPolicies??[],J=Y.filter((K)=>K.id!==I.policyId);if(J.length===Y.length)throw Error(`未找到路由策略:${I.policyId}`);let Q={...U,thinkingDepthPreference:{defaultLevel:U.thinkingDepthPreference?.defaultLevel??"medium",routingPolicies:J}};return await y7($,Q),{removedId:I.policyId,policies:J}}},{name:"seal_approval_runs_stats",description:"统计审核记录状态分布、来源系统分布及按单号/ID去重统计",parameters:X.object({since:X.string().optional().describe("时间范围,如 3months, 7days, 24hours"),dedupeBy:X.enum(["sourceDocumentSN","sourceDocumentId","id"]).default("sourceDocumentSN").describe("去重字段"),status:X.string().optional(),sourceSystem:X.string().optional(),taskMode:X.string().optional()}),handler:async($,I)=>{let U=await X8($,{limit:1000,status:I.status,sourceSystem:I.sourceSystem,taskMode:I.taskMode}),Y=I.dedupeBy??"sourceDocumentSN",J=U.records,Q={},K={},q=new Set;for(let G of J){let H=G.status??"unknown";Q[H]=(Q[H]??0)+1;let W=G.sourceSystem??"unknown";K[W]=(K[W]??0)+1;let V=G[Y];if(V)q.add(String(V))}return{total:J.length,dedupeBy:Y,unique:q.size,byStatus:Q,bySourceSystem:K}}},{name:"seal_approval_runs_count",description:"统计符合条件的审核记录总数",parameters:X.object({status:X.string().optional(),sourceSystem:X.string().optional(),taskMode:X.string().optional(),search:X.string().optional()}),handler:async($,I)=>{let U=await X8($,{limit:1,status:I.status,sourceSystem:I.sourceSystem,taskMode:I.taskMode,search:I.search});return{total:U.total??U.records.length}}}],Xq1=new Map(JG.map(($)=>[$.name,$]));function C4($){return Xq1.get($)}function YG($,I){return I?$:{...$,secret:""}}function wq1($){if($.seal.url)return $.seal.url;if($.source.type==="hose")return Q2($,$.source);return $.source.sealUrl}function Lq1($,I){let U=$.rules.length;if(I.countOnly||I.limit===0)return{count:U};let Y=I.offset??0,J=$.rules.slice(Y,I.limit===void 0?void 0:Y+I.limit),Q=I.fields;return{count:U,hasPendingDeletes:$.hasPendingDeletes,rules:Q?J.map((K)=>Dq1(K,Q)):J}}function Dq1($,I){let U={};for(let Y of I)if($[Y]!==void 0)U[Y]=$[Y];return U}function hZ0($){let I=$.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i);if(!I||!I[1])return 600000;let U=parseFloat(I[1]);switch((I[2]??"s").toLowerCase()){case"ms":return U;case"s":return U*1000;case"m":return U*60*1000;case"h":return U*3600*1000;case"d":return U*86400*1000;default:return U*1000}}function sL($){return Object.fromEntries(Object.entries($).map(([I,U])=>[I,["apiKey","apiSecret","secret"].includes(I)&&typeof U==="string"?"***":U]))}function Oq1($){let I=$.sourceSystem??$.mode??"hosecloud",U={skipInvoiceGeneration:$.skipInvoiceGeneration??!0,skipExpenseExtraction:$.skipExpenseExtraction??!0,thinkingDepthOverride:$.thinkingDepthOverride??"default",disableAttachmentCache:$.disableAttachmentCache??!1},Y=$.flowIds??(typeof $.documentSn==="string"?$.documentSn.split(",").map((J)=>J.trim()).filter(Boolean):$.documentSn);if(I==="hosecloud"){if(!Y?.length&&$.startTime===void 0)throw Error("hosecloud 模式需要提供 flowIds(单号列表)");if(Object.assign(U,{dataCollectionMode:"2",rejectNodeName:$.rejectNodeName??null,sourceSystem:"hosecloud"}),Y?.length)U.flowIds=Y;if($.signKey)U.signKey=$.signKey;if($.startTime!==void 0)U.startTime=$.startTime;if($.endTime!==void 0)U.endTime=$.endTime;if($.status)U.status=$.status;if($.limit)U.limit=$.limit}else if(I==="material_pack"||I==="material-pack"){let J=$.packageIds??($.packageId?[$.packageId]:void 0);if(!J?.length)throw Error("material_pack 模式需要提供 packageIds(材料包 id)");let Q=$.templateId??$.schemaConfig?.id;if(!Q)throw Error("material_pack 模式需要提供 templateId(或 schemaConfig.id)");if(Object.assign(U,{templateId:Q,packageIds:J,approvalCode:$.approvalCode??"material_pack",nodeId:$.nodeId??"material_pack",runMode:$.runMode??"import_and_simulate"}),$.schemaConfig!==void 0)U.schemaConfig=$.schemaConfig}else if(I==="weaver")Object.assign(U,{sourceSystem:"weaver",workflowTypeId:$.workflowTypeId,requestIds:$.requestIds,flowStatusList:$.flowStatusList,nodeId:$.nodeId,startTime:$.startTime,endTime:$.endTime,status:$.status,limit:$.limit??100,rejectNodeName:$.rejectNodeName??null});else if(I==="helios")Object.assign(U,{sourceSystem:"helios",documentType:$.documentType,businessCodes:$.businessCodes,rejectNodeName:$.rejectNodeName??null});else if(I==="maycur"||I==="maycur-standard")Object.assign(U,{sourceSystem:I,formCodes:$.formCodes??Y,createdAtStart:$.startTime,createdAtEnd:$.endTime,formSubTypeBizCode:$.formSubTypeBizCode,formStatus:$.formStatus,pageNo:$.pageNo??1,pageSize:$.pageSize??100,signKey:$.signKey});else if(I==="feishu")Object.assign(U,{sourceSystem:"feishu",approvalCode:$.approvalCode,nodeId:$.nodeId,startTime:$.startTime,endTime:$.endTime,status:$.status,limit:$.limit??100,signKey:$.signKey});else Object.assign(U,{sourceSystem:I});if($.rawParams)Object.assign(U,$.rawParams);return U}function Nq1($){return{id:$.id,status:$.status,approvalCode:$.approvalCode,sourceSystem:$.sourceSystem,totalCount:$.totalCount,processedCount:$.processedCount,successCount:$.successCount,failedCount:$.failedCount,createdCount:$.createdCount,createFailedCount:$.createFailedCount,requestSummary:$.requestSummary,resultSummary:$.resultSummary,createdAt:$.createdAt}}function YI($){let I=$.sourceDocumentSN,U=JI($),Y=YD($);return{id:$.id,tenantId:$.tenantId,agentId:$.agentId,status:$.status,taskMode:$.taskMode,finalExecutionMode:$.finalExecutionMode,sourceSystem:$.sourceSystem,sourceDocumentSN:I,sourceDocumentId:$.sourceDocumentId,documentId:$.documentId,simulationBatchId:$.sourceExtendData?.simulation_batch_id,langfuseTraceId:$.sourceExtendData?._langfuseTraceId,langfuseSessionFallback:I?`hosecloud-${I}`:void 0,ruleSetVersionNumber:$.ruleSetVersionNumber,ruleSetPublishedAt:$.ruleSetPublishedAt,ruleSetPublishedByName:$.ruleSetPublishedByName,humanResult:U?.value,humanResultPath:U?.path,aiDecision:Y.decision,aiSummary:Y.summary,createdAt:$.createdAt,updatedAt:$.updatedAt}}function Fq1($,I){return{date:I.date,timezone:I.timezone,fetched:I.fetched,matched:$.length,total:I.total,statusCounts:nZ0($,(U)=>U.status??"unknown"),taskModeCounts:nZ0($,(U)=>U.taskMode??"unknown"),records:$.map((U)=>{let Y=YI(U);return{createdAt:cZ0(Y.createdAt,I.timezone),sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId,status:Y.status,taskMode:Y.taskMode,finalExecutionMode:Y.finalExecutionMode,simulationBatchId:Y.simulationBatchId,langfuseTraceId:Y.langfuseTraceId,langfuseSessionFallback:Y.langfuseSessionFallback,ruleSetVersionNumber:Y.ruleSetVersionNumber,ruleSetPublishedAt:cZ0(Y.ruleSetPublishedAt,I.timezone),ruleSetPublishedByName:Y.ruleSetPublishedByName,humanResult:Y.humanResult,humanResultPath:Y.humanResultPath,recordId:Y.id}})}}function xZ0($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((U)=>U.trim()).filter(Boolean)}function dZ0($,I){let U={};for(let Y of I){if(Y==="metadata"){U.metadata=mZ0($);continue}let J=b5($,Y);if(J!==void 0)Pq1(U,Y,J)}return U}function mZ0($){let I=YI($);return{recordId:I.id,tenantId:I.tenantId,agentId:I.agentId,sourceSystem:I.sourceSystem,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId,documentId:I.documentId,status:I.status,taskMode:I.taskMode,finalExecutionMode:I.finalExecutionMode,simulationBatchId:I.simulationBatchId,langfuseTraceId:I.langfuseTraceId,langfuseSessionFallback:I.langfuseSessionFallback,ruleSetVersionNumber:I.ruleSetVersionNumber,ruleSetPublishedAt:I.ruleSetPublishedAt,ruleSetPublishedByName:I.ruleSetPublishedByName,createdAt:I.createdAt,updatedAt:I.updatedAt}}function Mq1($){return{metadata:mZ0($),document:lZ0($).document,aiResult:YD($),manualResult:JI($)?.value,manualResultPath:JI($)?.path,ruleSetVersionNumber:$.ruleSetVersionNumber,ruleSetPublishedAt:$.ruleSetPublishedAt,ruleSetPublishedByName:$.ruleSetPublishedByName}}function YD($){let I=QG($.result);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,traceId:$.sourceExtendData?._langfuseTraceId,langfuseTraceId:$.sourceExtendData?._langfuseTraceId,decision:ID(I,["decision","manualApproval.decision","manualApproval.result","review.decision","finalDecision"]),summary:ID(I,["summary","result.summary","review.summary","conclusion"]),riskPointCount:kZ0(I,["riskPoints","risks","risk_points","review.riskPoints"]),matchedRuleCount:kZ0(I,["matchedRules","hitRules","ruleResults","rules","review.matchedRules"])}}function lZ0($){let I=QG($.document),U=Eq1($.document),Y=U.map((J)=>`${J.label??J.path??""}:${J.value??""}`).join(` -`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:MJ({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:ID(I,["template.name","templateName","form.name","formName","formTitle"]),amount:eL(U,["金额","报销金额","付款金额","合计","价税合计"])??ID(I,["amount","totalAmount","expenseAmount"]),expenseType:eL(U,["费用类型","费用类别","报销类型"]),costCompany:eL(U,["费用承担公司","承担公司","成本中心","费用归属"]),payee:eL(U,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:U.slice(0,30)}),invoices:Bq1($),attachments:WJ($,{summary:!0}).attachments,aiResult:YD($),manualResult:JI($)?.value,hints:MJ({amountMentions:uZ0(Y,["金额","合计","税率"],8),partyMentions:uZ0(Y,["买方","卖方","甲方","乙方","收款"],8)})}}function Aq1($){let I=[["result.citedRules",b5($,"result.citedRules")],["result.matchedRules",b5($,"result.matchedRules")],["result.ruleResults",b5($,"result.ruleResults")],["result.rules",b5($,"result.rules")],["pipelineData.citedRules",b5($,"pipelineData.citedRules")],["pipelineData.matchedRules",b5($,"pipelineData.matchedRules")]],U=[],Y=new Set;for(let[J,Q]of I)(Array.isArray(Q)?Q:Q&&typeof Q==="object"?Object.values(Q):[]).forEach((q,G)=>{let H=QG(q);if(!H)return;let W=$4(H.runtimeRuleId)??$4(H.runtimeId)??$4(H.id)??$4(H.ruleId),V=$4(H.ruleCode)??$4(H.code)??(W?Cq1(W):void 0),z=MJ({runtimeRuleId:W,ruleCode:V,versionNumber:Tq1(H.versionNumber)??$.ruleSetVersionNumber,scope:$4(H.scope),strictness:$4(H.strictness),appliedAnalysis:H.appliedAnalysis??H.analysis??H.reasoning,checkResult:H.checkResult??H.result??H.decision,findings:H.findings??H.riskPoints??H.evidence,sourcePath:`${J}.${G}`}),Z=JSON.stringify(z);if(!Y.has(Z))Y.add(Z),U.push(z)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:U.length,rules:U}}function ID($,I){if(!$)return;for(let U of I){let Y=b5($,U);if(Y!==void 0)return Y}return}function kZ0($,I){if(!$)return 0;for(let U of I){let Y=b5($,U);if(Array.isArray(Y))return Y.length;if(Y&&typeof Y==="object")return Object.keys(Y).length;if(typeof Y==="number")return Y}return 0}function b5($,I){return I.split(".").reduce((U,Y)=>{if(U===void 0||U===null)return;if(Array.isArray(U)){let J=Number(Y);return Number.isInteger(J)?U[J]:void 0}if(typeof U==="object")return U[Y];return},$)}function Pq1($,I,U){let Y=I.split("."),J=$;for(let Q of Y.slice(0,-1)){let K=J[Q];if(!K||typeof K!=="object"||Array.isArray(K))J[Q]={};J=J[Q]}J[Y[Y.length-1]??I]=U}function MJ($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function QG($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Tq1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Eq1($){let I=[];return mh($,"document",I),I}function mh($,I,U){if(Array.isArray($)){$.forEach((K,q)=>mh(K,`${I}.${q}`,U));return}let Y=QG($);if(!Y)return;let J=$4(Y.label)??$4(Y.name)??$4(Y.title)??$4(Y.fieldName),Q=Y.value??Y.displayValue??Y.text??Y.content;if(J&&Q!==void 0&&typeof Q!=="object")U.push(MJ({path:I,label:J,value:Q,type:$4(Y.type)??$4(Y.fieldType)}));for(let[K,q]of Object.entries(Y)){if(K==="attachments")continue;mh(q,`${I}.${K}`,U)}}function eL($,I){return $.find((Y)=>{let J=$4(Y.label)??"";return I.some((Q)=>J.includes(Q))})?.value}function Bq1($){let I=[];return UD($.result,"result",I),UD($.document,"document",I),I.slice(0,20)}function UD($,I,U){if(Array.isArray($)){$.forEach((J,Q)=>UD(J,`${I}.${Q}`,U));return}let Y=QG($);if(!Y)return;if(/invoice|发票/i.test(I))U.push(MJ({path:I,fileName:$4(Y.fileName)??$4(Y.filename)??$4(Y.name),buyer:Y.buyer??Y.buyerName??Y.purchaserName,seller:Y.seller??Y.sellerName,amount:Y.amount??Y.totalAmount??Y.total,taxRate:Y.taxRate,category:Y.category??Y.type}));for(let[J,Q]of Object.entries(Y))UD(Q,`${I}.${J}`,U)}function uZ0($,I,U){return $.split(/\r?\n/).filter((Y)=>I.some((J)=>Y.includes(J))).slice(0,U)}function $D($){return $.map((I)=>{let U=YI(I);return{recordId:U.id,tenantId:U.tenantId,agentId:U.agentId,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,langfuseTraceId:U.langfuseTraceId,langfuseSessionFallback:U.langfuseSessionFallback,ruleSetVersionNumber:U.ruleSetVersionNumber,ruleSetPublishedAt:U.ruleSetPublishedAt,ruleSetPublishedByName:U.ruleSetPublishedByName,resolution:U.langfuseTraceId?"trace":U.langfuseSessionFallback?"session-fallback":"unresolved"}})}function ch($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function Rq1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let U=await f4($,I.recordId);if(!U.ruleSetVersionNumber)throw Error(`Approval run ${I.recordId} has no ruleSetVersionNumber`);return lh($,{versionNumber:U.ruleSetVersionNumber})}return lh($,I)}function vq1($,I){let U=dh(I.code),Y=oZ0(I.runtimeId),J=U?Number(U.slice(1)):Y;if(!J||J<1)throw Error("Pass --code '#0038' or --runtime-id rule-205");let Q=$.rules.find((G,H)=>{let W=G;return dh($4(W.code)??$4(W.ruleCode))===U||H+1===J});if(!Q)return;let K=Q,q=$.rules.indexOf(Q)+1;return MJ({runtimeRuleId:$4(K.runtimeRuleId)??`rule-${q}`,ruleCode:dh($4(K.code)??$4(K.ruleCode))??ah(q),versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt,publishedByName:$.publishedByName,description:Q.description,scope:Q.scope,strictness:Q.strictness,status:$4(K.status)})}function dh($){if(!$)return;let I=$.match(/\d+/)?.[0];return I?ah(Number(I)):$}function oZ0($){if(!$)return;let I=$.match(/(\d+)$/);return I?Number(I[1]):void 0}function Cq1($){let I=oZ0($);return I?ah(I):void 0}function ah($){return`#${String($).padStart(4,"0")}`}function jq1($,I){let U=YI($),Y={recordId:U.id,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,status:U.status,taskMode:U.taskMode,ruleSetVersionNumber:U.ruleSetVersionNumber,langfuseTraceId:U.langfuseTraceId,manualResult:U.humanResult,aiDecision:U.aiDecision,aiSummary:U.aiSummary,createdAt:U.createdAt};if(I.length===0)return Y;return dZ0(Y,I)}async function _q1($,I){if(I.recordId)return f4($,I.recordId);let Y=(await X8($,{limit:1,search:I.sourceDocumentSN??I.sourceDocumentId,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId})).records[0];if(!Y){let J=I.sourceDocumentSN?`sourceDocumentSN ${I.sourceDocumentSN}`:`sourceDocumentId ${I.sourceDocumentId}`;throw Error(`Approval run not found for ${J}`)}return f4($,Y.id)}function Sq1($){return $.replace(/\/+$/,"")}function $4($){return typeof $==="string"&&$.trim()?$:void 0}async function gq1($,I){let U=Math.min(100,Math.max(I.limit,20)),Y=[],J,Q=0;while(Q!I.sn||G.sourceDocumentSN===I.sn).filter((G)=>!I.batchId||G.sourceExtendData?.simulation_batch_id===I.batchId);if(Y.push(...q),K.records.length===0||J!==void 0&&Q>=J)break}return Y.sort((K,q)=>fZ0(q.createdAt)-fZ0(K.createdAt)),{total:J,scanned:Q,records:Y.slice(0,I.latest?1:I.limit)}}function fZ0($){if(typeof $==="number")return $;if(typeof $==="string"){let I=Date.parse($);return Number.isFinite(I)?I:0}return 0}async function lh($,I){if(I.versionId)return W2($,I.versionId);let U=await Y5($),Y=I.versionNumber?U.find((J)=>J.versionNumber===I.versionNumber):U[0];if(!Y)throw Error(I.versionNumber?`Rule version not found: ${I.versionNumber}`:"No rule versions found");return Y}function sh($,I){let U=I?.trim().toLowerCase();if(!U)return $;return $.filter((Y)=>{return[Y.id,Y.sourceDocumentSN,Y.sourceDocumentId,Y.documentId,Y.sourceExtendData?._langfuseTraceId,Y.sourceExtendData?.simulation_batch_id,Y.status,Y.taskMode,Y.finalExecutionMode,Y.sourceSystem,Y.ruleSetVersionNumber,Y.ruleSetPublishedByName].some((Q)=>oh(Q,U))||rh(Y,U)})}function oh($,I){if($===null||$===void 0)return!1;if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return String($).toLowerCase().includes(I);return!1}function rh($,I,U=0){if(U>6)return!1;if(oh($,I))return!0;if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some((Y)=>rh(Y,I,U+1));return Object.entries($).some(([Y,J])=>oh(Y,I)||rh(J,I,U+1))}function yq1($,I){let U=I?.trim().toLowerCase();if(!U)return $;return $.filter((Y)=>JI(Y)?.value.toLowerCase().includes(U))}function hq1($){return{...$,manualApprovalStatus:rZ0($.manualApprovalStatus,$.humanResult)}}function rZ0($,I){if($)return $;let U=I?.trim().toLowerCase();if(!U)return;if(["驳回","已驳回","拒绝","不通过","terminated","reject","rejected","denied"].includes(U))return"TERMINATED";return}async function bZ0($,I,U){let Y=sh(I,U.query);if(!U.humanResult?.trim())return Y;let J=await Promise.all(Y.map(async(Q)=>{if(JI(Q))return Q;try{return await f4($,Q.id)}catch{return Q}}));return yq1(J,U.humanResult)}function xq1($){return{originalDocumentData:{path:"document",frontendLabel:"单据原始数据",description:"前端详情页展示的单据原始数据对象",id:$.document?.id??$.documentId,sourceDocumentSN:$.document?.sourceDocumentSN??$.sourceDocumentSN,sourceDocumentId:$.document?.sourceDocumentId??$.sourceDocumentId},aiDocumentFields:{path:"document.fields",frontendLabel:"AI 看的单据",description:"AI 审核实际读取的字段数组,即单据原始数据中的 fields",fieldCount:$.document?.fields?.length},aiDocument:{path:"document.fields",frontendLabel:"AI 看的单据",description:"兼容别名,等同于 aiDocumentFields",aliasOf:"aiDocumentFields",fieldCount:$.document?.fields?.length},sourceDocument:{path:"sourceExtendData.hosecloudViewUrl",description:"合思原始单据入口;详情响应中只有入口和源单据 ID,不包含完整原始单据 JSON",sourceSystem:$.sourceSystem,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,originalDocumentId:$.sourceExtendData?.original_document_id,viewUrl:$.sourceExtendData?.hosecloudViewUrl},aiResult:{path:"result",description:"AI 最终审核结构化结果"},aiAuditLog:{path:"pipelineData.logs",description:"AI 审核过程日志"},manualApproval:{path:"manualApprovalRecord",description:"人工审核结果、节点和驳回原因"}}}function JI($){let I=[["result",$.result],["pipelineData",$.pipelineData]];for(let[U,Y]of I){let J=th(Y,U);if(J)return J}return}function th($,I,U=0){if(U>8||$===null||$===void 0)return;if(Array.isArray($)){for(let Y=0;Y<$.length;Y+=1){let J=th($[Y],`${I}[${Y}]`,U+1);if(J)return J}return}if(typeof $!=="object")return;for(let[Y,J]of Object.entries($)){let Q=`${I}.${Y}`,K=th(J,Q,U+1);if(K)return K;if(iZ0(Y)||iZ0(Q)){let q=tZ0(J);if(q)return{value:q,path:Q}}}return}function iZ0($){let I=$.toLowerCase(),U=I.includes("human")||I.includes("manual")||I.includes("reviewer")||I.includes("operator")||$.includes("人工")||$.includes("人工审批")||$.includes("人工审核"),Y=I.includes("result")||I.includes("decision")||I.includes("outcome")||I.includes("conclusion")||I.includes("action")||$.includes("结果")||$.includes("结论")||$.includes("动作");return U&&Y}function tZ0($){if(typeof $==="string")return $.trim()||void 0;if(typeof $==="number"||typeof $==="boolean")return String($);if(!$||typeof $!=="object")return;let I=$;for(let U of["label","name","text","value","result","decision","outcome","status","action"]){let Y=tZ0(I[U]);if(Y)return Y}return}function kq1($,I){if(I.recordId&&$.id!==I.recordId)return!1;if(I.sourceDocumentSN&&$.sourceDocumentSN!==I.sourceDocumentSN)return!1;if(I.sourceDocumentId&&$.sourceDocumentId!==I.sourceDocumentId)return!1;return!0}function nZ0($,I){return $.reduce((U,Y)=>{let J=I(Y);return U[J]=(U[J]??0)+1,U},{})}function pZ0($,I){let U=aZ0($);if(!U)return;let Y=sZ0(U,I),J=Y.year,Q=(Y.month??"01").padStart(2,"0"),K=(Y.day??"01").padStart(2,"0");return`${J}-${Q}-${K}`}function cZ0($,I){let U=aZ0($);if(!U)return;let Y=sZ0(U,I),J=(Y.month??"01").padStart(2,"0"),Q=(Y.day??"01").padStart(2,"0"),K=(Y.hour??"00").padStart(2,"0"),q=(Y.minute??"00").padStart(2,"0"),G=(Y.second??"00").padStart(2,"0");return`${Y.year??"0000"}-${J}-${Q} ${K}:${q}:${G}`}function aZ0($){if($===void 0)return null;let I=new Date($);return Number.isNaN(I.getTime())?null:I}function sZ0($,I){return Object.fromEntries(new Intl.DateTimeFormat("en-CA",{timeZone:I,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts($).filter((U)=>U.type!=="literal").map((U)=>[U.type,U.value]))}import{writeFileSync as uq1}from"node:fs";function eZ0($){let I=[],U={},Y;for(let J=0;J<$.length;J+=1){let Q=$[J];if(!Q)continue;if(Q==="--json"){let K=$[J+1];if(!K)throw Error("--json requires a JSON object argument");Y=JSON.parse(K),J+=1;continue}if(Q.startsWith("-")){let K=Q.replace(/^-+/,"");if(K.includes("=")){let G=K.indexOf("="),H=K.slice(0,G),W=K.slice(G+1);U[H]=W;continue}let q=$[J+1];if(!q||q.startsWith("-"))U[K]=!0;else U[K]=q,J+=1;continue}I.push(Q)}return{command:I,options:U,json:Y}}function t6($){if($===void 0)return{};if(!$||typeof $!=="object"||Array.isArray($))throw Error("--json must be an object");return $}function h($){return typeof $==="string"?$:void 0}function a0($){if(typeof $!=="string")return;let I=Number($);if(!Number.isFinite(I))throw Error(`Invalid number: ${$}`);return I}function W6($){if(typeof $!=="string")return;let I=$.split(",").map((U)=>U.trim()).filter(Boolean);return I.length?I:void 0}function _0($){if($===void 0)return;if(typeof $==="boolean")return $;if($==="true")return!0;if($==="false")return!1;throw Error(`Invalid boolean: ${$}`)}function z7($,I){let U=i1($,I);if(!U)throw Error(`Missing required JSON field: ${I}`);return U}function i1($,I){let U=$[I];return typeof U==="string"&&U.trim()?U.trim():void 0}function $z0($,I){let U=$[I];return typeof U==="number"&&Number.isFinite(U)?U:void 0}function eh($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function Iz0($){let I=$.trim().toLowerCase();if(["stateful","state","有状态"].includes(I))return!0;if(["stateless","无状态"].includes(I))return!1;throw Error("Invalid config mode. Use stateful or stateless.")}function KG($){if($==="latest")return{latest:!0};let I=Number($);if(Number.isInteger(I)&&I>0)return{versionNumber:I};return{versionId:$}}function Uz0($){if(!$)return{};let I=KG($);if("latest"in I)return{ruleVersionScope:"version",latestRuleVersion:!0};if("versionNumber"in I)return{ruleVersionScope:"version",ruleVersionNumber:I.versionNumber};return{ruleVersionScope:"version",ruleVersionId:I.versionId}}function Yz0($){if(!$)return{};let I=KG($);if("latest"in I)return{latestRuleVersion:!0};if("versionNumber"in I)return{ruleVersionNumber:I.versionNumber};return{ruleVersionId:I.versionId}}function Jz0($){if(!$)return{};let I=KG($);if("latest"in I)return{latest:!0};if("versionNumber"in I)return{versionNumber:I.versionNumber};return{versionId:I.versionId}}function $x($){if(!$)return;let I=$.trim().toLowerCase().replace(/[\s-]+/g,"_"),Y={assisted:"assisted",辅助:"assisted",semi_automatic:"semi_automatic",半自动:"semi_automatic",fully_automatic:"fully_automatic",全自动:"fully_automatic"}[I];if(!Y)throw Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");return Y}function Ix($){let I=a0($.autoApprovalRate??$["auto-approval-rate"]??$["approval-rate"]);if(I!==void 0&&(!Number.isInteger(I)||I<0||I>100))throw Error("Webhook auto approval rate must be an integer between 0 and 100");return I}function Ux($){return _0($.showSecret)??_0($["show-secret"])}function qG($){let I=a0($.minFileSizeBytes??$["min-file-size-bytes"]??$.minFileSize??$["min-file-size"]),U=a0($.maxFileSizeBytes??$["max-file-size-bytes"]??$.maxFileSize??$["max-file-size"]),Y=W6($.allowedExtensions??$["allowed-extensions"]??$.extensions);if(I===void 0&&U===void 0&&Y===void 0)return;return{minFileSizeBytes:I,maxFileSizeBytes:U,allowedExtensions:Y}}var fq1=100,bq1=120000,Qz0=["id","code","status","strictness","scope","createdAt","updatedAt"],iq1=200000;function Yx($){return $.map((I)=>typeof I==="string"?I:String(I)).join(" ")}function GG($){if(!$.length)return"";return`${$.join(` +`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:MJ({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:ID(I,["template.name","templateName","form.name","formName","formTitle"]),amount:eL(U,["金额","报销金额","付款金额","合计","价税合计"])??ID(I,["amount","totalAmount","expenseAmount"]),expenseType:eL(U,["费用类型","费用类别","报销类型"]),costCompany:eL(U,["费用承担公司","承担公司","成本中心","费用归属"]),payee:eL(U,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:U.slice(0,30)}),invoices:Bq1($),attachments:WJ($,{summary:!0}).attachments,aiResult:YD($),manualResult:JI($)?.value,hints:MJ({amountMentions:uZ0(Y,["金额","合计","税率"],8),partyMentions:uZ0(Y,["买方","卖方","甲方","乙方","收款"],8)})}}function Aq1($){let I=[["result.citedRules",b5($,"result.citedRules")],["result.matchedRules",b5($,"result.matchedRules")],["result.ruleResults",b5($,"result.ruleResults")],["result.rules",b5($,"result.rules")],["pipelineData.citedRules",b5($,"pipelineData.citedRules")],["pipelineData.matchedRules",b5($,"pipelineData.matchedRules")]],U=[],Y=new Set;for(let[J,Q]of I)(Array.isArray(Q)?Q:Q&&typeof Q==="object"?Object.values(Q):[]).forEach((q,G)=>{let H=QG(q);if(!H)return;let W=$4(H.runtimeRuleId)??$4(H.runtimeId)??$4(H.id)??$4(H.ruleId),V=$4(H.ruleCode)??$4(H.code)??(W?Cq1(W):void 0),z=MJ({runtimeRuleId:W,ruleCode:V,versionNumber:Tq1(H.versionNumber)??$.ruleSetVersionNumber,scope:$4(H.scope),strictness:$4(H.strictness),appliedAnalysis:H.appliedAnalysis??H.analysis??H.reasoning,checkResult:H.checkResult??H.result??H.decision,findings:H.findings??H.riskPoints??H.evidence,sourcePath:`${J}.${G}`}),Z=JSON.stringify(z);if(!Y.has(Z))Y.add(Z),U.push(z)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:U.length,rules:U}}function ID($,I){if(!$)return;for(let U of I){let Y=b5($,U);if(Y!==void 0)return Y}return}function kZ0($,I){if(!$)return 0;for(let U of I){let Y=b5($,U);if(Array.isArray(Y))return Y.length;if(Y&&typeof Y==="object")return Object.keys(Y).length;if(typeof Y==="number")return Y}return 0}function b5($,I){return I.split(".").reduce((U,Y)=>{if(U===void 0||U===null)return;if(Array.isArray(U)){let J=Number(Y);return Number.isInteger(J)?U[J]:void 0}if(typeof U==="object")return U[Y];return},$)}function Pq1($,I,U){let Y=I.split("."),J=$;for(let Q of Y.slice(0,-1)){let K=J[Q];if(!K||typeof K!=="object"||Array.isArray(K))J[Q]={};J=J[Q]}J[Y[Y.length-1]??I]=U}function MJ($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function QG($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Tq1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Eq1($){let I=[];return mh($,"document",I),I}function mh($,I,U){if(Array.isArray($)){$.forEach((K,q)=>mh(K,`${I}.${q}`,U));return}let Y=QG($);if(!Y)return;let J=$4(Y.label)??$4(Y.name)??$4(Y.title)??$4(Y.fieldName),Q=Y.value??Y.displayValue??Y.text??Y.content;if(J&&Q!==void 0&&typeof Q!=="object")U.push(MJ({path:I,label:J,value:Q,type:$4(Y.type)??$4(Y.fieldType)}));for(let[K,q]of Object.entries(Y)){if(K==="attachments")continue;mh(q,`${I}.${K}`,U)}}function eL($,I){return $.find((Y)=>{let J=$4(Y.label)??"";return I.some((Q)=>J.includes(Q))})?.value}function Bq1($){let I=[];return UD($.result,"result",I),UD($.document,"document",I),I.slice(0,20)}function UD($,I,U){if(Array.isArray($)){$.forEach((J,Q)=>UD(J,`${I}.${Q}`,U));return}let Y=QG($);if(!Y)return;if(/invoice|发票/i.test(I))U.push(MJ({path:I,fileName:$4(Y.fileName)??$4(Y.filename)??$4(Y.name),buyer:Y.buyer??Y.buyerName??Y.purchaserName,seller:Y.seller??Y.sellerName,amount:Y.amount??Y.totalAmount??Y.total,taxRate:Y.taxRate,category:Y.category??Y.type}));for(let[J,Q]of Object.entries(Y))UD(Q,`${I}.${J}`,U)}function uZ0($,I,U){return $.split(/\r?\n/).filter((Y)=>I.some((J)=>Y.includes(J))).slice(0,U)}function $D($){return $.map((I)=>{let U=YI(I);return{recordId:U.id,tenantId:U.tenantId,agentId:U.agentId,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,langfuseTraceId:U.langfuseTraceId,langfuseSessionFallback:U.langfuseSessionFallback,ruleSetVersionNumber:U.ruleSetVersionNumber,ruleSetPublishedAt:U.ruleSetPublishedAt,ruleSetPublishedByName:U.ruleSetPublishedByName,resolution:U.langfuseTraceId?"trace":U.langfuseSessionFallback?"session-fallback":"unresolved"}})}function ch($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function Rq1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let U=await f4($,I.recordId);if(!U.ruleSetVersionNumber)throw Error(`Approval run ${I.recordId} has no ruleSetVersionNumber`);return lh($,{versionNumber:U.ruleSetVersionNumber})}return lh($,I)}function vq1($,I){let U=dh(I.code),Y=oZ0(I.runtimeId),J=U?Number(U.slice(1)):Y;if(!J||J<1)throw Error("Pass --code '#0038' or --runtime-id rule-205");let Q=$.rules.find((G,H)=>{let W=G;return dh($4(W.code)??$4(W.ruleCode))===U||H+1===J});if(!Q)return;let K=Q,q=$.rules.indexOf(Q)+1;return MJ({runtimeRuleId:$4(K.runtimeRuleId)??`rule-${q}`,ruleCode:dh($4(K.code)??$4(K.ruleCode))??ah(q),versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt,publishedByName:$.publishedByName,description:Q.description,scope:Q.scope,strictness:Q.strictness,status:$4(K.status)})}function dh($){if(!$)return;let I=$.match(/\d+/)?.[0];return I?ah(Number(I)):$}function oZ0($){if(!$)return;let I=$.match(/(\d+)$/);return I?Number(I[1]):void 0}function Cq1($){let I=oZ0($);return I?ah(I):void 0}function ah($){return`#${String($).padStart(4,"0")}`}function jq1($,I){let U=YI($),Y={recordId:U.id,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,status:U.status,taskMode:U.taskMode,ruleSetVersionNumber:U.ruleSetVersionNumber,langfuseTraceId:U.langfuseTraceId,manualResult:U.humanResult,aiDecision:U.aiDecision,aiSummary:U.aiSummary,createdAt:U.createdAt};if(I.length===0)return Y;return dZ0(Y,I)}async function _q1($,I){if(I.recordId)return f4($,I.recordId);let Y=(await X8($,{limit:1,search:I.sourceDocumentSN??I.sourceDocumentId,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId})).records[0];if(!Y){let J=I.sourceDocumentSN?`sourceDocumentSN ${I.sourceDocumentSN}`:`sourceDocumentId ${I.sourceDocumentId}`;throw Error(`Approval run not found for ${J}`)}return f4($,Y.id)}function Sq1($){return $.replace(/\/+$/,"")}function $4($){return typeof $==="string"&&$.trim()?$:void 0}async function gq1($,I){let U=Math.min(100,Math.max(I.limit,20)),Y=[],J,Q=0;while(Q!I.sn||G.sourceDocumentSN===I.sn).filter((G)=>!I.batchId||G.sourceExtendData?.simulation_batch_id===I.batchId);if(Y.push(...q),K.records.length===0||J!==void 0&&Q>=J)break}return Y.sort((K,q)=>fZ0(q.createdAt)-fZ0(K.createdAt)),{total:J,scanned:Q,records:Y.slice(0,I.latest?1:I.limit)}}function fZ0($){if(typeof $==="number")return $;if(typeof $==="string"){let I=Date.parse($);return Number.isFinite(I)?I:0}return 0}async function lh($,I){if(I.versionId)return W2($,I.versionId);let U=await Y5($),Y=I.versionNumber?U.find((J)=>J.versionNumber===I.versionNumber):U[0];if(!Y)throw Error(I.versionNumber?`Rule version not found: ${I.versionNumber}`:"No rule versions found");return Y}function sh($,I){let U=I?.trim().toLowerCase();if(!U)return $;return $.filter((Y)=>{return[Y.id,Y.sourceDocumentSN,Y.sourceDocumentId,Y.documentId,Y.sourceExtendData?._langfuseTraceId,Y.sourceExtendData?.simulation_batch_id,Y.status,Y.taskMode,Y.finalExecutionMode,Y.sourceSystem,Y.ruleSetVersionNumber,Y.ruleSetPublishedByName].some((Q)=>oh(Q,U))||rh(Y,U)})}function oh($,I){if($===null||$===void 0)return!1;if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return String($).toLowerCase().includes(I);return!1}function rh($,I,U=0){if(U>6)return!1;if(oh($,I))return!0;if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some((Y)=>rh(Y,I,U+1));return Object.entries($).some(([Y,J])=>oh(Y,I)||rh(J,I,U+1))}function yq1($,I){let U=I?.trim().toLowerCase();if(!U)return $;return $.filter((Y)=>JI(Y)?.value.toLowerCase().includes(U))}function hq1($){return{...$,manualApprovalStatus:rZ0($.manualApprovalStatus,$.humanResult)}}function rZ0($,I){if($)return $;let U=I?.trim().toLowerCase();if(!U)return;if(["驳回","已驳回","拒绝","不通过","terminated","reject","rejected","denied"].includes(U))return"TERMINATED";return}async function bZ0($,I,U){let Y=sh(I,U.query);if(!U.humanResult?.trim())return Y;let J=await Promise.all(Y.map(async(Q)=>{if(JI(Q))return Q;try{return await f4($,Q.id)}catch{return Q}}));return yq1(J,U.humanResult)}function xq1($){return{originalDocumentData:{path:"document",frontendLabel:"单据原始数据",description:"前端详情页展示的单据原始数据对象",id:$.document?.id??$.documentId,sourceDocumentSN:$.document?.sourceDocumentSN??$.sourceDocumentSN,sourceDocumentId:$.document?.sourceDocumentId??$.sourceDocumentId},aiDocumentFields:{path:"document.fields",frontendLabel:"AI 看的单据",description:"AI 审核实际读取的字段数组,即单据原始数据中的 fields",fieldCount:$.document?.fields?.length},aiDocument:{path:"document.fields",frontendLabel:"AI 看的单据",description:"兼容别名,等同于 aiDocumentFields",aliasOf:"aiDocumentFields",fieldCount:$.document?.fields?.length},sourceDocument:{path:"sourceExtendData.hosecloudViewUrl",description:"合思原始单据入口;详情响应中只有入口和源单据 ID,不包含完整原始单据 JSON",sourceSystem:$.sourceSystem,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,originalDocumentId:$.sourceExtendData?.original_document_id,viewUrl:$.sourceExtendData?.hosecloudViewUrl},aiResult:{path:"result",description:"AI 最终审核结构化结果"},aiAuditLog:{path:"pipelineData.logs",description:"AI 审核过程日志"},manualApproval:{path:"manualApprovalRecord",description:"人工审核结果、节点和驳回原因"}}}function JI($){let I=[["result",$.result],["pipelineData",$.pipelineData]];for(let[U,Y]of I){let J=th(Y,U);if(J)return J}return}function th($,I,U=0){if(U>8||$===null||$===void 0)return;if(Array.isArray($)){for(let Y=0;Y<$.length;Y+=1){let J=th($[Y],`${I}[${Y}]`,U+1);if(J)return J}return}if(typeof $!=="object")return;for(let[Y,J]of Object.entries($)){let Q=`${I}.${Y}`,K=th(J,Q,U+1);if(K)return K;if(iZ0(Y)||iZ0(Q)){let q=tZ0(J);if(q)return{value:q,path:Q}}}return}function iZ0($){let I=$.toLowerCase(),U=I.includes("human")||I.includes("manual")||I.includes("reviewer")||I.includes("operator")||$.includes("人工")||$.includes("人工审批")||$.includes("人工审核"),Y=I.includes("result")||I.includes("decision")||I.includes("outcome")||I.includes("conclusion")||I.includes("action")||$.includes("结果")||$.includes("结论")||$.includes("动作");return U&&Y}function tZ0($){if(typeof $==="string")return $.trim()||void 0;if(typeof $==="number"||typeof $==="boolean")return String($);if(!$||typeof $!=="object")return;let I=$;for(let U of["label","name","text","value","result","decision","outcome","status","action"]){let Y=tZ0(I[U]);if(Y)return Y}return}function kq1($,I){if(I.recordId&&$.id!==I.recordId)return!1;if(I.sourceDocumentSN&&$.sourceDocumentSN!==I.sourceDocumentSN)return!1;if(I.sourceDocumentId&&$.sourceDocumentId!==I.sourceDocumentId)return!1;return!0}function nZ0($,I){return $.reduce((U,Y)=>{let J=I(Y);return U[J]=(U[J]??0)+1,U},{})}function pZ0($,I){let U=aZ0($);if(!U)return;let Y=sZ0(U,I),J=Y.year,Q=(Y.month??"01").padStart(2,"0"),K=(Y.day??"01").padStart(2,"0");return`${J}-${Q}-${K}`}function cZ0($,I){let U=aZ0($);if(!U)return;let Y=sZ0(U,I),J=(Y.month??"01").padStart(2,"0"),Q=(Y.day??"01").padStart(2,"0"),K=(Y.hour??"00").padStart(2,"0"),q=(Y.minute??"00").padStart(2,"0"),G=(Y.second??"00").padStart(2,"0");return`${Y.year??"0000"}-${J}-${Q} ${K}:${q}:${G}`}function aZ0($){if($===void 0)return null;let I=new Date($);return Number.isNaN(I.getTime())?null:I}function sZ0($,I){return Object.fromEntries(new Intl.DateTimeFormat("en-CA",{timeZone:I,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts($).filter((U)=>U.type!=="literal").map((U)=>[U.type,U.value]))}import{writeFileSync as uq1}from"node:fs";function eZ0($){let I=[],U={},Y;for(let J=0;J<$.length;J+=1){let Q=$[J];if(!Q)continue;if(Q==="--json"){let K=$[J+1];if(!K)throw Error("--json requires a JSON object argument");Y=JSON.parse(K),J+=1;continue}if(Q.startsWith("-")){let K=Q.replace(/^-+/,"");if(K.includes("=")){let G=K.indexOf("="),H=K.slice(0,G),W=K.slice(G+1);U[H]=W;continue}let q=$[J+1];if(!q||q.startsWith("-"))U[K]=!0;else U[K]=q,J+=1;continue}I.push(Q)}return{command:I,options:U,json:Y}}function t6($){if($===void 0)return{};if(!$||typeof $!=="object"||Array.isArray($))throw Error("--json must be an object");return $}function h($){return typeof $==="string"?$:void 0}function a0($){if(typeof $!=="string")return;let I=Number($);if(!Number.isFinite(I))throw Error(`Invalid number: ${$}`);return I}function W6($){if(typeof $!=="string")return;let I=$.split(",").map((U)=>U.trim()).filter(Boolean);return I.length?I:void 0}function _0($){if($===void 0)return;if(typeof $==="boolean")return $;if($==="true")return!0;if($==="false")return!1;throw Error(`Invalid boolean: ${$}`)}function z7($,I){let U=i1($,I);if(!U)throw Error(`Missing required JSON field: ${I}`);return U}function i1($,I){let U=$[I];return typeof U==="string"&&U.trim()?U.trim():void 0}function $z0($,I){let U=$[I];return typeof U==="number"&&Number.isFinite(U)?U:void 0}function eh($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function Iz0($){let I=$.trim().toLowerCase();if(["stateful","state","有状态"].includes(I))return!0;if(["stateless","无状态"].includes(I))return!1;throw Error("Invalid config mode. Use stateful or stateless.")}function KG($){if($==="latest")return{latest:!0};let I=Number($);if(Number.isInteger(I)&&I>0)return{versionNumber:I};return{versionId:$}}function Uz0($){if(!$)return{};let I=KG($);if("latest"in I)return{ruleVersionScope:"version",latestRuleVersion:!0};if("versionNumber"in I)return{ruleVersionScope:"version",ruleVersionNumber:I.versionNumber};return{ruleVersionScope:"version",ruleVersionId:I.versionId}}function Yz0($){if(!$)return{};let I=KG($);if("latest"in I)return{latestRuleVersion:!0};if("versionNumber"in I)return{ruleVersionNumber:I.versionNumber};return{ruleVersionId:I.versionId}}function Jz0($){if(!$)return{};let I=KG($);if("latest"in I)return{latest:!0};if("versionNumber"in I)return{versionNumber:I.versionNumber};return{versionId:I.versionId}}function $x($){if(!$)return;let I=$.trim().toLowerCase().replace(/[\s-]+/g,"_"),Y={assisted:"assisted",辅助:"assisted",semi_automatic:"semi_automatic",半自动:"semi_automatic",fully_automatic:"fully_automatic",全自动:"fully_automatic"}[I];if(!Y)throw Error("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic");return Y}function Ix($){let I=a0($.autoApprovalRate??$["auto-approval-rate"]??$["approval-rate"]);if(I!==void 0&&(!Number.isInteger(I)||I<0||I>100))throw Error("Webhook auto approval rate must be an integer between 0 and 100");return I}function Ux($){return _0($.showSecret)??_0($["show-secret"])}function qG($){let I=_0($.clearMaxFileSize??$["clear-max-file-size"])===!0,U=a0($.minFileSizeBytes??$["min-file-size-bytes"]??$.minFileSize??$["min-file-size"]),Y=a0($.maxFileSizeBytes??$["max-file-size-bytes"]??$.maxFileSize??$["max-file-size"]),J=W6($.allowedExtensions??$["allowed-extensions"]??$.extensions);if(U===void 0&&Y===void 0&&J===void 0&&!I)return;return{minFileSizeBytes:U,maxFileSizeBytes:I?null:Y,allowedExtensions:J}}var fq1=100,bq1=120000,Qz0=["id","code","status","strictness","scope","createdAt","updatedAt"],iq1=200000;function Yx($){return $.map((I)=>typeof I==="string"?I:String(I)).join(" ")}function GG($){if(!$.length)return"";return`${$.join(` `)} `}function HG($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1")}function E0($,I={}){nq1($,I);let U=`${JSON.stringify($,null,2)} `;if(I.outputFile){uq1(I.outputFile,U),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function nq1($,I={}){if(I.allowFull||I.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>iq1)throw Error(`Output is large (${U} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function Kz0($,I){if(I)return;let U=$&&typeof $==="object"?$:{},Y=typeof U.count==="number"?U.count:void 0,J=Array.isArray(U.rules)?U.rules.length:void 0,Q=Buffer.byteLength(JSON.stringify($),"utf-8"),K=Y??J??0;if(K>fq1||Q>bq1)throw Error(`Rule list is large (${K} rules, ${Q} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`)}function D0($){return{allowFull:_0($.full)===!0,outputFile:h($.outputFile)??h($["output-file"])}}function qz0(){console.log(`seal-use CLI @@ -371,7 +371,7 @@ Usage: seal-use webhook list [--query ] [--show-secret] [--corp ] seal-use webhook get|find [--show-secret] [--corp ] seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size 500] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] - seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] + seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ] seal-use webhook delete --yes [--corp ] seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook ] [--corp ] @@ -550,12 +550,27 @@ seal-use corps list - System Permissions Config: \`seal-use permissions available --corp \`, \`seal-use permissions configs --corp \`. - Billing & Feature Quotas: \`seal-use billing status --corp \`, \`seal-use billing plans --corp \`, \`seal-use billing features --corp \`. - Webhook 准备看板与审批回调管理: \`seal-use webhook ready [<材料包.zip>] [--webhook ] --corp \` (别名 \`status\`) 检查企业环境、租户连通性、已激活通道与材料包预检;\`seal-use webhook --corp \`. -- Webhook 材料包导入: \`seal-use webhook material-pack preview <材料包.zip> --corp \` 只做本地校验和解析(无网络请求);\`... push <材料包.zip> [--webhook ] --corp \` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 \`--webhook\`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = \`documentId\`(或 \`documentId@annotation\`),Excel 附件列以 \`[附件]\` 为前缀(如 \`[附件]合同协议\`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 \`[附件]\` 列中声明)。详见 \`references/cli.md\` 中 "Material Pack Workflow" 一节。它与 \`simulation material_pack\` 的官方服务端导入流程相互独立。 +- Webhook 材料包导入: \`seal-use webhook material-pack preview <材料包.zip> --corp \` 只做本地校验和解析(无网络请求);\`... push <材料包.zip> [--webhook ] --corp \` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 \`--webhook\`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = \`documentId\`(或 \`documentId@annotation\`),Excel 附件列以 \`[附件]\` 为前缀(如 \`[附件]合同协议\`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 \`[附件]\` 列中声明)。详见 \`references/cli.md\` 中 "Material Pack Workflow" 一节。它与 \`simulation material_pack\` 的官方服务端导入流程相互独立。 - HTTP REST API & Docs Server: \`seal-use http [--port 8787] [--host 127.0.0.1]\` (提供 \`/docs\` 交互文档、\`/openapi.json\`、\`POST /api/cli\` 与 \`/v1/*\` REST API)。 - 审批规则质量校验 (Linter): \`seal-use rules lint [--linter ] [--version ] [--code ] [--min-score ] [--summary] --corp \`; read \`references/rule-lint.md\`. 全局配置默认关闭 (\`config lint \`)。 - Full CLI inventory: read \`references/cli.md\`. +## Material-pack Webhook policy and recovery + +材料包附件策略保存在目标入站 Webhook 的 \`materialPackFilePolicy\` 下,按 Webhook 生效。新建 Webhook 的默认策略是:最小文件大小 \`500\` 字节、最大文件大小不限制、后缀白名单为常见 PDF/Office/文本/邮件/图片格式。\`信息表.xlsx\` 是材料包根清单,不属于普通附件,不受这三个附件策略限制。完整默认后缀和边界规则见 \`references/cli.md\`。 + +这套策略允许人工或助手修改。错误处理有两条通道:先通过错误通道明确告诉助手是哪一个文件、哪一条规则失败;再通过配置或文件处置通道完成恢复。遇到附件被拦截时按以下闭环处理: + +1. 从错误中识别被拦截的文件、实际大小、失败规则和目标 Webhook。 +2. 向用户说明可选处置:替换/压缩文件,或在确认允许该格式/大小后修改 Webhook 策略。 +3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置(CLI 使用 \`webhook get\`/\`webhook list\`,MCP 使用 \`seal_webhook_get\`/\`seal_webhook_list\`)。 +4. 调用 \`seal_webhook_update\` 或 \`seal-use webhook update\` 修改最小值、最大值或完整后缀白名单,写入后重新读取核对,再重试原来的材料包 push。 + +push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 \`stderr\` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。 + +注意:直接执行本地 \`material-pack preview\` 只使用默认策略或命令行临时覆盖,不会自动读取某个 Webhook 的持久化策略;\`webhook ready --file\`(指定 Webhook 时)和 \`material-pack push\` 才使用保存的 Webhook 策略。需要验证实际入站通道策略时,优先使用 \`ready --file --webhook ...\`,或直接重试 push。 + ## High-Value Commands \`\`\`bash @@ -770,7 +785,7 @@ Important nuance: - This is a bad-case pattern, not a general rule that every amount-total dispute is caused by \`pre_analysis\`. - Use it when the current trace shows recognized amounts being excluded downstream or duplicate attachments producing inconsistent conclusions. -`;var oz0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use \n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp ` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp \nseal-use corps switch \nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).\n- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode [--corp ]\nseal-use config test-dir [|--clear]\nseal-use config lint [--linter ] [--min-score ]\nseal-use rules pull [--corp ] [--version ] [--out ]\nseal-use rules lint [--file ] [--corp ] [--linter ] [--version ] [--code ] [--min-score ] [--summary]\nseal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]\nseal-use service [--port 8787] [--host 127.0.0.1] [--lines 50]\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp ]\nseal-use corps current [--corp ]\nseal-use corps switch \nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link [--name ] [--overwrite]\nseal-use auth diagnose [--corp ]\nseal-use auth hose-link [--corp ] [--expire 7200]\nseal-use delegation list [--corp ]\nseal-use delegation create [--note ] [--from-link ] [--corp ]\nseal-use delegation revoke [--corp ]\nseal-use users create --name --phone [--dept ] [--corp ]\nseal-use users reset-password [--corp ]\nseal-use users get [--corp ]\nseal-use users delete [--corp ]\nseal-use llm config [--corp ]\nseal-use llm providers [--corp ]\nseal-use permissions available [--corp ]\nseal-use permissions configs [--corp ]\nseal-use billing status [--corp ]\nseal-use billing plans [--corp ]\nseal-use billing features [--corp ]\nseal-use webhook list [--query ] [--show-secret] [--corp ]\nseal-use webhook get|find [--show-secret] [--corp ]\nseal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ]\nseal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ]\nseal-use webhook delete --yes [--corp ]\nseal-use deploy hosecloud requirements [--corp ]\nseal-use deploy hosecloud list [--corp ]\nseal-use deploy hosecloud get [] [--corp ]\nseal-use deploy hosecloud status [--corp ]\nseal-use deploy hosecloud configure --json '{...}' [--corp ]\nseal-use deploy hosecloud sync [] [--auto] [--corp ]\nseal-use preference get [--corp ]\nseal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--corp ]\nseal-use preference thinking-depth set --default [--corp ]\nseal-use preference thinking-depth policies list [--corp ]\nseal-use preference thinking-depth policies upsert --json '{...}' [--corp ]\nseal-use preference thinking-depth policies remove [--corp ]\nseal-use source config [--corp ]\nseal-use tool [--corp ] [--json '{\"key\":\"value\"}']\nseal-use approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai]\nseal-use approval-runs stats --corp [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]\nseal-use approval-runs count --corp [--status APPROVED]\nseal-use approval-runs export --corp [--start ] [--end ] [--limit ] [--downloads] [--out ]\nseal-use approval-runs search --corp [--query text] [--limit 20] [--includeBridge true]\nseal-use approval-runs get --corp [--fields metadata|document.fields,result.summary] [--output-file file.json]\nseal-use approval-runs attachments --corp \nseal-use approval-runs attachments download [--all] [--name ] [--out-dir ] --corp \nseal-use approval-runs result --corp [--summary]\nseal-use approval-runs url --corp \nseal-use approval-runs url --corp \nseal-use approval-runs url --sourceDocumentSN --corp \nseal-use approval-runs bridge --corp [--sourceDocumentSN ]\nseal-use simulation batch-records --corp \nseal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp \nseal-use simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp \nseal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" --corp \nseal-use simulation wait [--timeout 10m] [--poll-interval 2s] --corp \nseal-use simulation clean --corp \nseal-use simulation specifications [--integration ] --corp \nseal-use simulation list [--limit 50] --corp \nseal-use simulation get --corp \nseal-use simulation templates --corp \nseal-use simulation integrations --corp \nseal-use simulation package-upload <材料包.zip> --corp \n```\n\n## CLI Command Overview\n\n`seal-use version` returns:\n\n```json\n{\n \"name\": \"seal-use\",\n \"version\": \"\"\n}\n```\n\n`seal-use service ` manages the persistent background service daemon with embedded HTTP server (serving `/docs`, `/openapi.json`, and `POST /api/cli`). `status` returns the PID, version, host, port, active HTTP URL, state directory, PID file, and log file.\n\n`seal-use update` updates the git checkout, runs `bun install`, and restarts the local service if it was running.\n\nIdentity and session:\n\n- `seal-use auth diagnose --corp `\n- `seal-use corps list`\n- `seal-use corps current`\n\nApproval rule maintenance:\n\n- `seal-use rules count [--corp ]`\n- `seal-use rules list --summary [--corp ]`\n- `seal-use rules pull [--corp ] [--version ] [--out ]`\n- `seal-use rules lint [--file ] [--corp ] [--linter ] [--version ] [--code ] [--min-score ] [--summary]`\n- `seal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]`\n- `seal-use rules clear [--corp ] [--dry-run|--yes]`\n\nApproval run lightweight queries:\n\n- `seal-use approval-runs get --corp --fields metadata`\n- `seal-use approval-runs get --corp --summary`\n- `seal-use approval-runs pick --corp --sn <单号> --batch --latest`\n- `seal-use approval-runs document-summary --corp `\n- `seal-use approval-runs cited-rules --corp `\n- `seal-use approval-runs get --corp --fields document.fields,result.summary`\n- `seal-use approval-runs attachments --corp --summary`\n- `seal-use approval-runs attachments download [--all] [--name ] [--out-dir ] --corp `\n- `seal-use approval-runs result --corp --summary`\n\nApproval knowledge documents & style:\n\n- `seal-use rules get --corp --version --code '#0038'`\n- `seal-use rules get --corp --record-id --runtime-id rule-205`\n\nWebhook integrations:\n\n- `seal-use webhook ready [<材料包.zip|信息表.xlsx>] [--webhook ] [--corp ]`\n- `seal-use webhook status [<材料包.zip|信息表.xlsx>] [--corp ]`\n- `seal-use webhook list [--query ] [--show-secret] [--corp ]`\n- `seal-use webhook get|find [--show-secret] [--corp ]`\n- `seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ]`\n- `seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ]`\n- `seal-use webhook delete --yes [--corp ]`\n- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] --corp `\n- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook ] --corp `\n\nWebhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`.\n\nApproval runs, simulations, and Langfuse bridge:\n\n- `seal-use approval-runs search --corp [--query ] [--limit 20]`\n- `seal-use approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai]`\n- `seal-use approval-runs bridge --corp [--sourceDocumentSN ]`\n- `seal-use simulation create --mode hosecloud --flow-ids ... --corp `\n- `seal-use simulation wait --corp `\n- `seal-use simulation clean --corp `\n- `seal-use simulation list --corp `\n- `seal-use simulation get --corp `\n- `seal-use simulation batch-records --corp `\n- `seal-use simulation templates --corp `\n- `seal-use simulation integrations --corp `\n\n## Common Examples\n\nAdd and verify a Hose enterprise:\n\n```bash\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use auth diagnose --corp \n```\n\nForce-write a Hose config without verification:\n\n```bash\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\",\"force\":true}'\n```\n\nDiagnose auth failures:\n\n```bash\nseal-use auth diagnose --corp \n```\n\nThe diagnostic stages are `hose.openapi`, `hose.provisional`, `seal.sso`, and `seal.whoami`. Tokens are omitted from output.\n\nSearch approval content:\n\n```bash\nseal-use tool seal_approval_search --corp --json '{\"keywords\":[\"关键词\"],\"matchMode\":\"any\",\"maxResults\":20}'\n```\n\nGet aggregated approval context:\n\n```bash\nseal-use tool seal_approval_context_get --corp --json '{\"documentLimit\":20}'\n```\n\nCreate a draft approval rule:\n\n```bash\nseal-use tool seal_approval_rule_create --corp --json '{\"description\":\"规则描述\",\"scope\":\"适用场景\",\"strictness\":\"SHOULD_FOLLOW\"}'\n```\n\nUpdate an approval document:\n\n```bash\nseal-use tool seal_approval_document_update --corp --json '{\"documentId\":\"doc-id\",\"content\":\"Markdown 内容\"}'\n```\n\nSummarize one local date:\n\n```bash\nseal-use approval-runs summary --corp --date 2026-06-09 --timezone Asia/Shanghai --limit 100\n```\n\nFind a run and include Langfuse bridge rows:\n\n```bash\nseal-use approval-runs search --corp --query --limit 20 --includeBridge true\n```\n\nResolve Langfuse trace/session hints:\n\n```bash\nseal-use approval-runs bridge --corp --sourceDocumentSN \n```\n\n模拟测试批次(模拟发布闭环)创建与查询:\n\n```bash\n# 合思指定单号: 创建批次(响应只含 batchId)\nseal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" --reject-node 财务 --thinking-depth medium --skip-invoice-generation --corp \n# 材料包导入: 先上传材料包 ZIP(服务端解析并返回 schemaConfig), 再用返回的 id 发起\nseal-use simulation package-upload 测试材料包.zip --corp \nseal-use simulation create --mode material_pack --package-ids --template-id conference_reimbursement_v1 --schema-config schema.json --corp \n# 预留: 其他模式参数通过 --json 透传(如时间范围 startTime/endTime)\nseal-use simulation create --mode hosecloud --flow-ids \"B26017701\" --json '{\"startTime\":0,\"endTime\":0}' --corp \n# 创建后轮询批次状态与记录\nseal-use simulation list --limit 50 --corp \nseal-use simulation get --corp \nseal-use simulation batch-records --corp \nseal-use simulation templates --corp \nseal-use simulation integrations --corp \n```\n\n## Write Operation Payloads\n\nCreate a rule:\n\n```json\n{\n \"description\": \"规则描述\",\n \"scope\": \"适用场景\",\n \"strictness\": \"MUST_FOLLOW | SHOULD_FOLLOW | SUGGESTION\"\n}\n```\n\nUpdate a rule:\n\n```json\n{\n \"ruleId\": \"rule-id\",\n \"description\": \"可选\",\n \"scope\": \"可选\",\n \"strictness\": \"SHOULD_FOLLOW\"\n}\n```\n\nPublish a rule version:\n\n```json\n{\n \"versionName\": \"版本名称\"\n}\n```\n\nCreate a document:\n\n```json\n{\n \"title\": \"标题\",\n \"purpose\": \"用途\",\n \"content\": \"Markdown 内容\",\n \"contentType\": \"text/markdown\",\n \"status\": \"可选\",\n \"scenarios\": [\"场景\"],\n \"tags\": [\"标签\"]\n}\n```\n\nUpdate a document:\n\n```json\n{\n \"documentId\": \"doc-id\",\n \"title\": \"可选\",\n \"purpose\": \"可选\",\n \"content\": \"可选\",\n \"enabled\": true,\n \"scenarios\": [\"可选\"],\n \"tags\": [\"可选\"]\n}\n```\n\nUpdate style preferences:\n\n```json\n{\n \"tone\": \"可选\",\n \"language\": \"可选\",\n \"detailLevel\": \"可选\",\n \"outputFormat\": \"可选\",\n \"examples\": [\"可选\"],\n \"prohibitedPhrases\": [\"可选\"],\n \"customInstructions\": \"可选\"\n}\n```\n\n## Material Pack Workflow\n\nA **material pack** (材料包) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is the primary input to the Webhook-based AI approval ingestion pipeline.\n\n### ZIP structure convention\n\n```\n材料包.zip\n├── 信息表.xlsx ← must exist at ZIP root\n├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)\n│ ├── 合同协议/\n│ │ └── 采购合同.pdf\n│ └── 支付凭证/\n│ └── 支付宝交易明细.pdf\n└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId\n └── 发票/\n └── 增值税专用发票.pdf\n```\n\n- The root directory name **must equal** the `documentId` **OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).\n- `信息表.xlsx` at the ZIP root is the only file not associated with any document directory.\n\n### Excel column convention\n\n| Column type | Naming | Purpose |\n|---|---|---|\n| Regular column | Any header (e.g. `会议编号`, `总金额`) | Standard document fields |\n| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`) | Declares attached files for this row |\n\n- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.\n- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).\n- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`\n\n### Sheet → document level mapping\n\n| Excel sheet | Maps to |\n|---|---|\n| First sheet (main / 会议) | Root document `categoryFields` |\n| 费用明细表 (has `报销金额` column) | Per-row entries in `mingxi_list` |\n| 劳务明细 (has `姓名` column) | Per-person entries in `daoshi_list` |\n\n### Strict bidirectional validation\n\nBefore pushing or previewing, the system enforces:\n\n1. **Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: `\n2. **ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: `\n3. **Document Directory Scope Isolation**: All attachments declared for a document `DOC_X` **must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: 。附件必须位于该单据自己的根目录...`\n4. **Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire material pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「」被重复声明了 N 次...`\n5. **Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`\n6. **documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet must have a matching ZIP root dir (exact match or `documentId@annotation`). Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`\n\nAll validation errors are collected and reported together in a single `MaterialPackValidationError`.\n\n### CLI usage\n\n```bash\n# Check environment readiness and optionally pre-validate the material pack\nseal-use webhook ready [--file ] [--corp ]\n\n# Dry-run: local parse & validation only, no network calls, returns preview JSON\nseal-use webhook material-pack preview --corp \n# Preview with temporary local policy overrides (comma-separated extensions)\nseal-use webhook material-pack preview --min-file-size 500 --max-file-size 20971520 --allowed-extensions .pdf,.xlsx,.docx --corp \n\n# Upload attachments and push documents via inbound Webhook\nseal-use webhook material-pack push [--webhook ] --corp \n# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)\n```\n\n### Attachment file policy configuration\n\nThe policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow.\n\n```bash\n# New Webhook: use the default 500-byte minimum and default extension whitelist\nseal-use webhook add --name \"材料包入站\" --result-url \"https://your-domain.com/callback\" --corp \n\n# Configure an existing Webhook; sizes are bytes and extensions are comma-separated\nseal-use webhook update \\\n --min-file-size 500 \\\n --max-file-size 20971520 \\\n --allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png \\\n --corp \n```\n\nThe saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.\n\n### Error messages reference\n\n| Error message | Meaning | Fix |\n|---|---|---|\n| `Excel 声明的附件路径在 ZIP 中不存在: ` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |\n| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: ` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |\n| `单据「X」声明了跨单据或非本单据目录的附件路径: ` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |\n| `附件路径「」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |\n| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |\n| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |\n| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |\n| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |\n| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |\n| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |\n| `附件上传失败 ` | Network/server error during file upload | Check webhook URL, secret, and server availability |\n\n## Failure Handling\n\n- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use `seal-use service restart` after updates so the optional local service picks up new code.\n- If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`.\n- If date-based summaries look wrong, pass `--timezone Asia/Shanghai` and an explicit `--date`.\n- If `langfuseTraceId` is missing, use `langfuseSessionFallback`.\n- If a write operation fails, report the raw JSON error and do not retry with guessed payloads.\n";var rz0="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-use approval-runs pick --corp --sn --latest\nseal-use approval-runs pick --corp --sn --batch --latest\nseal-use approval-runs pick --corp --sn --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-use approval-runs get --corp --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-use approval-runs get --corp --fields metadata\nseal-use approval-runs get --corp --fields document.fields,result.summary\nseal-use approval-runs get --corp --fields result.summary,result.decision,result.riskPoints\nseal-use approval-runs get --corp --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get ` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-use approval-runs document-summary --corp \n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-use approval-runs cited-rules --corp \n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n# 查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-use approval-runs attachments --corp --summary\n\n# 下载全部附件到本地目录(优先使用 ossSignedUrl 签名直链)\nseal-use approval-runs attachments download --all --out-dir ./downloads --corp \n\n# 按名称或 fileId 过滤下载单个附件\nseal-use approval-runs attachments download --name 发票 --corp \n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-use approval-runs result --corp --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n";var tz0=`# Approval Attachment Trace Investigation +`;var oz0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use \n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp ` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp \nseal-use corps switch \nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).\n- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode [--corp ]\nseal-use config test-dir [|--clear]\nseal-use config lint [--linter ] [--min-score ]\nseal-use rules pull [--corp ] [--version ] [--out ]\nseal-use rules lint [--file ] [--corp ] [--linter ] [--version ] [--code ] [--min-score ] [--summary]\nseal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]\nseal-use service [--port 8787] [--host 127.0.0.1] [--lines 50]\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp ]\nseal-use corps current [--corp ]\nseal-use corps switch \nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link [--name ] [--overwrite]\nseal-use auth diagnose [--corp ]\nseal-use auth hose-link [--corp ] [--expire 7200]\nseal-use delegation list [--corp ]\nseal-use delegation create [--note ] [--from-link ] [--corp ]\nseal-use delegation revoke [--corp ]\nseal-use users create --name --phone [--dept ] [--corp ]\nseal-use users reset-password [--corp ]\nseal-use users get [--corp ]\nseal-use users delete [--corp ]\nseal-use llm config [--corp ]\nseal-use llm providers [--corp ]\nseal-use permissions available [--corp ]\nseal-use permissions configs [--corp ]\nseal-use billing status [--corp ]\nseal-use billing plans [--corp ]\nseal-use billing features [--corp ]\nseal-use webhook list [--query ] [--show-secret] [--corp ]\nseal-use webhook get|find [--show-secret] [--corp ]\nseal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ]\nseal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ]\nseal-use webhook delete --yes [--corp ]\nseal-use deploy hosecloud requirements [--corp ]\nseal-use deploy hosecloud list [--corp ]\nseal-use deploy hosecloud get [] [--corp ]\nseal-use deploy hosecloud status [--corp ]\nseal-use deploy hosecloud configure --json '{...}' [--corp ]\nseal-use deploy hosecloud sync [] [--auto] [--corp ]\nseal-use preference get [--corp ]\nseal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--corp ]\nseal-use preference thinking-depth set --default [--corp ]\nseal-use preference thinking-depth policies list [--corp ]\nseal-use preference thinking-depth policies upsert --json '{...}' [--corp ]\nseal-use preference thinking-depth policies remove [--corp ]\nseal-use source config [--corp ]\nseal-use tool [--corp ] [--json '{\"key\":\"value\"}']\nseal-use approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai]\nseal-use approval-runs stats --corp [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]\nseal-use approval-runs count --corp [--status APPROVED]\nseal-use approval-runs export --corp [--start ] [--end ] [--limit ] [--downloads] [--out ]\nseal-use approval-runs search --corp [--query text] [--limit 20] [--includeBridge true]\nseal-use approval-runs get --corp [--fields metadata|document.fields,result.summary] [--output-file file.json]\nseal-use approval-runs attachments --corp \nseal-use approval-runs attachments download [--all] [--name ] [--out-dir ] --corp \nseal-use approval-runs result --corp [--summary]\nseal-use approval-runs url --corp \nseal-use approval-runs url --corp \nseal-use approval-runs url --sourceDocumentSN --corp \nseal-use approval-runs bridge --corp [--sourceDocumentSN ]\nseal-use simulation batch-records --corp \nseal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp \nseal-use simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp \nseal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" --corp \nseal-use simulation wait [--timeout 10m] [--poll-interval 2s] --corp \nseal-use simulation clean --corp \nseal-use simulation specifications [--integration ] --corp \nseal-use simulation list [--limit 50] --corp \nseal-use simulation get --corp \nseal-use simulation templates --corp \nseal-use simulation integrations --corp \nseal-use simulation package-upload <材料包.zip> --corp \n```\n\n## CLI Command Overview\n\n`seal-use version` returns:\n\n```json\n{\n \"name\": \"seal-use\",\n \"version\": \"\"\n}\n```\n\n`seal-use service ` manages the persistent background service daemon with embedded HTTP server (serving `/docs`, `/openapi.json`, and `POST /api/cli`). `status` returns the PID, version, host, port, active HTTP URL, state directory, PID file, and log file.\n\n`seal-use update` updates the git checkout, runs `bun install`, and restarts the local service if it was running.\n\nIdentity and session:\n\n- `seal-use auth diagnose --corp `\n- `seal-use corps list`\n- `seal-use corps current`\n\nApproval rule maintenance:\n\n- `seal-use rules count [--corp ]`\n- `seal-use rules list --summary [--corp ]`\n- `seal-use rules pull [--corp ] [--version ] [--out ]`\n- `seal-use rules lint [--file ] [--corp ] [--linter ] [--version ] [--code ] [--min-score ] [--summary]`\n- `seal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]`\n- `seal-use rules clear [--corp ] [--dry-run|--yes]`\n\nApproval run lightweight queries:\n\n- `seal-use approval-runs get --corp --fields metadata`\n- `seal-use approval-runs get --corp --summary`\n- `seal-use approval-runs pick --corp --sn <单号> --batch --latest`\n- `seal-use approval-runs document-summary --corp `\n- `seal-use approval-runs cited-rules --corp `\n- `seal-use approval-runs get --corp --fields document.fields,result.summary`\n- `seal-use approval-runs attachments --corp --summary`\n- `seal-use approval-runs attachments download [--all] [--name ] [--out-dir ] --corp `\n- `seal-use approval-runs result --corp --summary`\n\nApproval knowledge documents & style:\n\n- `seal-use rules get --corp --version --code '#0038'`\n- `seal-use rules get --corp --record-id --runtime-id rule-205`\n\nWebhook integrations:\n\n- `seal-use webhook ready [<材料包.zip|信息表.xlsx>] [--webhook ] [--corp ]`\n- `seal-use webhook status [<材料包.zip|信息表.xlsx>] [--corp ]`\n- `seal-use webhook list [--query ] [--show-secret] [--corp ]`\n- `seal-use webhook get|find [--show-secret] [--corp ]`\n- `seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ]`\n- `seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ]`\n- `seal-use webhook delete --yes [--corp ]`\n- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] --corp `\n- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook ] --corp `\n\nWebhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound.\n\nApproval runs, simulations, and Langfuse bridge:\n\n- `seal-use approval-runs search --corp [--query ] [--limit 20]`\n- `seal-use approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai]`\n- `seal-use approval-runs bridge --corp [--sourceDocumentSN ]`\n- `seal-use simulation create --mode hosecloud --flow-ids ... --corp `\n- `seal-use simulation wait --corp `\n- `seal-use simulation clean --corp `\n- `seal-use simulation list --corp `\n- `seal-use simulation get --corp `\n- `seal-use simulation batch-records --corp `\n- `seal-use simulation templates --corp `\n- `seal-use simulation integrations --corp `\n\n## Common Examples\n\nAdd and verify a Hose enterprise:\n\n```bash\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use auth diagnose --corp \n```\n\nForce-write a Hose config without verification:\n\n```bash\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\",\"force\":true}'\n```\n\nDiagnose auth failures:\n\n```bash\nseal-use auth diagnose --corp \n```\n\nThe diagnostic stages are `hose.openapi`, `hose.provisional`, `seal.sso`, and `seal.whoami`. Tokens are omitted from output.\n\nSearch approval content:\n\n```bash\nseal-use tool seal_approval_search --corp --json '{\"keywords\":[\"关键词\"],\"matchMode\":\"any\",\"maxResults\":20}'\n```\n\nGet aggregated approval context:\n\n```bash\nseal-use tool seal_approval_context_get --corp --json '{\"documentLimit\":20}'\n```\n\nCreate a draft approval rule:\n\n```bash\nseal-use tool seal_approval_rule_create --corp --json '{\"description\":\"规则描述\",\"scope\":\"适用场景\",\"strictness\":\"SHOULD_FOLLOW\"}'\n```\n\nUpdate an approval document:\n\n```bash\nseal-use tool seal_approval_document_update --corp --json '{\"documentId\":\"doc-id\",\"content\":\"Markdown 内容\"}'\n```\n\nSummarize one local date:\n\n```bash\nseal-use approval-runs summary --corp --date 2026-06-09 --timezone Asia/Shanghai --limit 100\n```\n\nFind a run and include Langfuse bridge rows:\n\n```bash\nseal-use approval-runs search --corp --query --limit 20 --includeBridge true\n```\n\nResolve Langfuse trace/session hints:\n\n```bash\nseal-use approval-runs bridge --corp --sourceDocumentSN \n```\n\n模拟测试批次(模拟发布闭环)创建与查询:\n\n```bash\n# 合思指定单号: 创建批次(响应只含 batchId)\nseal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" --reject-node 财务 --thinking-depth medium --skip-invoice-generation --corp \n# 材料包导入: 先上传材料包 ZIP(服务端解析并返回 schemaConfig), 再用返回的 id 发起\nseal-use simulation package-upload 测试材料包.zip --corp \nseal-use simulation create --mode material_pack --package-ids --template-id conference_reimbursement_v1 --schema-config schema.json --corp \n# 预留: 其他模式参数通过 --json 透传(如时间范围 startTime/endTime)\nseal-use simulation create --mode hosecloud --flow-ids \"B26017701\" --json '{\"startTime\":0,\"endTime\":0}' --corp \n# 创建后轮询批次状态与记录\nseal-use simulation list --limit 50 --corp \nseal-use simulation get --corp \nseal-use simulation batch-records --corp \nseal-use simulation templates --corp \nseal-use simulation integrations --corp \n```\n\n## Write Operation Payloads\n\nCreate a rule:\n\n```json\n{\n \"description\": \"规则描述\",\n \"scope\": \"适用场景\",\n \"strictness\": \"MUST_FOLLOW | SHOULD_FOLLOW | SUGGESTION\"\n}\n```\n\nUpdate a rule:\n\n```json\n{\n \"ruleId\": \"rule-id\",\n \"description\": \"可选\",\n \"scope\": \"可选\",\n \"strictness\": \"SHOULD_FOLLOW\"\n}\n```\n\nPublish a rule version:\n\n```json\n{\n \"versionName\": \"版本名称\"\n}\n```\n\nCreate a document:\n\n```json\n{\n \"title\": \"标题\",\n \"purpose\": \"用途\",\n \"content\": \"Markdown 内容\",\n \"contentType\": \"text/markdown\",\n \"status\": \"可选\",\n \"scenarios\": [\"场景\"],\n \"tags\": [\"标签\"]\n}\n```\n\nUpdate a document:\n\n```json\n{\n \"documentId\": \"doc-id\",\n \"title\": \"可选\",\n \"purpose\": \"可选\",\n \"content\": \"可选\",\n \"enabled\": true,\n \"scenarios\": [\"可选\"],\n \"tags\": [\"可选\"]\n}\n```\n\nUpdate style preferences:\n\n```json\n{\n \"tone\": \"可选\",\n \"language\": \"可选\",\n \"detailLevel\": \"可选\",\n \"outputFormat\": \"可选\",\n \"examples\": [\"可选\"],\n \"prohibitedPhrases\": [\"可选\"],\n \"customInstructions\": \"可选\"\n}\n```\n\n## Material Pack Workflow\n\nA **material pack** (材料包) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is the primary input to the Webhook-based AI approval ingestion pipeline.\n\n### ZIP structure convention\n\n```\n材料包.zip\n├── 信息表.xlsx ← must exist at ZIP root\n├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)\n│ ├── 合同协议/\n│ │ └── 采购合同.pdf\n│ └── 支付凭证/\n│ └── 支付宝交易明细.pdf\n└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId\n └── 发票/\n └── 增值税专用发票.pdf\n```\n\n- The root directory name **must equal** the `documentId` **OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).\n- `信息表.xlsx` at the ZIP root is the only file not associated with any document directory.\n\n### Excel column convention\n\n| Column type | Naming | Purpose |\n|---|---|---|\n| Regular column | Any header (e.g. `会议编号`, `总金额`) | Standard document fields |\n| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`) | Declares attached files for this row |\n\n- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.\n- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).\n- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`\n\n### Sheet → document level mapping\n\n| Excel sheet | Maps to |\n|---|---|\n| First sheet (main / 会议) | Root document `categoryFields` |\n| 费用明细表 (has `报销金额` column) | Per-row entries in `mingxi_list` |\n| 劳务明细 (has `姓名` column) | Per-person entries in `daoshi_list` |\n\n### Strict bidirectional validation\n\nBefore pushing or previewing, the system enforces:\n\n1. **Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: `\n2. **ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: `\n3. **Document Directory Scope Isolation**: All attachments declared for a document `DOC_X` **must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: 。附件必须位于该单据自己的根目录...`\n4. **Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire material pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「」被重复声明了 N 次...`\n5. **Attachment file policy**: Every attachment except the root `信息表.xlsx` must satisfy the selected Webhook's minimum size, optional maximum size, and extension whitelist. The default minimum is 500 bytes; the default maximum is unlimited; the default whitelist includes common PDF, Office, text, email, and image formats. Error: `附件文件过小...` / `附件文件过大...` / `附件后缀不在白名单中...`\n6. **documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet must have a matching ZIP root dir (exact match or `documentId@annotation`). Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`\n\nAll validation errors are collected and reported together in a single `MaterialPackValidationError`.\n\n### CLI usage\n\n```bash\n# Check environment readiness and optionally pre-validate the material pack\nseal-use webhook ready [--file ] [--corp ]\n\n# Dry-run: local parse & validation only, no network calls, returns preview JSON\nseal-use webhook material-pack preview --corp \n# Preview with temporary local policy overrides (comma-separated extensions)\nseal-use webhook material-pack preview --min-file-size 500 --max-file-size 20971520 --allowed-extensions .pdf,.xlsx,.docx --corp \n\n# Upload attachments and push documents via inbound Webhook\nseal-use webhook material-pack push [--webhook ] --corp \n# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)\n```\n\n### Attachment file policy configuration\n\nThe policy is stored per inbound Webhook integration and is applied before any attachment upload or document push. A failed check stops the entire material-pack flow. The policy is intentionally mutable: after an authorized configuration change, retrying the same push reads the saved policy again.\n\nDefault configuration:\n\n```json\n{\n \"minFileSizeBytes\": 500,\n \"maxFileSizeBytes\": null,\n \"allowedExtensions\": [\n \".pdf\", \".xls\", \".xlsx\", \".csv\", \".doc\", \".docx\", \".ppt\", \".pptx\",\n \".txt\", \".rtf\", \".odt\", \".ods\", \".odp\", \".jpg\", \".jpeg\", \".png\",\n \".gif\", \".bmp\", \".webp\", \".heic\", \".eml\", \".msg\"\n ]\n}\n```\n\n`null` or an omitted `maxFileSizeBytes` means no per-file upper bound. Values are bytes; a file smaller than the minimum or larger than the maximum fails. Extensions are normalized case-insensitively and may be written with or without the leading dot. The root `信息表.xlsx` remains exempt from attachment policy checks.\n\n```bash\n# New Webhook: use the default 500-byte minimum and default extension whitelist\nseal-use webhook add --name \"材料包入站\" --result-url \"https://your-domain.com/callback\" --corp \n\n# Configure an existing Webhook; sizes are bytes and extensions are comma-separated\nseal-use webhook update \\\n --min-file-size 500 \\\n --max-file-size 20971520 \\\n --allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png \\\n --corp \n\n# Allow a newly confirmed format while retaining the rest of the policy:\n# first read webhook get/list, then pass the complete desired whitelist.\nseal-use webhook update \\\n --allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png,.zip \\\n --corp \n\n# Remove only the maximum-size limit (minimum and whitelist are retained).\nseal-use webhook update --clear-max-file-size --corp \n```\n\nThe saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy.\n\n### Failure recovery loop\n\nWhen a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop:\n\n1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary.\n2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy.\n3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration.\n4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins.\n\nThe same loop is available through MCP: read with `seal_webhook_get`/`seal_webhook_list`, update with `seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal_webhook_material_pack` in `push` mode. For MCP, set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one.\n\nIf the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack.\n\nThe direct local `material-pack preview` command and MCP preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use `webhook ready --file --webhook ` or the actual push path when validating against the saved inbound policy.\n\n### Error messages reference\n\n| Error message | Meaning | Fix |\n|---|---|---|\n| `Excel 声明的附件路径在 ZIP 中不存在: ` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |\n| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: ` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |\n| `单据「X」声明了跨单据或非本单据目录的附件路径: ` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |\n| `附件路径「」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |\n| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |\n| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |\n| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |\n| `附件文件过小` | Attachment is below the configured minimum byte size | Replace the empty/truncated file or lower `--min-file-size` |\n| `附件文件过大` | Attachment exceeds the configured maximum byte size | Replace/compress the file or raise `--max-file-size` |\n| `附件后缀不在白名单中` | Attachment extension is not allowed by the Webhook policy | Add the extension with `--allowed-extensions` or convert the file |\n| `附件上传失败 ` | Network/server error during file upload | Check webhook URL, secret, and server availability |\n\n## Failure Handling\n\n- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use `seal-use service restart` after updates so the optional local service picks up new code.\n- If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`.\n- If date-based summaries look wrong, pass `--timezone Asia/Shanghai` and an explicit `--date`.\n- If `langfuseTraceId` is missing, use `langfuseSessionFallback`.\n- If a write operation fails, report the raw JSON error and do not retry with guessed payloads.\n";var rz0="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-use approval-runs pick --corp --sn --latest\nseal-use approval-runs pick --corp --sn --batch --latest\nseal-use approval-runs pick --corp --sn --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-use approval-runs get --corp --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-use approval-runs get --corp --fields metadata\nseal-use approval-runs get --corp --fields document.fields,result.summary\nseal-use approval-runs get --corp --fields result.summary,result.decision,result.riskPoints\nseal-use approval-runs get --corp --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get ` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-use approval-runs document-summary --corp \n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-use approval-runs cited-rules --corp \n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n# 查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-use approval-runs attachments --corp --summary\n\n# 下载全部附件到本地目录(优先使用 ossSignedUrl 签名直链)\nseal-use approval-runs attachments download --all --out-dir ./downloads --corp \n\n# 按名称或 fileId 过滤下载单个附件\nseal-use approval-runs attachments download --name 发票 --corp \n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-use approval-runs result --corp --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Output Discipline\n\nIf a command warns that output is large, do not retry with `--full` reflexively. Narrow with `--summary`, `--fields`, or `--output-file` first.\n";var tz0=`# Approval Attachment Trace Investigation Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result. diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index afc62f3..a94b206 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -66,12 +66,27 @@ seal-use corps list - System Permissions Config: `seal-use permissions available --corp `, `seal-use permissions configs --corp `. - Billing & Feature Quotas: `seal-use billing status --corp `, `seal-use billing plans --corp `, `seal-use billing features --corp `. - Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] [--webhook ] --corp ` (别名 `status`) 检查企业环境、租户连通性、已激活通道与材料包预检;`seal-use webhook --corp `. -- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp ` 只做本地校验和解析(无网络请求);`... push <材料包.zip> [--webhook ] --corp ` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Material Pack Workflow" 一节。它与 `simulation material_pack` 的官方服务端导入流程相互独立。 +- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp ` 只做本地校验和解析(无网络请求);`... push <材料包.zip> [--webhook ] --corp ` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。每个 Webhook 可配置材料包附件的最小字节数、可选最大字节数和文件后缀白名单;这是可修改的持久化策略,不是不可绕过的硬编码。校验不通过时不会上传附件或推送单据。材料包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Material Pack Workflow" 一节。它与 `simulation material_pack` 的官方服务端导入流程相互独立。 - HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。 - 审批规则质量校验 (Linter): `seal-use rules lint [--linter ] [--version ] [--code ] [--min-score ] [--summary] --corp `; read `references/rule-lint.md`. 全局配置默认关闭 (`config lint `)。 - Full CLI inventory: read `references/cli.md`. +## Material-pack Webhook policy and recovery + +材料包附件策略保存在目标入站 Webhook 的 `materialPackFilePolicy` 下,按 Webhook 生效。新建 Webhook 的默认策略是:最小文件大小 `500` 字节、最大文件大小不限制、后缀白名单为常见 PDF/Office/文本/邮件/图片格式。`信息表.xlsx` 是材料包根清单,不属于普通附件,不受这三个附件策略限制。完整默认后缀和边界规则见 `references/cli.md`。 + +这套策略允许人工或助手修改。错误处理有两条通道:先通过错误通道明确告诉助手是哪一个文件、哪一条规则失败;再通过配置或文件处置通道完成恢复。遇到附件被拦截时按以下闭环处理: + +1. 从错误中识别被拦截的文件、实际大小、失败规则和目标 Webhook。 +2. 向用户说明可选处置:替换/压缩文件,或在确认允许该格式/大小后修改 Webhook 策略。 +3. 用户或业务负责人明确确认放宽策略后,读取目标 Webhook 当前配置(CLI 使用 `webhook get`/`webhook list`,MCP 使用 `seal_webhook_get`/`seal_webhook_list`)。 +4. 调用 `seal_webhook_update` 或 `seal-use webhook update` 修改最小值、最大值或完整后缀白名单,写入后重新读取核对,再重试原来的材料包 push。 + +push 会重新读取最新 Webhook 配置;校验通过后才会开始上传附件。CLI 以非零退出码和 `stderr` 返回可恢复的业务错误,MCP 以工具错误返回。没有用户授权或没有修改权限时,不能擅自放宽策略,也不能绕过校验。 + +注意:直接执行本地 `material-pack preview` 只使用默认策略或命令行临时覆盖,不会自动读取某个 Webhook 的持久化策略;`webhook ready --file`(指定 Webhook 时)和 `material-pack push` 才使用保存的 Webhook 策略。需要验证实际入站通道策略时,优先使用 `ready --file --webhook ...`,或直接重试 push。 + ## High-Value Commands ```bash diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 7323cd5..3649995 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -71,8 +71,8 @@ seal-use billing plans [--corp ] seal-use billing features [--corp ] seal-use webhook list [--query ] [--show-secret] [--corp ] seal-use webhook get|find [--show-secret] [--corp ] -seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--corp ] -seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--corp ] +seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] +seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ] seal-use webhook delete --yes [--corp ] seal-use deploy hosecloud requirements [--corp ] seal-use deploy hosecloud list [--corp ] @@ -169,12 +169,12 @@ Webhook integrations: - `seal-use webhook list [--query ] [--show-secret] [--corp ]` - `seal-use webhook get|find [--show-secret] [--corp ]` - `seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ]` -- `seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ]` +- `seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ]` - `seal-use webhook delete --yes [--corp ]` - `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] --corp ` - `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook ] --corp ` -Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. +Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once. Each Webhook can also store a mutable `materialPackFilePolicy` with `minFileSizeBytes`, optional `maxFileSizeBytes`, and `allowedExtensions`. Update is a patch: omitted policy fields are retained; `allowedExtensions` replaces the complete list; `--clear-max-file-size` removes the upper bound. Approval runs, simulations, and Langfuse bridge: @@ -418,7 +418,23 @@ seal-use webhook material-pack push [--webhook ] --corp \ --max-file-size 20971520 \ --allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png \ --corp + +# Allow a newly confirmed format while retaining the rest of the policy: +# first read webhook get/list, then pass the complete desired whitelist. +seal-use webhook update \ + --allowed-extensions .pdf,.xlsx,.xls,.docx,.pptx,.jpg,.png,.zip \ + --corp + +# Remove only the maximum-size limit (minimum and whitelist are retained). +seal-use webhook update --clear-max-file-size --corp ``` The saved configuration is returned by `webhook get`/`webhook list` under `materialPackFilePolicy`. The root `信息表.xlsx` is always allowed as the material-pack manifest and is not subject to the attachment policy. +### Failure recovery loop + +When a push fails because of the attachment policy, the error is actionable and should be handled as a two-channel recovery loop: + +1. Error channel: read `附件文件过小`, `附件文件过大`, or `附件后缀不在白名单中`, including the attachment path and the configured boundary. +2. Resolution channel: ask whether the user wants to replace/compress the file or explicitly allow the format/size by changing the target Webhook policy. +3. If configuration change is authorized, read the current policy with `webhook get`/`webhook list`, update only the necessary fields, and verify the returned configuration. +4. Retry the original `material-pack push`; it will load the latest saved policy before any upload begins. + +The same loop is available through MCP: read with `seal_webhook_get`/`seal_webhook_list`, update with `seal_webhook_update` and its `materialPackFilePolicy` patch, then retry `seal_webhook_material_pack` in `push` mode. For MCP, set `maxFileSizeBytes` to `null` to clear the upper bound. `allowedExtensions` is a complete replacement list, so include existing allowed suffixes when adding one. + +If the assistant lacks permission to update the Webhook or the user does not authorize relaxing the rule, report the block rather than bypassing validation. Since validation happens before the upload loop, a failed attempt does not leave a partially pushed material pack. + +The direct local `material-pack preview` command and MCP preview use the default or temporary policy. They do not automatically read a selected Webhook's persisted policy. Use `webhook ready --file --webhook ` or the actual push path when validating against the saved inbound policy. + ### Error messages reference | Error message | Meaning | Fix | diff --git a/src/cli/parser.ts b/src/cli/parser.ts index fc09de0..1b43524 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -206,6 +206,9 @@ export function webhookShowSecretOption(options: Record ): MaterialPackFilePolicyPatch | undefined { + const clearMaxFileSize = booleanOption( + options.clearMaxFileSize ?? options["clear-max-file-size"] + ) === true; const minFileSizeBytes = numberOption( options.minFileSizeBytes ?? options["min-file-size-bytes"] ?? options.minFileSize ?? options["min-file-size"] ); @@ -216,9 +219,18 @@ export function materialPackFilePolicyOptions( options.allowedExtensions ?? options["allowed-extensions"] ?? options.extensions ); - if (minFileSizeBytes === undefined && maxFileSizeBytes === undefined && allowedExtensions === undefined) { + if ( + minFileSizeBytes === undefined && + maxFileSizeBytes === undefined && + allowedExtensions === undefined && + !clearMaxFileSize + ) { return undefined; } - return { minFileSizeBytes, maxFileSizeBytes, allowedExtensions }; + return { + minFileSizeBytes, + maxFileSizeBytes: clearMaxFileSize ? null : maxFileSizeBytes, + allowedExtensions + }; } diff --git a/src/cli/printer.ts b/src/cli/printer.ts index 2581785..e63f59a 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -123,7 +123,7 @@ Usage: seal-use webhook list [--query ] [--show-secret] [--corp ] seal-use webhook get|find [--show-secret] [--corp ] seal-use webhook add --name --result-url [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret ] [--min-file-size 500] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] - seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] + seal-use webhook update [--name ] [--result-url ] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret |--rotate-secret] [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--clear-max-file-size] [--corp ] seal-use webhook delete --yes [--corp ] seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--min-file-size ] [--max-file-size ] [--allowed-extensions <.pdf,.xlsx,...>] [--corp ] seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook ] [--corp ]