diff --git a/.data/attachments/inbound/m-3001.eml b/.data/attachments/inbound/m-3001.eml new file mode 100644 index 0000000..099c477 --- /dev/null +++ b/.data/attachments/inbound/m-3001.eml @@ -0,0 +1,12 @@ +{ + "messageId": "m-3001", + "from": "buyer@acme.com", + "to": [ + "rfq@we.com" + ], + "cc": [], + "subject": "询价 RFQ-A7X 车规 Analog(客户 C001)", + "body": "请报价:LM358DR 5000pcs 交期8周。单号 RFQ-A7X,客户码 C001。", + "receivedAt": "2026-07-27T02:00:00.000Z", + "attachments": [] +} \ No newline at end of file diff --git a/activities/quote-alternative/package.json b/activities/quote-alternative/package.json new file mode 100644 index 0000000..616fbfc --- /dev/null +++ b/activities/quote-alternative/package.json @@ -0,0 +1 @@ +{ "name": "@activities/quote-alternative", "version": "0.1.0", "private": true, "type": "module", "exports": { ".": "./src/index.ts" } } diff --git a/activities/quote-alternative/src/case-model.ts b/activities/quote-alternative/src/case-model.ts new file mode 100644 index 0000000..745d87f --- /dev/null +++ b/activities/quote-alternative/src/case-model.ts @@ -0,0 +1,111 @@ +/** + * A2 替代选型的案例模型 —— **双表示同版本**:CMMN XML(机器面)与案例说明书(叙事面)。 + */ + +export const CMMN_XML = ` + + + + + + + + + + + create + + + update + needAlternative = true + + + create + + + update + candidatesConfirmed >= 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + P2D + + + + +`; + +export const NARRATIVE = `§0 开案:替代选型一事一议 —— 收到替代评估请求即开案。客户/PM 给出初选物料,或芯片类型与大致参数。 +先核初选(EOL 等风险提示 + 是否我司主推品牌),无风险且主推直接采信初选办结; +需要替代的,先撒网(AI 检索/聚合平台拉初筛清单)后逐条人工核验,常要两三轮, +存活候选按替代等级分级(P2P/功能兼容/其他)圈 2~3 颗,做参数对比与风险评估成报告交回。 +**任何替代必须把差异与风险写清 —— 差异没核清的不放行。** + +S1 初选核险:一手资料以原厂官网为准(产品页/规格书/PCN·EOL 公告); +查芯片规格书确认初选料有无 EOL/停产风险,生命周期对照 PN物料主库; +对品牌原厂字典判是否我司主推 —— 无风险且主推,直接采信初选、免替代办结。 +顺手查替代料库与技术问题案例库(裁量项),有沉淀方案或已知坑先亮出来。 + +S2 圈选替代:先撒网后核验,常要两三轮。逐条人工核验做全面参数对比 —— +先明确每项数据的来源(一律以原厂官网规格书为准),再逐项对标(Pin-to-Pin); +存活者按替代等级分级;候选过客户技术画像禁用清单;不足 2~3 颗就放宽参数或换角度重新撒网。 + +S3 对比评估交付:收齐候选规格书,关键参数逐项对比写进替代对标表,标出差异项与替代等级, +写明差异带来的风险;按等级定评估深度 —— P2P 核确免改动,功能兼容/其他逐项评软件开发、 +外围电路与 layout 改动。FAE 签字后交回发起方。 + +全程随时可做:知识入库 —— 规格书入库、替代关系回填替代料库与 PN物料主库、踩到的坑记案例库。 + +§Z 结案:必做的事都办完、没有进行中的事,自动算结案(CMMN AutoComplete)。 +无需替代的,确认初选可用即结案;需要替代的,推荐报告(已签字)交回发起方即结案 —— +每办一案,知识库厚一层。`; diff --git a/activities/quote-alternative/src/index.ts b/activities/quote-alternative/src/index.ts new file mode 100644 index 0000000..9f06d36 --- /dev/null +++ b/activities/quote-alternative/src/index.ts @@ -0,0 +1,63 @@ +/** + * 统一报价 A2 · 替代选型 —— 活动包代码入口(ADR-004)。 + * loop 活动:调度权归 AI;本文件只做视图流控与「差异没核清不放行」的把关呈现。 + */ +import { defineActivity } from '@sdk'; +import type { ActivityBase, ActivityOutcome } from '@sdk'; + +const SHORTLIST = 'quote_alternative.shortlist'; +const BENCHMARK = 'quote_alternative.benchmark'; + +export default defineActivity({ + name: 'quote-alternative', + paradigm: 'loop', + + async run(base: ActivityBase): Promise { + const shortlist = await base.ledger.read(SHORTLIST); + const benchmark = await base.ledger.read(BENCHMARK); + // 差异没核清的不放行 —— 禁区的机检形态 + const unclear = benchmark.filter((r) => String(r['risk'] ?? '').trim() === ''); + + await base.interaction.pushView([ + { + t: 'kv', + title: '选型进展', + items: [ + { k: '原型号', v: String(base.contract.data['originalPn'] ?? '') }, + { k: '初筛候选', v: `${shortlist.length} 颗` }, + { k: '已对标', v: `${benchmark.length} 颗` }, + { k: '差异未核清', v: `${unclear.length} 颗` }, + ], + }, + { + t: 'cards', + title: '候选替代', + items: benchmark.map((r) => ({ + tag: String(r['grade'] ?? '待定级'), + title: String(r['candidate_pn'] ?? ''), + swap: { from: String(r['original_pn'] ?? ''), to: String(r['candidate_pn'] ?? '') }, + big: String(r['grade'] ?? '—'), + bigLabel: '替代等级', + note: String(r['risk'] ?? '差异风险未写'), + tone: String(r['risk'] ?? '').trim() === '' ? 'danger' : 'ok', + })), + }, + ]); + + if (benchmark.length < 2) { + await base.interaction.say( + shortlist.length === 0 ? '尚未撒网,先拉初筛清单。' : `已初筛 ${shortlist.length} 颗,继续逐条核验分级。`, + 'conclusion', + ); + return { kind: 'await', reason: '候选不足 2 颗' }; + } + + if (unclear.length > 0) { + await base.interaction.say(`${unclear.length} 颗候选的差异风险未写清 —— 差异没核清的不放行。`, 'criterion'); + return { kind: 'await', reason: '差异风险未核清' }; + } + + await base.interaction.say('候选已分级、差异与风险已写清,可签字交回发起方。', 'criterion'); + return { kind: 'submit', deliverable: 'benchmark-table', rationale: '2 颗以上分级候选,差异与风险齐备' }; + }, +}); diff --git a/activities/quote-alternative/src/manifest.ts b/activities/quote-alternative/src/manifest.ts new file mode 100644 index 0000000..2c970d5 --- /dev/null +++ b/activities/quote-alternative/src/manifest.ts @@ -0,0 +1,185 @@ +/** + * 活动包清单 —— 统一报价 A2 · 替代选型(**案例活动 · loop**)。 + * + * 业务素材:docs/MVP示例工作流.html §1.6。 + * `▶需拍板`(签字交出)→ manualActivation + 放行;`✋客户改需求` → userEventListener; + * `⏱时限过半` → 时间监听(**时限必配**)。 + */ +import type { ActivityManifest, DmnModel } from '@contracts'; +import { activityIdSchema } from '@contracts'; +import { CMMN_XML, NARRATIVE } from './case-model.ts'; + +const DOMAIN = 'quote_alternative'; +const ACTIVITY_ID = activityIdSchema.parse('quote-alternative'); + +/** 替代等级 —— 把「装得下的判断」从 LLM 手里拿走 */ +export const GRADE_DMN: DmnModel = { + drd: [{ decision: 'alt-grade', requires: [], inputs: ['pinCompatible', 'packageSame', 'paramDelta'] }], + tables: [ + { + id: 'alt-grade', + label: '替代等级判定', + hitPolicy: 'FIRST', + inputs: [ + { name: 'pinCompatible', expression: 'pinCompatible' }, + { name: 'packageSame', expression: 'packageSame' }, + { name: 'paramDelta', expression: 'paramDelta' }, + ], + outputs: [{ name: 'grade' }, { name: 'effort' }], + rules: [ + { id: 'g-p2p', when: ['true', 'true', '<= 0.05'], then: ['P2P', '核确免改动'] }, + { id: 'g-func', when: ['-', '-', '<= 0.20'], then: ['功能兼容', '评外围电路与 layout'] }, + { id: 'g-other', when: ['-', '-', '-'], then: ['其他', '须验证'] }, + ], + }, + ], +}; + +export const manifest: ActivityManifest = { + identity: { + activityId: ACTIVITY_ID, + name: 'A2 · 替代选型', + packageVersion: '0.1.0', + category: '统一报价', + paradigm: 'loop', + sdkVersion: '0.1.0-m5', + checksum: 'dev-checksum-quote-alternative', + }, + + contract: { + activityId: ACTIVITY_ID, + version: '0.1.0', + input: { + data: { + type: 'object', + required: ['originalPn'], + properties: { + originalPn: { type: 'string' }, + chipType: { type: 'string' }, + params: { type: 'object' }, + scenario: { type: 'string' }, + }, + }, + messageAllowed: true, + }, + output: { + mandatory: [ + { + name: 'benchmark', + payload: { type: 'object', required: ['rows'], properties: { rows: { type: 'array' } } }, + description: '替代对标表(已签字)', + }, + ], + selective: [], + }, + requiredDeliverables: [{ key: 'benchmark-table', label: '替代对标表(FAE 签字)' }], + acceptanceCriteria: [ + { key: 'candidates', label: '2~3 颗分级候选经确认', level: 'L2', predicate: 'candidatesConfirmed >= 2' }, + { key: 'diff-clear', label: '差异项与风险逐项写清', level: 'L2', predicate: 'undocumentedDiff = 0' }, + { key: 'source-traceable', label: '每项数据来源可溯(以原厂官网规格书为准)', level: 'L3' }, + { key: 'fae-sign', label: 'FAE 签字放行', level: 'L5' }, + ], + prohibitions: [ + { key: 'no-unclear-diff', statement: '差异没核清的不放行' }, + { key: 'no-banned', statement: '客户技术画像禁用清单里的型号不得作候选' }, + ], + authorization: { + discretion: [{ key: 'widen-search', statement: '候选不足 2~3 颗时可放宽参数或换角度重新撒网' }], + preauthorizedActions: [], + humanCallBudget: 6, + }, + resources: { + tools: [{ name: 'crm.history-price-read' }], + skills: [], + models: ['quote-extractor'], + roles: ['FAE'], + budget: { steps: 100, tokens: 260_000, activeMinutes: 360, humanCalls: 6 }, + }, + }, + + declarations: { + models: ['quote-extractor'], + tools: [{ name: 'crm.history-price-read' }], + ledger: [ + { + domain: DOMAIN, + object: 'shortlist', + label: '初筛清单', + fields: [ + { name: 'original_pn', type: 'text', primaryKey: true, masked: false, label: '原型号' }, + { name: 'candidate_pn', type: 'text', primaryKey: true, masked: false, label: '候选型号' }, + { name: 'brand', type: 'text', primaryKey: false, masked: false, label: '品牌' }, + { name: 'lifecycle', type: 'text', primaryKey: false, masked: false, label: '生命周期' }, + ], + }, + { + domain: DOMAIN, + object: 'benchmark', + label: '替代对标表', + fields: [ + { name: 'original_pn', type: 'text', primaryKey: true, masked: false }, + { name: 'candidate_pn', type: 'text', primaryKey: true, masked: false }, + { name: 'grade', type: 'text', primaryKey: false, masked: false, label: '替代等级' }, + { name: 'param_diff', type: 'text', primaryKey: false, masked: false, label: '参数差异项' }, + { name: 'risk', type: 'text', primaryKey: false, masked: false, label: '差异风险' }, + { name: 'verify_advice', type: 'text', primaryKey: false, masked: false, label: '验证建议' }, + { name: 'signed_by', type: 'text', primaryKey: false, masked: false, label: 'FAE 签字' }, + ], + }, + ], + listeners: [ + { + // ⏱ 时限过半:向 BD 与 PM 同步进度与风险 + origin: 'static', + eventType: 'time', + keyFilter: { kind: 'half-deadline' }, + semantic: 'observe', + deadline: 'P2D', + escalation: ['nudge'], + }, + { + // ✋ 客户改需求:应用条件/参数变更 → 回初选核险与圈选复核 + origin: 'static', + eventType: 'human', + keyFilter: { kind: 'requirement-change' }, + semantic: 'observe', + deadline: 'P5D', + escalation: ['nudge', 'reroute'], + }, + ], + harness: { + memoryWindow: 30, + stallAfter: 'P1D', + nudge: [{ after: 'PT12H', action: 'nudge' }], + retry: { times: 2, backoff: 'PT5M' }, + }, + }, + + assets: { + businessModel: { + paradigm: 'loop', + cmmnXml: CMMN_XML, + narrative: NARRATIVE, + dmn: GRADE_DMN, + }, + skills: [], + viewTemplates: [ + { name: 'alt-board', html: '

替代选型

' }, + ], + cardSchemas: {}, + distillHooks: [ + { on: 'milestone', milestone: 'M_candidates', prompt: '归纳本轮撒网的有效角度与无效角度。' }, + { on: 'terminal', prompt: '归纳替代经验:哪些参数差异实际造成了问题、哪些品牌的替代关系可复用。' }, + ], + }, + + samples: [ + { + name: 'EOL 料替代', + input: { originalPn: 'TL072CDR', chipType: '运放', scenario: '车规' }, + expect: { ports: ['benchmark'] }, + }, + ], + + entry: { file: 'index.js', checksum: 'dev-entry-quote-alternative' }, +}; diff --git a/activities/quote-archive/package.json b/activities/quote-archive/package.json new file mode 100644 index 0000000..a58fe5c --- /dev/null +++ b/activities/quote-archive/package.json @@ -0,0 +1 @@ +{ "name": "@activities/quote-archive", "version": "0.1.0", "private": true, "type": "module", "exports": { ".": "./src/index.ts" } } diff --git a/activities/quote-archive/src/index.ts b/activities/quote-archive/src/index.ts new file mode 100644 index 0000000..2e65234 --- /dev/null +++ b/activities/quote-archive/src/index.ts @@ -0,0 +1,37 @@ +/** + * 统一报价 A7 · 情报归档 —— 活动包代码入口(ADR-004)。 + * 「不成交也留资产」:把归档结果摆给人看,确认无空档再提交放行。 + */ +import { defineActivity } from '@sdk'; +import type { ActivityBase, ActivityOutcome } from '@sdk'; + +export default defineActivity({ + name: 'quote-archive', + paradigm: 'flow', + + async run(base: ActivityBase): Promise { + const history = await base.ledger.read('shared.history_price'); + const stats = await base.ledger.read('shared.landing_stats'); + + await base.interaction.pushView([ + { + t: 'kv', + title: '归档闭环', + items: [ + { k: '情报回写', v: `${history.length} 条` }, + { k: '落地率', v: stats.length > 0 ? String(stats[0]?.['landing_rate'] ?? '—') : '—' }, + { k: '客户', v: String(base.contract.data['customerCode'] ?? '') }, + ], + }, + ]); + + // 不得空归档 —— 每一单不成交的报价也是情报资产 + if (history.length === 0) { + await base.interaction.say('情报尚未回写,继续登记结果。', 'conclusion'); + return { kind: 'await', reason: '等待结果登记步完成' }; + } + + await base.interaction.say('拒绝原因与竞对价位已回写,画像与落地率已落账。', 'criterion'); + return { kind: 'submit', deliverable: 'history-archive', rationale: '情报、画像、落地率三样齐备' }; + }, +}); diff --git a/activities/quote-archive/src/manifest.ts b/activities/quote-archive/src/manifest.ts new file mode 100644 index 0000000..81944be --- /dev/null +++ b/activities/quote-archive/src/manifest.ts @@ -0,0 +1,180 @@ +/** + * 活动包清单 —— 统一报价 A7 · 情报归档。 + * + * 业务素材:docs/MVP示例工作流.html §1.7(S1 结果登记 → S2 画像更新 → S3 落地率统计)。 + * 「不成交也留资产:情报、客户画像、落地率」—— 写的是**共享域**,跨活动的沉淀事实。 + */ +import type { ActivityManifest } from '@contracts'; +import { activityIdSchema } from '@contracts'; + +const ACTIVITY_ID = activityIdSchema.parse('quote-archive'); + +export const manifest: ActivityManifest = { + identity: { + activityId: ACTIVITY_ID, + name: 'A7 · 情报归档', + packageVersion: '0.1.0', + category: '统一报价', + paradigm: 'flow', + sdkVersion: '0.1.0-m5', + checksum: 'dev-checksum-quote-archive', + }, + + contract: { + activityId: ACTIVITY_ID, + version: '0.1.0', + input: { + data: { + type: 'object', + required: ['customerCode', 'quoteNo'], + properties: { + customerCode: { type: 'string' }, + quoteNo: { type: 'string' }, + reason: { type: 'string' }, + competitorPrice: { type: 'number' }, + }, + }, + messageAllowed: true, + }, + output: { + mandatory: [ + { + name: 'archived', + payload: { type: 'object', properties: { landingRate: { type: 'number' } } }, + description: '归档闭环:情报回写 + 落地率落账', + }, + ], + selective: [], + }, + requiredDeliverables: [ + { key: 'history-archive', label: '历史价格情报(归档)' }, + { key: 'landing-stats', label: '报价落地率统计' }, + ], + acceptanceCriteria: [ + { key: 'reason-logged', label: '拒绝原因 / 竞对价位已回写', level: 'L1', predicate: 'reasonLogged = true' }, + { key: 'profile-updated', label: '客户画像标签已更新', level: 'L2', predicate: 'profileUpdated = true' }, + { key: 'bd-release', label: 'BD 放行', level: 'L5' }, + ], + prohibitions: [{ key: 'no-blank-archive', statement: '不得空归档 —— 每一单不成交的报价也是情报资产' }], + authorization: { discretion: [], preauthorizedActions: [], humanCallBudget: 1 }, + resources: { + tools: [], + skills: [], + models: ['quote-extractor'], + roles: ['BD'], + budget: { steps: 30, tokens: 60_000, activeMinutes: 60, humanCalls: 1 }, + }, + }, + + declarations: { + models: ['quote-extractor'], + tools: [], + ledger: [ + { + // 共享域:跨活动的沉淀事实(AM 11.3 暗耦合禁令的两条合法路径之一) + domain: 'shared', + object: 'history_price', + label: '历史价格情报', + fields: [ + { name: 'pn', type: 'text', primaryKey: true, masked: false }, + { name: 'quoted_at', type: 'date', primaryKey: true, masked: false }, + { name: 'lost_reason', type: 'text', primaryKey: false, masked: false, label: '拒绝原因' }, + { name: 'competitor_price', type: 'number', primaryKey: false, masked: false, label: '竞对价位' }, + ], + }, + { + domain: 'shared', + object: 'customer', + label: '客户资料库', + fields: [ + { name: 'customer_code', type: 'text', primaryKey: true, masked: false, label: '客户码' }, + { name: 'grade', type: 'text', primaryKey: false, masked: false, label: '客户等级' }, + { name: 'profile_tags', type: 'text', primaryKey: false, masked: false, label: '画像标签' }, + ], + }, + { + domain: 'shared', + object: 'landing_stats', + label: '报价落地率统计', + fields: [ + { name: 'period', type: 'text', primaryKey: true, masked: false, label: '月份' }, + { name: 'landing_rate', type: 'number', primaryKey: false, masked: false, label: '落地率' }, + { name: 'type_a_hit', type: 'number', primaryKey: false, masked: false, label: 'TypeA命中' }, + { name: 'reply_rate_d3', type: 'number', primaryKey: false, masked: false, label: 'D+3回复率' }, + ], + }, + ], + listeners: [], + // 7 天闭环(MVP示例 §1.7) + harness: { memoryWindow: 15, stallAfter: 'P1D', nudge: [], retry: { times: 2, backoff: 'PT30S' } }, + }, + + assets: { + businessModel: { + paradigm: 'flow', + steps: [ + { + kind: 'llm', + name: 'S1_log_result', + label: 'S1 结果登记(拒绝原因 / 竞对价位)', + input: { reason: 'reason', quoteNo: 'quoteNo' }, + output: { domain: 'shared', object: 'history_price', fields: { lost_reason: 'lostReason' } }, + model: 'quote-extractor', + template: '从跟进反馈里抽出拒绝原因与竞对价位。只输出 JSON。反馈:{{reason}}', + outputSchema: { + type: 'object', + properties: { lostReason: { type: 'string' }, competitorPrice: { type: 'number' } }, + }, + failure: { retry: { times: 2, backoff: 'PT30S' }, fallback: { kind: 'human', workOrder: 'execution' } }, + }, + { + kind: 'pure-tool', + name: 'S2_profile', + label: 'S2 画像更新(供 P-01 的客户等级因子取用)', + input: { customerCode: 'customerCode', reason: 'reason' }, + output: { domain: 'shared', object: 'customer', fields: { profile_tags: 'tags' } }, + tool: 'quote-archive.profile', + failure: { retry: { times: 1, backoff: 'PT10S' }, fallback: { kind: 'blocked' } }, + }, + { + kind: 'pure-tool', + name: 'S3_landing_rate', + label: 'S3 落地率统计', + input: {}, + output: { domain: 'shared', object: 'landing_stats', fields: { landing_rate: 'landingRate' } }, + tool: 'quote-archive.landing-rate', + failure: { retry: { times: 1, backoff: 'PT10S' }, fallback: { kind: 'blocked' } }, + }, + { + kind: 'human', + name: 'S4_release', + label: 'S4 归档闭环验收放行', + input: {}, + workOrder: 'acceptance', + card: { title: '情报归档请验收', deliverable: 'history-archive' }, + deadline: 'P1D', + failure: { retry: { times: 0, backoff: 'PT30S' }, fallback: { kind: 'blocked' } }, + }, + ], + parallelGroups: [], + }, + skills: [], + viewTemplates: [ + { name: 'archive-summary', html: '

归档闭环

' }, + ], + cardSchemas: {}, + distillHooks: [ + { on: 'terminal', prompt: '归纳丢单的共性:价格、交期、竞对、客户类型 —— 供下一单更快更准。' }, + ], + }, + + samples: [ + { + name: '客户拒绝', + input: { customerCode: 'C001', quoteNo: 'Q202601', reason: '竞对报价更低' }, + expect: { ports: ['archived'] }, + }, + ], + + entry: { file: 'index.js', checksum: 'dev-entry-quote-archive' }, +}; diff --git a/activities/quote-negotiate/package.json b/activities/quote-negotiate/package.json new file mode 100644 index 0000000..8a54c42 --- /dev/null +++ b/activities/quote-negotiate/package.json @@ -0,0 +1 @@ +{ "name": "@activities/quote-negotiate", "version": "0.1.0", "private": true, "type": "module", "exports": { ".": "./src/index.ts" } } diff --git a/activities/quote-negotiate/src/index.ts b/activities/quote-negotiate/src/index.ts new file mode 100644 index 0000000..068520a --- /dev/null +++ b/activities/quote-negotiate/src/index.ts @@ -0,0 +1,50 @@ +/** + * 统一报价 A6 · 报价议价 —— 活动包代码入口(ADR-004)。 + * + * 「发出的同时必须建立 D+3/D+7 跟进 —— 没有跟进的报价等于没报。」 + * 这里把跟进监听立起来:AI 对世界只有触达(动作,落在放行)与等待(监听)两种姿势。 + */ +import { defineActivity } from '@sdk'; +import type { ActivityBase, ActivityOutcome } from '@sdk'; + +const QUOTE = 'quote_negotiate.formal_quote'; + +export default defineActivity({ + name: 'quote-negotiate', + paradigm: 'flow', + + async run(base: ActivityBase): Promise { + const lines = await base.ledger.read(QUOTE); + + await base.interaction.pushView([ + { + t: 'table', + title: '正式报价单', + cols: ['PN', '单价CNY', '交期', 'MOQ', '有效期'], + rows: lines.map((r) => [ + String(r['pn'] ?? ''), + String(r['unit_price'] ?? '—'), + String(r['lead_time'] ?? '—'), + String(r['moq'] ?? '—'), + String(r['valid_until'] ?? '—'), + ]), + }, + ]); + + const incomplete = lines.filter((r) => r['unit_price'] === undefined || r['valid_until'] === undefined); + if (lines.length === 0 || incomplete.length > 0) { + await base.interaction.say('报价单条目尚未齐备,继续排版。', 'conclusion'); + return { kind: 'await', reason: '等待报价单生成步完成' }; + } + + // 建 D+3 跟进:等客户回音 —— 时限必配,无死等 + await base.tools.listen({ + eventType: 'data', + keyFilter: { kind: 'customer-reply', customerCode: String(base.contract.data['customerCode'] ?? '') }, + deadline: 'P3D', + }); + await base.interaction.say('已建 D+3 跟进监听 —— 没有跟进的报价等于没报。', 'guidance'); + + return { kind: 'submit', deliverable: 'formal-quote', rationale: '报价单齐备且已建跟进,提交放行即发出' }; + }, +}); diff --git a/activities/quote-negotiate/src/manifest.ts b/activities/quote-negotiate/src/manifest.ts new file mode 100644 index 0000000..06a7829 --- /dev/null +++ b/activities/quote-negotiate/src/manifest.ts @@ -0,0 +1,188 @@ +/** + * 活动包清单 —— 统一报价 A6 · 报价议价。 + * + * 业务素材:docs/MVP示例工作流.html §1.4(S1 生成发出 → S2 CRM 留档 → S3 建立跟进)。 + * 关键机制:生成正式报价单是**写类动作** → 登记为动作意向 → 落地预检 → + * 放行通过即落地(台账回写 + 出站发送)→ 输出口发射;并建 D+3 跟进监听。 + */ +import type { ActivityManifest } from '@contracts'; +import { activityIdSchema } from '@contracts'; + +const DOMAIN = 'quote_negotiate'; +const ACTIVITY_ID = activityIdSchema.parse('quote-negotiate'); + +export const manifest: ActivityManifest = { + identity: { + activityId: ACTIVITY_ID, + name: 'A6 · 报价议价', + packageVersion: '0.1.0', + category: '统一报价', + paradigm: 'flow', + sdkVersion: '0.1.0-m5', + checksum: 'dev-checksum-quote-negotiate', + }, + + contract: { + activityId: ACTIVITY_ID, + version: '0.1.0', + input: { + data: { + type: 'object', + required: ['customerCode', 'items'], + properties: { customerCode: { type: 'string' }, items: { type: 'array' } }, + }, + messageAllowed: true, + }, + output: { + mandatory: [], + // 议价结果是**业务分支**:必须建模为选择组的一口,随放行发射 —— 不得用异常终态编码 + selective: [ + { + group: 'negotiation', + ports: [ + { name: 'won', payload: { type: 'object' }, description: '成交 → 转订单履约(ORM)' }, + { name: 'revise', payload: { type: 'object' }, description: '有异议 → 返回调整 A4' }, + { name: 'lost', payload: { type: 'object' }, description: '拒绝/超时 → 转 A7 情报归档' }, + ], + }, + ], + }, + requiredDeliverables: [ + { key: 'formal-quote', label: '正式报价单(PDF · 中英双语)' }, + { key: 'followup', label: 'D+3/D+7 跟进提醒' }, + ], + acceptanceCriteria: [ + { key: 'quote-complete', label: '单价/交期/SPQ/MOQ/贸易条款/有效期齐备', level: 'L1', predicate: 'missingQuoteFields = 0' }, + { key: 'validity', label: '按报价有效期 P-04 注明有效期', level: 'L2', predicate: 'validityDays > 0' }, + { key: 'followup-set', label: '已建 D+3/D+7 跟进 —— 没有跟进的报价等于没报', level: 'L2', predicate: 'followupSet = true' }, + { key: 'bd-release', label: 'BD 放行', level: 'L5' }, + ], + prohibitions: [ + { key: 'no-break-line', statement: '客户议价超出授权范围的,回 A5 重批,不私自破线' }, + { key: 'no-send-before-release', statement: '报价单在放行前不得发出 —— 写类动作集中在放行时落地' }, + ], + authorization: { + discretion: [{ key: 'haggle-band', statement: '在已批准的价格区间内回旋;出区间必须回审批' }], + // 预授权必须逐项列举:催办模板可即时发,报价单不行 + preauthorizedActions: [{ tool: 'mail.send', operation: 'nudge', limit: '仅催办模板' }], + humanCallBudget: 3, + }, + resources: { + tools: [{ name: 'mail.send' }, { name: 'crm.history-price-read' }], + skills: [], + models: ['quote-extractor'], + roles: ['BD'], + budget: { steps: 50, tokens: 120_000, activeMinutes: 60, humanCalls: 3 }, + }, + }, + + declarations: { + models: ['quote-extractor'], + tools: [{ name: 'mail.send' }, { name: 'crm.history-price-read' }], + ledger: [ + { + domain: DOMAIN, + object: 'formal_quote', + label: '正式报价单', + fields: [ + { name: 'quote_no', type: 'text', primaryKey: true, masked: false, label: '报价单号' }, + { name: 'pn', type: 'text', primaryKey: true, masked: false, label: 'PN' }, + { name: 'unit_price', type: 'number', primaryKey: false, masked: false, label: '单价CNY' }, + { name: 'lead_time', type: 'text', primaryKey: false, masked: false, label: '交期' }, + { name: 'spq', type: 'integer', primaryKey: false, masked: false, label: 'SPQ' }, + { name: 'moq', type: 'integer', primaryKey: false, masked: false, label: 'MOQ' }, + { name: 'trade_terms', type: 'text', primaryKey: false, masked: false, label: '贸易条款' }, + { name: 'valid_until', type: 'date', primaryKey: false, masked: false, label: '有效期' }, + ], + }, + { + domain: 'shared', + object: 'history_price', + label: '历史价格情报(共享域)', + fields: [ + { name: 'pn', type: 'text', primaryKey: true, masked: false }, + { name: 'quoted_at', type: 'date', primaryKey: true, masked: false, label: '报价日期' }, + { name: 'unit_price', type: 'number', primaryKey: false, masked: false }, + { name: 'lead_time', type: 'text', primaryKey: false, masked: false }, + ], + }, + ], + listeners: [ + { + origin: 'static', + eventType: 'data', + keyFilter: { kind: 'customer-reply' }, + semantic: 'complete-step', + // 建 D+3 跟进监听:等客户回音,时限必配 —— 无死等 + deadline: 'P3D', + escalation: ['nudge', 'escalate'], + }, + ], + harness: { + memoryWindow: 20, + stallAfter: 'PT15M', + nudge: [{ after: 'PT10M', action: 'nudge' }], + retry: { times: 2, backoff: 'PT30S' }, + }, + }, + + assets: { + businessModel: { + paradigm: 'flow', + steps: [ + { + kind: 'llm', + name: 'S1_compose', + label: 'S1 生成正式报价单', + input: { items: 'items', customerCode: 'customerCode' }, + output: { domain: DOMAIN, object: 'formal_quote', fields: { unit_price: 'unitPrice', lead_time: 'leadTime' } }, + model: 'quote-extractor', + template: + '把已批准的报价草案排版为正式报价单条目(单价CNY/交期/SPQ/MOQ/贸易条款),' + + '按报价有效期 P-04 注明 7 日历天有效。只输出 JSON。条目:{{items}}', + outputSchema: { + type: 'object', + required: ['lines'], + properties: { lines: { type: 'array' }, validityDays: { type: 'integer' } }, + }, + failure: { retry: { times: 2, backoff: 'PT30S' }, fallback: { kind: 'human', workOrder: 'execution' } }, + }, + { + kind: 'tool', + name: 'S2_send', + label: 'S2 发出报价单(写类 → 登记动作意向,放行时落地)', + input: { customerCode: 'customerCode' }, + tool: 'mail.send', + failure: { retry: { times: 2, backoff: 'PT1M' }, fallback: { kind: 'human', workOrder: 'execution' } }, + }, + { + kind: 'human', + name: 'S3_release', + label: 'S3 正式报价单验收放行(放行即落地:台账回写 + 出站发送)', + input: {}, + workOrder: 'acceptance', + card: { title: '正式报价单请验收 —— 放行即发出', deliverable: 'formal-quote' }, + deadline: 'P1D', + failure: { retry: { times: 0, backoff: 'PT30S' }, fallback: { kind: 'blocked' } }, + }, + ], + parallelGroups: [], + }, + skills: [], + viewTemplates: [ + { name: 'quote-preview', html: '

正式报价单

' }, + ], + cardSchemas: {}, + distillHooks: [{ on: 'terminal', prompt: '归纳本单议价的经验:客户的还价幅度、成交与否的关键因素。' }], + }, + + samples: [ + { + name: '车规 Analog 报价', + input: { customerCode: 'C001', items: [{ pn: 'LM358DR', quotedPrice: 1.95 }] }, + expect: { ports: ['won'] }, + }, + ], + + entry: { file: 'index.js', checksum: 'dev-entry-quote-negotiate' }, +}; diff --git a/activities/quote-pricing/package.json b/activities/quote-pricing/package.json new file mode 100644 index 0000000..ede96b3 --- /dev/null +++ b/activities/quote-pricing/package.json @@ -0,0 +1 @@ +{ "name": "@activities/quote-pricing", "version": "0.1.0", "private": true, "type": "module", "exports": { ".": "./src/index.ts" } } diff --git a/activities/quote-pricing/src/index.ts b/activities/quote-pricing/src/index.ts new file mode 100644 index 0000000..04bbb8a --- /dev/null +++ b/activities/quote-pricing/src/index.ts @@ -0,0 +1,80 @@ +/** + * 统一报价 A4 · 成本定价 —— 活动包代码入口(ADR-004)。 + * + * flow 活动:下一步由步序声明给定。本文件只做声明装不下的两件事 —— + * 视图流控,与「结论不可静默覆写」的呈现:P-02 拦下的条目必须显式呈现给人。 + */ +import { defineActivity } from '@sdk'; +import type { ActivityBase, ActivityOutcome } from '@sdk'; + +const DRAFT = 'quote_pricing.draft'; + +export default defineActivity({ + name: 'quote-pricing', + paradigm: 'flow', + + async run(base: ActivityBase): Promise { + const items = await base.ledger.read(DRAFT); + const priced = items.filter((r) => typeof r['quoted_price'] === 'number'); + // 底价门禁 P-02 拦下的条目 —— DMN 结论是**约束性输入**,不得静默覆写 + const blocked = items.filter((r) => String(r['disposition'] ?? '').includes('拦截')); + + await base.interaction.pushView([ + { + t: 'kv', + title: '定价概览', + items: [ + { k: '条目', v: `${items.length} 条` }, + { k: '已定价', v: `${priced.length} 条` }, + { k: '底价门禁拦下', v: `${blocked.length} 条` }, + ], + }, + { + t: 'table', + title: '报价草案', + cols: ['PN', '拟报单价', '毛利率', '偏离度', '门禁处置'], + rows: items.map((r) => [ + String(r['pn'] ?? ''), + fmt(r['quoted_price']), + pct(r['margin']), + pct(r['deviation']), + String(r['disposition'] ?? '待判'), + ]), + linkDonut: { + col: 4, + title: '门禁分布', + map: [ + { match: '直接放行', label: '直接放行', tone: 'ok' }, + { match: 'PM', label: 'PM 附理由', tone: 'warn' }, + { match: '拦截', label: '拦截', tone: 'danger' }, + ], + }, + }, + ]); + + if (priced.length < items.length) { + await base.interaction.say(`还有 ${items.length - priced.length} 条未定价,继续按利润模型 P-01 求值。`, 'conclusion'); + return { kind: 'await', reason: '等待定价步完成' }; + } + + if (blocked.length > 0) { + // 超出授权边界 → 走「人 · 决策」,不自行破线 + await base.interaction.say( + `${blocked.length} 条低于底价 20% 以上,已被底价门禁 P-02 拦下 —— 需要人裁决回调还是注明理由。`, + 'criterion', + ); + return { kind: 'await', reason: '等待超限条目的人裁决' }; + } + + await base.interaction.say(`${items.length} 条已全部定价且过底价门禁,可提交审批。`, 'criterion'); + return { kind: 'submit', deliverable: 'quote-draft', rationale: '全条目带偏离度,底价门禁全过' }; + }, +}); + +function fmt(value: unknown): string { + return typeof value === 'number' ? value.toFixed(2) : '—'; +} + +function pct(value: unknown): string { + return typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : '—'; +} diff --git a/activities/quote-pricing/src/manifest.ts b/activities/quote-pricing/src/manifest.ts new file mode 100644 index 0000000..56865ce --- /dev/null +++ b/activities/quote-pricing/src/manifest.ts @@ -0,0 +1,242 @@ +/** + * 活动包清单 —— 统一报价 A4 · 成本定价。 + * + * 业务素材:docs/MVP示例工作流.html §1.2(S1 取价基准 → S2 逐条定价 → S3 底价自检)。 + * README《已裁定的落地决策》③:**A4 = flow** —— 取价、查表定价、自检的判断 + * **全部装进 DMN 决策表确定性求值**;一旦出现「由 AI 决定怎么办」,按 AM 2.1 上升。 + */ +import type { ActivityManifest, DmnModel } from '@contracts'; +import { activityIdSchema } from '@contracts'; + +const DOMAIN = 'quote_pricing'; +const ACTIVITY_ID = activityIdSchema.parse('quote-pricing'); + +/** + * 利润模型 P-01 —— 品牌 × 类型 × 客户等级 × 数量档 → 目标毛利。 + * 「经验」段落不入决策表(那是技能 / 活动记忆种子:载方法不载权力)。 + */ +export const P01_DMN: DmnModel = { + drd: [ + { decision: 'p01-margin', requires: [], inputs: ['customerGrade', 'materialType', 'volumeTier'] }, + { decision: 'p02-floor', requires: ['p01-margin'], inputs: ['quotedPrice', 'floorPrice'] }, + ], + tables: [ + { + id: 'p01-margin', + label: '利润模型 P-01', + hitPolicy: 'FIRST', + inputs: [ + { name: 'customerGrade', expression: 'customerGrade' }, + { name: 'materialType', expression: 'materialType' }, + { name: 'volumeTier', expression: 'volumeTier' }, + ], + outputs: [{ name: 'marginLow' }, { name: 'marginHigh' }], + rules: [ + { id: 'p01-1', when: ['"战略客户"', '"A"', '"大批量"'], then: [0.08, 0.1], annotation: '战略客户 A 类标准件大批量 8%–10%' }, + { id: 'p01-2', when: ['"普通客户"', '"A"', '-'], then: [0.12, 0.15], annotation: '普通客户 A 类标准件 12%–15%' }, + { id: 'p01-3', when: ['-', '"B"', '-'], then: [0.15, 0.2], annotation: 'B 类波动件 15%–20%' }, + { id: 'p01-4', when: ['-', '"C"', '-'], then: [0.2, 0.5], annotation: 'C 类替代/EOL ≥20% 或一事一议' }, + { id: 'p01-default', when: ['-', '-', '-'], then: [0.12, 0.15], annotation: '兜底按普通客户标准件' }, + ], + }, + { + /** 底价门禁 P-02 —— 偏离底价 ±20% 即止 */ + id: 'p02-floor', + label: '底价门禁 P-02', + hitPolicy: 'FIRST', + inputs: [{ name: 'deviation', expression: 'deviation' }], + outputs: [{ name: 'disposition' }, { name: 'passable' }], + rules: [ + { id: 'p02-1', when: ['>= 0'], then: ['直接放行', true], annotation: '≥底价 → 直接放行' }, + { id: 'p02-2', when: ['[-0.20..0)'], then: ['PM 附理由放行', true], annotation: '低于底价 ≤20% → PM 附理由' }, + { id: 'p02-3', when: ['< -0.20'], then: ['拦截 · BOSS 拍板', false], annotation: '低于底价 >20% → 拦截' }, + ], + }, + ], +}; + +export const manifest: ActivityManifest = { + identity: { + activityId: ACTIVITY_ID, + name: 'A4 · 成本定价', + packageVersion: '0.1.0', + category: '统一报价', + paradigm: 'flow', + sdkVersion: '0.1.0-m5', + checksum: 'dev-checksum-quote-pricing', + }, + + contract: { + activityId: ACTIVITY_ID, + version: '0.1.0', + input: { + data: { + type: 'object', + required: ['customerCode', 'records'], + properties: { + customerCode: { type: 'string' }, + records: { type: 'array' }, + // B/C 类由 A3/A2 交回的底价与替代方案;A 类直通时为空 + floorPrices: { type: 'array' }, + }, + }, + messageAllowed: true, + }, + output: { + mandatory: [ + { + name: 'draft', + payload: { + type: 'object', + required: ['items'], + properties: { items: { type: 'array' } }, + }, + description: '报价草案(逐条带偏离度)', + }, + ], + selective: [], + }, + requiredDeliverables: [{ key: 'quote-draft', label: '报价草案(全条目带偏离度)' }], + acceptanceCriteria: [ + { key: 'all-priced', label: '每条都有拟报单价与毛利率', level: 'L1', predicate: 'unpriced = 0' }, + // 底价门禁沉为 L2 机检 —— 「约束力收缩」的终点 + { key: 'floor-gate', label: '偏离底价 ≤±20%,超限者已回调或注明理由', level: 'L2', modelRef: 'p02-floor' }, + { key: 'pm-release', label: 'BD 放行', level: 'L5' }, + ], + prohibitions: [ + { key: 'no-silent-override', statement: '不得静默绕开 P-02 的结论;要破线只能走「人 · 决策」' }, + { key: 'no-stale-floor', statement: '底价超一周未更新的,先刷底价再判' }, + ], + authorization: { + discretion: [{ key: 'margin-band', statement: '在 P-01 给出的毛利区间内自决;出区间必须调人决策' }], + preauthorizedActions: [], + humanCallBudget: 2, + }, + resources: { + tools: [{ name: 'crm.history-price-read' }], + skills: [], + models: ['quote-extractor'], + roles: ['BD'], + budget: { steps: 60, tokens: 150_000, activeMinutes: 120, humanCalls: 2 }, + }, + }, + + declarations: { + models: ['quote-extractor'], + tools: [{ name: 'crm.history-price-read' }], + ledger: [ + { + domain: DOMAIN, + object: 'draft', + label: '报价草案', + fields: [ + { name: 'pn', type: 'text', primaryKey: true, masked: false, label: 'PN' }, + { name: 'quoted_price', type: 'number', primaryKey: false, masked: false, label: '拟报单价' }, + { name: 'margin', type: 'number', primaryKey: false, masked: false, label: '毛利率' }, + { name: 'deviation', type: 'number', primaryKey: false, masked: false, label: '偏离度' }, + { name: 'disposition', type: 'text', primaryKey: false, masked: false, label: '门禁处置' }, + ], + }, + ], + listeners: [ + { + origin: 'static', + eventType: 'human', + keyFilter: { kind: 'decision' }, + semantic: 'complete-step', + deadline: 'PT4H', + escalation: ['nudge', 'escalate'], + }, + ], + // SLA <2h(MVP示例 §1.2 留痕 · SLA) + harness: { + memoryWindow: 20, + stallAfter: 'PT2H', + nudge: [{ after: 'PT1H', action: 'nudge' }], + retry: { times: 2, backoff: 'PT30S' }, + }, + }, + + assets: { + businessModel: { + paradigm: 'flow', + steps: [ + { + kind: 'tool', + name: 'S1_basis', + label: 'S1 取价基准', + // Type A 取历史价近期价;B/C 取供应商底价表(C 类参考替代对标表) + input: { pn: 'pn' }, + output: { domain: DOMAIN, object: 'draft', fields: { deviation: 'deviation' } }, + tool: 'crm.history-price-read', + failure: { retry: { times: 2, backoff: 'PT1M' }, fallback: { kind: 'human', workOrder: 'execution' } }, + }, + { + kind: 'pure-tool', + name: 'S2_price', + label: 'S2 逐条定价(DMN · 利润模型 P-01)', + input: { customerGrade: 'customerGrade', materialType: 'materialType', volumeTier: 'volumeTier' }, + output: { domain: DOMAIN, object: 'draft', fields: { margin: 'marginLow', quoted_price: 'quotedPrice' } }, + tool: 'quote-pricing.margin', + failure: { retry: { times: 1, backoff: 'PT10S' }, fallback: { kind: 'blocked' } }, + }, + { + kind: 'pure-tool', + name: 'S3_floor_gate', + label: 'S3 底价自检(DMN · 底价门禁 P-02)', + input: { deviation: 'deviation' }, + output: { domain: DOMAIN, object: 'draft', fields: { disposition: 'disposition' } }, + tool: 'quote-pricing.floor-gate', + failure: { retry: { times: 1, backoff: 'PT10S' }, fallback: { kind: 'blocked' } }, + }, + { + kind: 'human', + name: 'S4_decide_breach', + label: '超限条目:调人决策(回调还是注明理由)', + // 只有门禁不过才调人 —— 条件必谓词,零 LLM + when: 'breached > 0', + input: {}, + workOrder: 'execution', + card: { title: '有条目低于底价 20% 以上,请裁决', fields: ['disposition', 'reason'] }, + deadline: 'PT4H', + failure: { retry: { times: 0, backoff: 'PT30S' }, fallback: { kind: 'blocked' } }, + }, + { + kind: 'human', + name: 'S5_release', + label: 'S5 报价草案验收放行', + input: {}, + workOrder: 'acceptance', + card: { title: '报价草案(全条目带偏离度)请验收', deliverable: 'quote-draft' }, + deadline: 'P1D', + failure: { retry: { times: 0, backoff: 'PT30S' }, fallback: { kind: 'blocked' } }, + }, + ], + parallelGroups: [], + }, + skills: [], + viewTemplates: [ + { + name: 'pricing-summary', + html: '

报价草案

已定价 条

', + }, + ], + cardSchemas: {}, + distillHooks: [ + { + on: 'terminal', + prompt: '归纳本单定价的经验:哪些组合的毛利档被人回调过、底价门禁拦下的形态、破线的理由。', + }, + ], + }, + + samples: [ + { + name: '战略客户 A 类大批量', + input: { customerCode: 'C001', records: [{ pn: 'LM358DR', type: 'A' }] }, + expect: { ports: ['draft'] }, + }, + ], + + entry: { file: 'index.js', checksum: 'dev-entry-quote-pricing' }, +}; diff --git a/activities/quote-sourcing/package.json b/activities/quote-sourcing/package.json new file mode 100644 index 0000000..8b60891 --- /dev/null +++ b/activities/quote-sourcing/package.json @@ -0,0 +1 @@ +{ "name": "@activities/quote-sourcing", "version": "0.1.0", "private": true, "type": "module", "exports": { ".": "./src/index.ts" } } diff --git a/activities/quote-sourcing/src/case-model.ts b/activities/quote-sourcing/src/case-model.ts new file mode 100644 index 0000000..df3af27 --- /dev/null +++ b/activities/quote-sourcing/src/case-model.ts @@ -0,0 +1,120 @@ +/** + * A3 渠道寻源的案例模型 —— **双表示同版本**:CMMN XML(机器面)与案例说明书(叙事面)。 + * 「说明书是 XML 的叙事投影,迭代时一起放行」(AM 3.1)。 + */ + +export const CMMN_XML = ` + + + + + + + + + + create + + + update + needNewQuote = true + + + update + channelsPicked >= 2 + + + create + + + create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + P4D + + + P7D + + + +`; + +export const NARRATIVE = `§0 开案:本案例覆盖四种询价场景 —— BOM早期、BOM后期、现货询价、样品询价。 +场景不同,供应商选择尺度与价格验证规则各异,但都遵循同一主线: +PM 提交询价请求 → 查历史报价判定可否直采 →(须询价时)按场景圈渠道 → 发询验证 → 填入寻源比价表反馈。 + +S1 接需核史:系统带出在供供应商与历史报价。先核历史,按场景规则逐 PN 判定是否可直接采用 —— +可直采则跳过询价直接进入反馈交付;须新询价则进入选渠阶段。 + · 查历史报价:未达 3 次询价但有效期已过的,标记须重询。 + · 判定采用策略:BOM早期有效期内直采、过期浮动≤10%直采、10-20%取均价、>20%重询; + BOM后期历史最低(≥3次)直采,否则降 20% 谈;现货/样品一律重询。 + +S2 选渠定策:BOM早期/样品渠道可放宽;BOM后期按主→备选→贸易商顺序圈 2~3 家,贸易商尽量不用; +现货仅选有库存且可提供仓库实拍的供应商。渠道资质核实是「看情况」的裁量项。 + +S3 发询比价:同一料所有渠道一次发齐;PN/数量/目标价/回价时限写死在询价里。 +回价逐单登记,一一对应不可缺项。价格验证因场景而异。回价异常或未应答则追价补询(裁量项)。 + +S4 反馈交付:确认报价/LT/SPQ/有效期逐项填入寻源比价表,供 PM 直接查阅。 +现货/样品场景多一步下单与跟踪(裁量项)。 + +全程随时可做:知识入库 —— 回价与成交沉淀历史价格情报,渠道表现回写供应商渠道目录。 + +§Z 结案:必做的事都办完、没有进行中的事,自动算结案(CMMN AutoComplete)。 +寻源比价表交付 PM 即结案 —— 每询一轮,行情底账厚一层。`; diff --git a/activities/quote-sourcing/src/index.ts b/activities/quote-sourcing/src/index.ts new file mode 100644 index 0000000..4f4584d --- /dev/null +++ b/activities/quote-sourcing/src/index.ts @@ -0,0 +1,59 @@ +/** + * 统一报价 A3 · 渠道寻源 —— 活动包代码入口(ADR-004)。 + * + * **loop 活动**:下一步由 Agent 在案例模型的结构上临场决断,引擎只推进到 Enabled 为止。 + * 本文件只做视图流控 —— 把阶段、里程碑与比价进展摆给人看。 + */ +import { defineActivity } from '@sdk'; +import type { ActivityBase, ActivityOutcome } from '@sdk'; + +const QUOTES = 'quote_sourcing.supplier_quote'; +const COMPARE = 'quote_sourcing.compare_table'; + +export default defineActivity({ + name: 'quote-sourcing', + paradigm: 'loop', + + async run(base: ActivityBase): Promise { + const quotes = await base.ledger.read(QUOTES); + const compare = await base.ledger.read(COMPARE); + const suppliers = new Set(quotes.map((q) => String(q['supplier'] ?? ''))); + + await base.interaction.pushView([ + { + t: 'kv', + title: '寻源进展', + items: [ + { k: '场景', v: String(base.contract.data['scenario'] ?? '') }, + { k: '已圈渠道', v: `${suppliers.size} 家` }, + { k: '已收回价', v: `${quotes.length} 单` }, + { k: '比价表', v: compare.length > 0 ? '已填' : '未填' }, + ], + }, + { + t: 'table', + title: '供应商回价', + cols: ['供应商', '回价', 'MOQ', '交期', '渠道等级'], + rows: quotes.map((q) => [ + String(q['supplier'] ?? ''), + String(q['price'] ?? '—'), + String(q['moq'] ?? '—'), + String(q['lead_time'] ?? '—'), + String(q['grade'] ?? '—'), + ]), + }, + ]); + + if (compare.length === 0) { + // 交集为空即断点 —— 由引擎判定、Agent 定夺调人还是立监听,这里不代它决定 + await base.interaction.say( + suppliers.size === 0 ? '尚未圈定渠道,先按场景定策。' : `已收 ${quotes.length} 单回价,待填寻源比价表。`, + 'conclusion', + ); + return { kind: 'await', reason: '寻源比价表未交付' }; + } + + await base.interaction.say('寻源比价表已填齐,可交回 PM。', 'criterion'); + return { kind: 'submit', deliverable: 'compare-table', rationale: '每料有有效报价或明确无货' }; + }, +}); diff --git a/activities/quote-sourcing/src/manifest.ts b/activities/quote-sourcing/src/manifest.ts new file mode 100644 index 0000000..4c6b413 --- /dev/null +++ b/activities/quote-sourcing/src/manifest.ts @@ -0,0 +1,187 @@ +/** + * 活动包清单 —— 统一报价 A3 · 渠道寻源(**案例活动 · loop**)。 + * + * 业务素材:docs/MVP示例工作流.html §1.5。按 README《归一化对照表》映射: + * 案例图 → CMMN XML;案例说明书 → 同版本叙事面; + * `!必做` → entryCriterion 常项;`看情况` → discretionary(planningTable); + * `#可反复` → repetitionRule;`▶需拍板` → manualActivation + 放行; + * `⏱时限/回价到期` → 时间监听(**时限必配**)。 + */ +import type { ActivityManifest, DmnModel } from '@contracts'; +import { activityIdSchema } from '@contracts'; +import { CMMN_XML, NARRATIVE } from './case-model.ts'; + +const DOMAIN = 'quote_sourcing'; +const ACTIVITY_ID = activityIdSchema.parse('quote-sourcing'); + +/** 采用策略 —— 「能算的不问 LLM」:场景 × 历史情形 → 直采 / 重询 */ +export const STRATEGY_DMN: DmnModel = { + drd: [{ decision: 'sourcing-strategy', requires: [], inputs: ['scenario', 'priceDrift', 'quoteCount'] }], + tables: [ + { + id: 'sourcing-strategy', + label: '采用策略判定', + hitPolicy: 'FIRST', + inputs: [ + { name: 'scenario', expression: 'scenario' }, + { name: 'priceDrift', expression: 'priceDrift' }, + { name: 'quoteCount', expression: 'quoteCount' }, + ], + outputs: [{ name: 'strategy' }, { name: 'needNewQuote' }], + rules: [ + { id: 'st-spot', when: ['"现货","样品"', '-', '-'], then: ['一律重询', true] }, + { id: 'st-early-direct', when: ['"BOM早期"', '<= 0.10', '-'], then: ['直采', false] }, + { id: 'st-early-avg', when: ['"BOM早期"', '[0.10..0.20]', '-'], then: ['取均价', false] }, + { id: 'st-late-direct', when: ['"BOM后期"', '-', '>= 3'], then: ['历史最低直采', false] }, + { id: 'st-default', when: ['-', '-', '-'], then: ['重询', true] }, + ], + }, + ], +}; + +export const manifest: ActivityManifest = { + identity: { + activityId: ACTIVITY_ID, + name: 'A3 · 渠道寻源', + packageVersion: '0.1.0', + category: '统一报价', + paradigm: 'loop', + sdkVersion: '0.1.0-m5', + checksum: 'dev-checksum-quote-sourcing', + }, + + contract: { + activityId: ACTIVITY_ID, + version: '0.1.0', + input: { + data: { + type: 'object', + required: ['pn', 'scenario'], + properties: { + pn: { type: 'string' }, + scenario: { type: 'string' }, + quantity: { type: 'integer' }, + targetPrice: { type: 'number' }, + }, + }, + messageAllowed: true, + messageHint: '急料、客户特殊要求写这里', + }, + output: { + mandatory: [ + { + name: 'compare', + payload: { type: 'object', required: ['rows'], properties: { rows: { type: 'array' } } }, + description: '寻源比价表(多渠道横比定底)', + }, + ], + selective: [], + }, + requiredDeliverables: [{ key: 'compare-table', label: '寻源比价表' }], + acceptanceCriteria: [ + { key: 'each-has-quote', label: '每料有有效报价或明确无货', level: 'L2', predicate: 'unquoted = 0' }, + { key: 'channels-enough', label: 'BOM后期每料 2~3 家渠道', level: 'L2', predicate: 'channelsPicked >= 2' }, + { key: 'cross-check', label: '价格验证按场景规则做过', level: 'L3' }, + { key: 'prm-release', label: '采购放行', level: 'L5' }, + ], + prohibitions: [ + { key: 'no-stockless-trader', statement: '现货场景不得选无库存转单商' }, + { key: 'no-unverified', statement: '不实回价或远低行情的,必须换渠道补询,不得直接采用' }, + ], + authorization: { + discretion: [{ key: 'channel-band', statement: '按场景放宽或收紧渠道尺度;贸易商尽量不用' }], + preauthorizedActions: [{ tool: 'mail.send', operation: 'inquiry', limit: '询价模板' }], + humanCallBudget: 8, + }, + resources: { + tools: [{ name: 'mail.send' }, { name: 'crm.history-price-read' }], + skills: [], + models: ['quote-extractor'], + roles: ['PRM'], + budget: { steps: 120, tokens: 300_000, activeMinutes: 480, humanCalls: 8 }, + }, + }, + + declarations: { + models: ['quote-extractor'], + tools: [{ name: 'mail.send' }, { name: 'crm.history-price-read' }], + ledger: [ + { + domain: DOMAIN, + object: 'supplier_quote', + label: '供应商回价单', + fields: [ + { name: 'pn', type: 'text', primaryKey: true, masked: false }, + { name: 'supplier', type: 'text', primaryKey: true, masked: false, label: '供应商' }, + { name: 'price', type: 'number', primaryKey: false, masked: false, label: '回价' }, + { name: 'moq', type: 'integer', primaryKey: false, masked: false, label: 'MOQ' }, + { name: 'lead_time', type: 'text', primaryKey: false, masked: false, label: '交期' }, + { name: 'valid_until', type: 'date', primaryKey: false, masked: false, label: '有效期' }, + { name: 'grade', type: 'text', primaryKey: false, masked: false, label: '渠道等级' }, + ], + }, + { + domain: DOMAIN, + object: 'compare_table', + label: '寻源比价表', + fields: [ + { name: 'pn', type: 'text', primaryKey: true, masked: false }, + { name: 'supplier', type: 'text', primaryKey: false, masked: false }, + { name: 'price', type: 'number', primaryKey: false, masked: false }, + { name: 'conclusion', type: 'text', primaryKey: false, masked: false, label: '结论' }, + ], + }, + ], + listeners: [ + { + // 回价到期:临过期提醒复核确认,过期触发重询 —— 时限必配 + origin: 'static', + eventType: 'data', + keyFilter: { kind: 'supplier-quote' }, + semantic: 'observe', + deadline: 'P4D', + escalation: ['nudge', 'escalate'], + }, + { + origin: 'static', + eventType: 'time', + keyFilter: { kind: 'quote-expiry' }, + semantic: 'observe', + deadline: 'P7D', + escalation: ['nudge', 'reroute'], + }, + ], + // 按场景时限:BOM早期/现货 1~4 日、样品 1~3 日、BOM后期 3~9 日 —— 取最宽做停滞阈值 + harness: { + memoryWindow: 30, + stallAfter: 'P2D', + nudge: [{ after: 'P1D', action: 'nudge' }], + retry: { times: 2, backoff: 'PT5M' }, + }, + }, + + assets: { + businessModel: { + paradigm: 'loop', + cmmnXml: CMMN_XML, + // 双表示同版本:XML 是机器面,说明书是叙事面 —— 不允许分叉 + narrative: NARRATIVE, + dmn: STRATEGY_DMN, + }, + skills: [], + viewTemplates: [ + { name: 'sourcing-board', html: '

寻源看板

' }, + ], + cardSchemas: {}, + distillHooks: [ + { on: 'milestone', milestone: 'M_quotes', prompt: '归纳各渠道的回价节奏与配合度。' }, + { on: 'terminal', prompt: '归纳本单寻源:哪些渠道靠谱、哪些场景的价格验证规则该收紧。' }, + ], + }, + + samples: [ + { name: 'BOM后期询价', input: { pn: 'LM358DR', scenario: 'BOM后期', quantity: 5000 }, expect: { ports: ['compare'] } }, + ], + + entry: { file: 'index.js', checksum: 'dev-entry-quote-sourcing' }, +}; diff --git a/apps/api/src/app/main.ts b/apps/api/src/app/main.ts index 8ae6ece..84332ac 100644 --- a/apps/api/src/app/main.ts +++ b/apps/api/src/app/main.ts @@ -8,6 +8,7 @@ import { createContainer } from './container.ts'; import { createServer } from './server.ts'; import { createConsumers } from './workers/consumers.ts'; import { startDispatcher } from './workers/dispatcher.ts'; +import { startTaskAdvancer } from './workers/task-advancer.ts'; export async function boot(): Promise { const config = loadConfig(); @@ -17,6 +18,9 @@ export async function boot(): Promise { // 派发器:投递记录即队列,按目标 ID 取 advisory lock 串行消费(ADR-008) const dispatcher = startDispatcher({ container, consumers: createConsumers() }, config.dispatchIntervalMs); + // 过程在后端:运行中的任务由推进器一拍一拍推,不依赖浏览器在线 + const advancer = startTaskAdvancer({ container }, config.dispatchIntervalMs); + const app = createServer(container); serve({ fetch: app.fetch, port: config.port }, (info) => { process.stdout.write(`JCAI api · http://localhost:${info.port} · env=${config.nodeEnv}\n`); @@ -24,6 +28,7 @@ export async function boot(): Promise { const shutdown = async (): Promise => { dispatcher.stop(); + advancer.stop(); await container.close(); process.exit(0); }; diff --git a/apps/api/src/app/seed-quote.ts b/apps/api/src/app/seed-quote.ts index 5a528d2..c48fa53 100644 --- a/apps/api/src/app/seed-quote.ts +++ b/apps/api/src/app/seed-quote.ts @@ -50,6 +50,37 @@ const HISTORY_TOOL = { connectionKeys: ['endpoint'], }; +/** 出站邮件 —— **写类**:过程中登记为动作意向,放行后由系统执行落地 */ +const MAIL_TOOL = { + ...HISTORY_TOOL, + name: 'mail.send', + description: '发出邮件(报价单 / 询价函 / 催办):写类动作,放行时才真正触达世界', + input: { + type: 'object', + required: ['to', 'subject'], + properties: { to: { type: 'string' }, subject: { type: 'string' }, body: { type: 'string' } }, + }, + output: { type: 'object', properties: { queued: { type: 'boolean' } } }, + effect: 'write' as const, + idempotent: true, + connectionKeys: ['endpoint'], +}; + +/** 纯工具:无外效应、无连接配置、活动私有作用域 */ +function pureTool(name: string, description: string, ownerActivityId: string, required: string[]) { + return { + ...HISTORY_TOOL, + name, + description, + input: { type: 'object', required, properties: Object.fromEntries(required.map((k) => [k, {}])) }, + output: { type: 'object', properties: {} }, + effect: 'read' as const, + connectionKeys: [], + pure: true, + ownerActivityId, + }; +} + /** 打标纯工具:三分类规则 P-03 的确定性求值 —— 无外效应,活动私有作用域 */ const CLASSIFY_TOOL = { ...HISTORY_TOOL, @@ -84,28 +115,77 @@ export async function seedQuote(container: Container): Promise { log('① LLM 实例已绑定:quote-extractor'); /* ② 工具注册两审 + 白名单 */ - for (const contract of [HISTORY_TOOL, CLASSIFY_TOOL]) { + const tools = [ + HISTORY_TOOL, + MAIL_TOOL, + CLASSIFY_TOOL, + pureTool('quote-pricing.margin', '利润模型 P-01 的确定性求值:客户等级×物料类型×数量档 → 目标毛利区间', 'quote-pricing', ['customerGrade']), + pureTool('quote-pricing.floor-gate', '底价门禁 P-02 的确定性求值:偏离底价 ±20% 即止', 'quote-pricing', ['deviation']), + pureTool('quote-archive.profile', '客户画像更新:把成交行为写成标签,供 P-01 的客户等级因子取用', 'quote-archive', ['customerCode']), + pureTool('quote-archive.landing-rate', '落地率统计:放行通过的报价 ÷ 发出的报价', 'quote-archive', []), + ]; + for (const contract of tools) { const verdict = await container.toolbox.register({ contract, - samples: [{ input: { pn: 'LM358DR', historyDays: 30 }, expectShape: { type: 'object' } }], + samples: [ + { + input: { pn: 'LM358DR', historyDays: 30, customerGrade: '普通客户', deviation: 0, to: 'x@y.com', subject: 't', customerCode: 'C001' }, + expectShape: { type: 'object' }, + }, + ], ...(contract.connectionKeys.length > 0 ? { connectionValues: { endpoint: 'replay://crm' } } : {}), }); if (!verdict.accepted) { log(' 工具 ' + contract.name + ' 未过两审:' + verdict.staticFindings.map((f) => f.message).join('; ')); } } + // 白名单按活动逐个给 —— 授权在白名单与契约,不在活动代码 await container.toolbox.setAllowlist('quote-intake', [HISTORY_TOOL.name, CLASSIFY_TOOL.name]); - log('② 功能工具已注册并入白名单'); + await container.toolbox.setAllowlist('quote-pricing', [HISTORY_TOOL.name]); + await container.toolbox.setAllowlist('quote-negotiate', [HISTORY_TOOL.name, MAIL_TOOL.name]); + await container.toolbox.setAllowlist('quote-archive', []); + await container.toolbox.setAllowlist('quote-sourcing', [HISTORY_TOOL.name, MAIL_TOOL.name]); + await container.toolbox.setAllowlist('quote-alternative', [HISTORY_TOOL.name]); + log('② 功能工具已注册并入白名单(逐活动授权)'); /* ③ 经安装通道装入活动包 —— 静态审 + 样例集(首装无历史,免回放审) */ const root = activitiesRoot(); - const manifestRaw = JSON.parse(await readFile(join(root, 'quote-intake/dist/manifest.json'), 'utf8')); - const manifest = activityManifestSchema.parse(manifestRaw); - const artifact = await readFile(join(root, 'quote-intake/dist/index.js'), 'utf8'); - const verdict = await container.registry.install(manifest, artifact); - log('③ 活动包已安装:' + manifest.identity.name + '(静态审 ' + String(verdict.staticFindings.length) + ' 条提示)'); + const packages = [ + 'quote-intake', + 'quote-pricing', + 'quote-negotiate', + 'quote-archive', + 'quote-sourcing', + 'quote-alternative', + ]; + for (const dir of packages) { + const manifestRaw = JSON.parse(await readFile(join(root, dir, 'dist/manifest.json'), 'utf8')); + const manifest = activityManifestSchema.parse(manifestRaw); + const artifact = await readFile(join(root, dir, 'dist/index.js'), 'utf8'); + const verdict = await container.registry.install(manifest, artifact); + log(' 装入 ' + manifest.identity.name + '(' + manifest.identity.paradigm + ',静态审 ' + String(verdict.staticFindings.length) + ' 条提示)'); + } + log('③ 六个活动包已经安装通道装入'); + + /* ④ 编排「统一报价」流程包 v1 并发布 —— 七节点(SOP×5 + Case×2)+ 网关 + 审批点 */ + const activityNode = ( + id: string, + label: string, + activityId: string, + position: string, + failure: 'terminate' | 'tolerate', + col: number, + row = 0, + ) => ({ + id, + kind: 'activity' as const, + label, + activityId, + owner: { position, strategy: 'sole' as const }, + failure: { kind: failure }, + layout: { row, col }, + }); - /* ④ 编排「统一报价」流程包 v1 并发布 */ const pkg = processPackageSchema.parse({ id: 'unified-quote', name: '统一报价', @@ -117,21 +197,33 @@ export async function seedQuote(container: Container): Promise { required: ['customerCode', 'rfqRef'], properties: { customerCode: { type: 'string' }, rfqRef: { type: 'string' }, subject: { type: 'string' } }, }, - output: { type: 'object', properties: { records: { type: 'array' } } }, + output: { type: 'object', properties: { landingRate: { type: 'number' } } }, }, nodes: [ { id: 'start', kind: 'start', label: '客户RFQ询价', layout: { row: 0, col: 0 } }, + activityNode('A1', 'A1 RFQ需求分析', 'quote-intake', 'BD', 'terminate', 1), + // 已裁定 ②:G2 料号分流 = **并行网关**,三道并行、每边载荷按 Type 过滤 + { id: 'G2', kind: 'gateway', label: 'G2 料号分流', gateway: 'parallel', mode: 'fork', layout: { row: 0, col: 2 } }, + // 某类条目为空的分支按「容忍」处置 —— A4 汇合处的必填映射不得依赖可空分支 + activityNode('A3', 'A3 渠道寻源', 'quote-sourcing', 'PRM', 'tolerate', 3, -1), + activityNode('A2', 'A2 替代选型', 'quote-alternative', 'FAE', 'tolerate', 3, 1), + { id: 'G2J', kind: 'gateway', label: 'G2 汇合', gateway: 'parallel', mode: 'join', layout: { row: 0, col: 4 } }, + activityNode('A4', 'A4 成本定价', 'quote-pricing', 'BD', 'terminate', 5), + // 已裁定 ①:A5 定价审批 = **审批点**;G3 审批结果并入驳回走向(驳回 → 回 A4 重开新实例) { - id: 'A1', - kind: 'activity', - label: 'A1 RFQ需求分析', - activityId: 'quote-intake', - owner: { position: 'BD', strategy: 'sole' }, - failure: { kind: 'terminate' }, - message: '真实 RFQ 五花八门,先归一成台账化的统一受理记录,再逐条打标定车道。', - layout: { row: 0, col: 1 }, + id: 'AP', + kind: 'approval', + label: 'AP 定价审批', + approver: { position: 'PM', strategy: 'sole' }, + reject: { kind: 'reopen', nodeId: 'A4', mapping: [] }, + nudge: { deadline: 'PT30M', steps: [{ after: 'PT20M', action: 'nudge' }] }, + layout: { row: 0, col: 6 }, }, - { id: 'end', kind: 'end', label: '归档闭环', layout: { row: 0, col: 2 } }, + activityNode('A6', 'A6 报价议价', 'quote-negotiate', 'BD', 'terminate', 7), + // G4 议价结果 = 异或网关:成交 / 有异议(回边 A4)/ 拒绝超时 + { id: 'G4', kind: 'gateway', label: 'G4 议价结果', gateway: 'exclusive', mode: 'fork', layout: { row: 0, col: 8 } }, + activityNode('A7', 'A7 情报归档', 'quote-archive', 'BD', 'terminate', 9), + { id: 'end', kind: 'end', label: '归档闭环', layout: { row: 0, col: 10 } }, ], edges: [ { @@ -144,7 +236,86 @@ export async function seedQuote(container: Container): Promise { ], reopen: false, }, - { id: 'e-a1-end', from: 'A1', to: 'end', mapping: [], reopen: false }, + { id: 'e-a1-g2', from: 'A1', to: 'G2', mapping: [], label: '统一受理记录', reopen: false }, + + // 三道并行:TYPE-A 直通定价 / TYPE-B 寻源 / TYPE-C 选型 + // TYPE-A 直通:不经活动,直接进汇合 —— A4 因此只有一条并发入边,来源无歧义 + { id: 'e-g2-j', from: 'G2', to: 'G2J', label: 'TYPE-A 直通定价', mapping: [], reopen: false }, + { + id: 'e-g2-a3', + from: 'G2', + to: 'A3', + label: 'TYPE-B 转寻源', + mapping: [ + { target: 'pn', source: { from: 'output-port', port: 'intake', path: 'records' } }, + { target: 'scenario', source: { from: 'constant', value: 'BOM后期' } }, + ], + reopen: false, + }, + { + id: 'e-g2-a2', + from: 'G2', + to: 'A2', + label: 'TYPE-C 转选型', + mapping: [{ target: 'originalPn', source: { from: 'output-port', port: 'intake', path: 'records' } }], + reopen: false, + }, + + // 汇合:容忍分支的输出**不进 A4 的必填映射**(静态校验会拦) + { id: 'e-a3-j', from: 'A3', to: 'G2J', mapping: [], reopen: false }, + { id: 'e-a2-j', from: 'A2', to: 'G2J', mapping: [], reopen: false }, + { + id: 'e-j-a4', + from: 'G2J', + to: 'A4', + mapping: [ + { target: 'customerCode', source: { from: 'initiation', path: 'customerCode' } }, + { target: 'records', source: { from: 'initiation', path: 'records' } }, + ], + reopen: false, + }, + + { id: 'e-a4-ap', from: 'A4', to: 'AP', mapping: [], label: '报价草案提审', reopen: false }, + { + id: 'e-ap-a6', + from: 'AP', + to: 'A6', + label: '通过', + mapping: [ + { target: 'customerCode', source: { from: 'initiation', path: 'customerCode' } }, + { target: 'items', source: { from: 'output-port', port: 'draft', path: 'items' } }, + ], + reopen: false, + }, + + { id: 'e-a6-g4', from: 'A6', to: 'G4', mapping: [], reopen: false }, + { id: 'e-g4-end', from: 'G4', to: 'end', condition: 'outcome = "won"', label: '成交 → 转订单履约', reopen: false }, + // 已裁定 ④:议价回环 = **流程层回边**,人裁决后重开新任务实例 + { + id: 'e-g4-a4', + from: 'G4', + to: 'A4', + condition: 'outcome = "revise"', + label: '有异议 → 返回调整', + mapping: [ + { target: 'customerCode', source: { from: 'initiation', path: 'customerCode' } }, + { target: 'records', source: { from: 'initiation', path: 'records' } }, + ], + reopen: true, + }, + { + id: 'e-g4-a7', + from: 'G4', + to: 'A7', + condition: 'outcome = "lost"', + label: '拒绝/超时 → 情报归档', + mapping: [ + { target: 'customerCode', source: { from: 'initiation', path: 'customerCode' } }, + { target: 'quoteNo', source: { from: 'initiation', path: 'rfqRef' } }, + ], + reopen: false, + }, + { id: 'e-a7-end', from: 'A7', to: 'end', mapping: [], reopen: false }, ], variables: [], }); @@ -155,7 +326,7 @@ export async function seedQuote(container: Container): Promise { log(' 闭合校验未过,不得发布:' + report.violations.map((v) => v.message).join('; ')); } else { await container.process.publish(pkg.id, pkg.version); - log('④ 流程包「统一报价」v1 已发布(边映射闭合校验通过)'); + log('④ 流程包「统一报价」v1 已发布 —— 7 节点 + 3 网关 + 1 审批点,边映射闭合校验通过'); } /* 事件触发器「客户RFQ询价」 */ diff --git a/apps/api/src/app/tools/first-party.ts b/apps/api/src/app/tools/first-party.ts index 22952c3..2918c0b 100644 --- a/apps/api/src/app/tools/first-party.ts +++ b/apps/api/src/app/tools/first-party.ts @@ -46,7 +46,72 @@ const classify: ToolHandler = async ({ input }) => { return { ok: false, error: { code: 'no-match', retryable: false, message: '三分类规则无命中行' } }; }; +/** 利润模型 P-01:品牌 × 类型 × 客户等级 × 数量档 → 目标毛利区间 */ +const P01_RULES = [ + { id: 'p01-1', when: ['"战略客户"', '"A"', '"大批量"'], then: { marginLow: 0.08, marginHigh: 0.1 } }, + { id: 'p01-2', when: ['"普通客户"', '"A"', '-'], then: { marginLow: 0.12, marginHigh: 0.15 } }, + { id: 'p01-3', when: ['-', '"B"', '-'], then: { marginLow: 0.15, marginHigh: 0.2 } }, + { id: 'p01-4', when: ['-', '"C"', '-'], then: { marginLow: 0.2, marginHigh: 0.5 } }, + { id: 'p01-default', when: ['-', '-', '-'], then: { marginLow: 0.12, marginHigh: 0.15 } }, +] as const; + +const margin: ToolHandler = async ({ input }) => { + const values = [input['customerGrade'], input['materialType'], input['volumeTier']]; + for (const rule of P01_RULES) { + if (rule.when.every((cell, i) => evaluateUnaryTest(cell, values[i], {}))) { + const base = Number(input['basePrice'] ?? 0); + return { + ok: true, + output: { ...rule.then, rule: rule.id, quotedPrice: Number((base * (1 + rule.then.marginLow)).toFixed(4)) }, + }; + } + } + return { ok: false, error: { code: 'no-match', retryable: false, message: '利润模型无命中行' } }; +}; + +/** 底价门禁 P-02:偏离底价 ±20% 即止 —— 结论是约束性输入,不可静默覆写 */ +const floorGate: ToolHandler = async ({ input }) => { + const deviation = Number(input['deviation'] ?? 0); + if (deviation >= 0) return { ok: true, output: { disposition: '直接放行', passable: true, rule: 'p02-1' } }; + if (deviation >= -0.2) return { ok: true, output: { disposition: 'PM 附理由放行', passable: true, rule: 'p02-2' } }; + return { ok: true, output: { disposition: '拦截 · BOSS 拍板', passable: false, rule: 'p02-3' } }; +}; + +/** 客户画像更新:把行为写成标签,供 P-01 的客户等级因子取用 */ +const profile: ToolHandler = async ({ input }) => { + const reason = String(input['reason'] ?? ''); + const tags: string[] = []; + if (/价|贵|低/.test(reason)) tags.push('价格敏感型'); + if (/快|急/.test(reason)) tags.push('快速决策型'); + if (tags.length === 0) tags.push('待观察'); + return { ok: true, output: { tags: tags.join('/') } }; +}; + +/** 落地率统计:放行通过的报价 ÷ 发出的报价 */ +const landingRate: ToolHandler = async ({ input }) => { + const won = Number(input['won'] ?? 0); + const total = Number(input['total'] ?? 0); + return { + ok: true, + output: { landingRate: total === 0 ? 0 : Number((won / total).toFixed(4)), period: String(input['period'] ?? '') }, + }; +}; + +/** 出站发送 —— 写类:过程中登记为动作意向,放行后由系统执行落地(OS 7.3) */ +const mailSend: ToolHandler = async ({ input, connection }) => { + // 运行时只拿得到申报过的连接目标;真发信由 channel 的出站面承担 + return { + ok: true, + output: { queued: true, to: String(input['to'] ?? ''), via: connection['endpoint'] ?? 'simulated' }, + }; +}; + export const FIRST_PARTY_TOOLS: ReadonlyArray = [ ['crm.history-price-read', historyPriceRead], ['quote-intake.classify', classify], + ['quote-pricing.margin', margin], + ['quote-pricing.floor-gate', floorGate], + ['quote-archive.profile', profile], + ['quote-archive.landing-rate', landingRate], + ['mail.send', mailSend], ]; diff --git a/apps/api/src/app/workers/task-advancer.ts b/apps/api/src/app/workers/task-advancer.ts new file mode 100644 index 0000000..b9d5a3d --- /dev/null +++ b/apps/api/src/app/workers/task-advancer.ts @@ -0,0 +1,63 @@ +/** + * 任务推进器 —— 「过程在后端」的落点(编码规范 §9;语义出处 OS 09)。 + * + * 「环不依赖浏览器在线 —— 负责人关掉页面,活动照常推进」: + * 运行中的任务由本 worker 一拍一拍推,直到进入等待(等人 / 等事件)或收敛终态。 + * 预算与停滞熔断在 `task.tick()` 里**环外先判**,这里不重复把关。 + */ +import { and, eq, sql } from 'drizzle-orm'; +import { taskTable } from '@modules/task'; +import type { Container } from '../container.ts'; + +export type AdvancerOptions = { + readonly container: Container; + /** 一轮最多推几个任务 */ + readonly batchSize?: number; + /** 单个任务一轮最多推几拍 —— 防止一个任务占满 worker */ + readonly maxTicks?: number; +}; + +export async function advanceOnce(options: AdvancerOptions): Promise { + const { container } = options; + const rows = await container.db + .select({ id: taskTable.id }) + .from(taskTable) + .where(and(eq(taskTable.runtime, 'running'), sql`${taskTable.terminal} is null`)) + .limit(options.batchSize ?? 5); + + let advanced = 0; + for (const row of rows) { + for (let tick = 0; tick < (options.maxTicks ?? 3); tick += 1) { + try { + const outcome = await container.task.tick(row.id as never); + advanced += 1; + // 进入等待或终结就停手 —— 挂起在等的任务由事件唤醒,不空转 + if (outcome.task.runtime !== 'running' || outcome.task.terminal !== undefined) break; + if (!outcome.progressed) break; + } catch (error) { + process.stderr.write( + `[task-advancer] ${row.id}:${error instanceof Error ? error.message : String(error)}\n`, + ); + break; + } + } + } + return advanced; +} + +export function startTaskAdvancer(options: AdvancerOptions, intervalMs: number): { stop(): void } { + let stopped = false; + const timer = setInterval(() => { + if (stopped) return; + void advanceOnce(options).catch((error: unknown) => { + process.stderr.write(`[task-advancer] ${error instanceof Error ? error.message : String(error)}\n`); + }); + }, intervalMs); + timer.unref(); + return { + stop() { + stopped = true; + clearInterval(timer); + }, + }; +} diff --git a/apps/api/src/modules/process/internal/domain/closure.ts b/apps/api/src/modules/process/internal/domain/closure.ts index 6553de2..8b4aacd 100644 --- a/apps/api/src/modules/process/internal/domain/closure.ts +++ b/apps/api/src/modules/process/internal/domain/closure.ts @@ -136,11 +136,13 @@ function checkActivityNode( } } - // AND 汇合后的同名字段必须显式指定来源分支,不做隐式合并 - const targets = inbound.flatMap((e) => e.mapping.map((m) => m.target)); + // AND 汇合后的同名字段必须显式指定来源分支,不做隐式合并。 + // 回边(reopen)是**重新入场**不是并发汇合 —— 不参与此判定(OS 03 失败走向 / 议价回环)。 + const concurrent = inbound.filter((e) => !e.reopen); + const targets = concurrent.flatMap((e) => e.mapping.map((m) => m.target)); const seen = new Set(); for (const target of targets) { - if (seen.has(target) && inbound.length > 1) { + if (seen.has(target) && concurrent.length > 1) { out.push({ kind: 'join-ambiguous-source', nodeId: node.id, diff --git a/tools/build-activities.ts b/tools/build-activities.ts index 8e1658a..e09a2ad 100644 --- a/tools/build-activities.ts +++ b/tools/build-activities.ts @@ -12,10 +12,22 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { manifest as quoteIntake } from '../activities/quote-intake/src/manifest.ts'; +import { manifest as quotePricing } from '../activities/quote-pricing/src/manifest.ts'; +import { manifest as quoteNegotiate } from '../activities/quote-negotiate/src/manifest.ts'; +import { manifest as quoteArchive } from '../activities/quote-archive/src/manifest.ts'; +import { manifest as quoteSourcing } from '../activities/quote-sourcing/src/manifest.ts'; +import { manifest as quoteAlternative } from '../activities/quote-alternative/src/manifest.ts'; const root = dirname(dirname(fileURLToPath(import.meta.url))); -const PACKAGES = [{ dir: 'quote-intake', manifest: quoteIntake }] as const; +const PACKAGES = [ + { dir: 'quote-intake', manifest: quoteIntake }, + { dir: 'quote-pricing', manifest: quotePricing }, + { dir: 'quote-negotiate', manifest: quoteNegotiate }, + { dir: 'quote-archive', manifest: quoteArchive }, + { dir: 'quote-sourcing', manifest: quoteSourcing }, + { dir: 'quote-alternative', manifest: quoteAlternative }, +] as const; for (const pkg of PACKAGES) { const base = join(root, 'activities', pkg.dir);