@wanji_dsh/dsh-sales 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/.dsh/skills/wanji-sales-assistant/SKILL.md +28 -3
  2. package/.dsh/skills/wanji-sales-assistant/references/draft-review.md +2 -2
  3. package/.dsh/skills/wanji-sales-assistant/references/wechat-delivery.md +24 -0
  4. package/README.md +24 -4
  5. package/README.zh.md +51 -4
  6. package/dist/client.js +9632 -664
  7. package/dist/host.js +3200 -958
  8. package/dist/types/{agent-evaluators.d.ts → agent-evaluators-v2.d.ts} +17 -3
  9. package/dist/types/agent-knowledge.d.ts +11 -2
  10. package/dist/types/agent.d.ts +21 -8
  11. package/dist/types/commercial-boundary.d.ts +7 -0
  12. package/dist/types/customer-intent.d.ts +49 -0
  13. package/dist/types/customer-materials.d.ts +49 -0
  14. package/dist/types/dialogue-tasks.d.ts +10 -0
  15. package/dist/types/draft-edits.d.ts +7 -0
  16. package/dist/types/evaluation-client.d.ts +2 -6
  17. package/dist/types/fact-proof.d.ts +2 -1
  18. package/dist/types/generation-progress.d.ts +32 -0
  19. package/dist/types/generation-runtime.d.ts +17 -0
  20. package/dist/types/generation-session-route.d.ts +5 -0
  21. package/dist/types/generation-sessions.d.ts +36 -0
  22. package/dist/types/host.d.ts +15 -0
  23. package/dist/types/knowledge-host.d.ts +22 -3
  24. package/dist/types/knowledge-judgment-delivery.d.ts +2 -0
  25. package/dist/types/knowledge-judgments.d.ts +12 -0
  26. package/dist/types/knowledge-privacy.d.ts +2 -0
  27. package/dist/types/knowledge-turns.d.ts +22 -0
  28. package/dist/types/langfuse-config.d.ts +1 -0
  29. package/dist/types/langfuse-outbox.d.ts +10 -2
  30. package/dist/types/material-catalog.d.ts +17 -0
  31. package/dist/types/material-metadata.d.ts +4 -0
  32. package/dist/types/material-reply.d.ts +24 -0
  33. package/dist/types/material-request.d.ts +45 -0
  34. package/dist/types/material-retrieval.d.ts +29 -0
  35. package/dist/types/model.d.ts +23 -2
  36. package/dist/types/open-generation.d.ts +5 -2
  37. package/dist/types/open-review.d.ts +39 -15
  38. package/dist/types/operation-evidence.d.ts +7 -0
  39. package/dist/types/percentage-quote.d.ts +6 -0
  40. package/dist/types/plan-projection.d.ts +2 -0
  41. package/dist/types/product-evidence.d.ts +4 -0
  42. package/dist/types/question-relay.d.ts +24 -0
  43. package/dist/types/question-route.d.ts +4 -0
  44. package/dist/types/question-tracing.d.ts +84 -0
  45. package/dist/types/quote-context.d.ts +9 -5
  46. package/dist/types/response-contract.d.ts +10 -0
  47. package/dist/types/retrieval-queries.d.ts +4 -0
  48. package/dist/types/review-turn.d.ts +6 -0
  49. package/dist/types/sales-context-types.d.ts +15 -0
  50. package/dist/types/semantic-rerank.d.ts +9 -0
  51. package/dist/types/sending-policy.d.ts +2 -0
  52. package/dist/types/server/intent-evaluation.d.ts +27 -0
  53. package/dist/types/server/intent-host.d.ts +17 -0
  54. package/dist/types/stream-preview.d.ts +11 -0
  55. package/dist/types/turn-packet.d.ts +21 -8
  56. package/dist/types/turn-plan.d.ts +19 -7
  57. package/dist/types/update/activity.d.ts +1 -1
  58. package/dist/types/verified-arithmetic.d.ts +5 -0
  59. package/dist/types/voice-examples.d.ts +1 -0
  60. package/dist/types/wechat/cua-approval.d.ts +36 -0
  61. package/dist/types/wechat/cua-sender.d.ts +160 -0
  62. package/dist/types/wechat/cua-vision.d.ts +31 -0
  63. package/dist/types/wechat/delivery.d.ts +47 -0
  64. package/dist/types/wechat/intent-scheduler.d.ts +26 -0
  65. package/dist/types/wechat/repository-client.d.ts +1 -1
  66. package/dist/types/wechat/routes.d.ts +9 -7
  67. package/dist/types/wechat/service.d.ts +8 -3
  68. package/dist/types/wechat/types.d.ts +5 -0
  69. package/dist/types/wechat-draft-input.d.ts +3 -0
  70. package/dist/types/wechat-voice.d.ts +3 -0
  71. package/dist/types/weknora-http.d.ts +8 -0
  72. package/dist/wechat-repository-worker.js +248 -22
  73. package/docs/agent-knowledge-observation.md +58 -0
  74. package/docs/customer-material-retrieval.md +48 -0
  75. package/docs/licenses/ccount@2.0.1.txt +24 -0
  76. package/docs/licenses/character-entities@2.0.2.txt +24 -0
  77. package/docs/licenses/debug@4.4.3.txt +21 -0
  78. package/docs/licenses/decode-named-character-reference@1.3.0.txt +24 -0
  79. package/docs/licenses/dequal@2.0.3.txt +23 -0
  80. package/docs/licenses/devlop@1.1.0.txt +24 -0
  81. package/docs/licenses/escape-string-regexp@5.0.0.txt +11 -0
  82. package/docs/licenses/longest-streak@3.1.0.txt +24 -0
  83. package/docs/licenses/markdown-table@3.1.0.txt +24 -0
  84. package/docs/licenses/mdast-util-find-and-replace@3.0.4.txt +24 -0
  85. package/docs/licenses/mdast-util-from-markdown@2.0.3.txt +24 -0
  86. package/docs/licenses/mdast-util-gfm-autolink-literal@2.1.0.txt +24 -0
  87. package/docs/licenses/mdast-util-gfm-footnote@2.1.0.txt +24 -0
  88. package/docs/licenses/mdast-util-gfm-strikethrough@2.0.1.txt +24 -0
  89. package/docs/licenses/mdast-util-gfm-table@2.0.1.txt +24 -0
  90. package/docs/licenses/mdast-util-gfm-task-list-item@2.0.1.txt +24 -0
  91. package/docs/licenses/mdast-util-gfm@3.0.0.txt +24 -0
  92. package/docs/licenses/mdast-util-phrasing@4.1.0.txt +25 -0
  93. package/docs/licenses/mdast-util-to-markdown@2.2.3.txt +24 -0
  94. package/docs/licenses/mdast-util-to-string@4.0.0.txt +24 -0
  95. package/docs/licenses/micromark-core-commonmark@2.0.4.txt +24 -0
  96. package/docs/licenses/micromark-extension-gfm-autolink-literal@2.1.0.txt +24 -0
  97. package/docs/licenses/micromark-extension-gfm-footnote@2.1.0.txt +24 -0
  98. package/docs/licenses/micromark-extension-gfm-strikethrough@2.1.0.txt +24 -0
  99. package/docs/licenses/micromark-extension-gfm-table@2.1.2.txt +24 -0
  100. package/docs/licenses/micromark-extension-gfm-tagfilter@2.0.0.txt +24 -0
  101. package/docs/licenses/micromark-extension-gfm-task-list-item@2.1.0.txt +24 -0
  102. package/docs/licenses/micromark-extension-gfm@3.0.0.txt +24 -0
  103. package/docs/licenses/micromark-factory-destination@2.0.1.txt +24 -0
  104. package/docs/licenses/micromark-factory-label@2.0.1.txt +24 -0
  105. package/docs/licenses/micromark-factory-space@2.1.0.txt +24 -0
  106. package/docs/licenses/micromark-factory-title@2.0.1.txt +24 -0
  107. package/docs/licenses/micromark-factory-whitespace@2.0.1.txt +24 -0
  108. package/docs/licenses/micromark-util-character@2.1.1.txt +24 -0
  109. package/docs/licenses/micromark-util-chunked@2.0.1.txt +24 -0
  110. package/docs/licenses/micromark-util-classify-character@2.0.1.txt +24 -0
  111. package/docs/licenses/micromark-util-combine-extensions@2.0.1.txt +24 -0
  112. package/docs/licenses/micromark-util-decode-numeric-character-reference@2.0.2.txt +24 -0
  113. package/docs/licenses/micromark-util-decode-string@2.0.1.txt +24 -0
  114. package/docs/licenses/micromark-util-edit-map@1.0.0.txt +24 -0
  115. package/docs/licenses/micromark-util-encode@2.0.1.txt +24 -0
  116. package/docs/licenses/micromark-util-html-tag-name@2.0.1.txt +24 -0
  117. package/docs/licenses/micromark-util-normalize-identifier@2.0.1.txt +24 -0
  118. package/docs/licenses/micromark-util-resolve-all@2.0.1.txt +24 -0
  119. package/docs/licenses/micromark-util-sanitize-uri@2.0.1.txt +24 -0
  120. package/docs/licenses/micromark-util-subtokenize@2.1.0.txt +24 -0
  121. package/docs/licenses/micromark-util-symbol@2.0.1.txt +24 -0
  122. package/docs/licenses/micromark-util-types@2.0.3.txt +24 -0
  123. package/docs/licenses/micromark@4.0.3.txt +24 -0
  124. package/docs/licenses/ms@2.1.3.txt +23 -0
  125. package/docs/licenses/unist-util-is@6.0.1.txt +24 -0
  126. package/docs/licenses/unist-util-stringify-position@4.0.0.txt +24 -0
  127. package/docs/licenses/unist-util-visit-parents@6.1.0.txt +24 -0
  128. package/docs/licenses/unist-util-visit@5.2.0.txt +24 -0
  129. package/docs/licenses/zwitch@2.0.4.txt +24 -0
  130. package/docs/sales-agent-evaluation-v2.md +102 -0
  131. package/docs/wechat-sync.md +23 -0
  132. package/package.json +20 -7
  133. package/runtime/customer-materials.json +1935 -0
  134. package/runtime/documented-operation-references.json +123 -0
  135. package/runtime/operation-references.json +352 -0
  136. package/runtime/product-references.json +10 -0
  137. package/runtime/wechat-manifest.json +1 -1
  138. package/runtime/wechat-ocr-arm64 +0 -0
@@ -142,6 +142,9 @@ function validateSalesBatch(value) {
142
142
  return value;
143
143
  }
144
144
 
145
+ // src/customer-intent.ts
146
+ var intentSemanticPolicyVersion = 2;
147
+
145
148
  // src/turn-packet.ts
146
149
  function bindProgress(raw, packet) {
147
150
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw Error("\u5BA2\u6237\u8FDB\u5C55\u5FC5\u987B\u662F\u5E26\u6765\u6E90\u7684\u5BF9\u8C61\u3002");
@@ -149,7 +152,8 @@ function bindProgress(raw, packet) {
149
152
  if (Object.keys(p).sort().join(",") !== "artifacts,decisions,source_id,stage" || !["exploring", "evaluating", "confirming", "paused", "declined"].includes(String(p.stage)) || !Array.isArray(p.decisions) || p.decisions.length > 16 || !Array.isArray(p.artifacts) || p.artifacts.length > 8) throw Error("\u8FDB\u5C55\u7ED3\u6784\u65E0\u6548\uFF1B\u4E0D\u80FD\u5939\u5E26\u4EF7\u683C\u6279\u51C6\u6216\u6267\u884C\u7ED3\u679C\u3002");
150
153
  const bind = (id, customerOnly = false) => {
151
154
  const s = typeof id === "string" ? packet.sources[id] : void 0;
152
- if (!s || !["customer", "deal"].includes(s.authority) || customerOnly && s.authority !== "customer") throw Error("progress\u6765\u6E90 " + String(id) + " \u4E0D\u662F\u5BA2\u6237\u8BC1\u636E\u3002Q/V/O\u516C\u53F8\u6761\u4EF6\u5DF2\u4FDD\u7559\u5728approved_offer/current_company_facts\uFF0C\u4E0D\u653E\u5165\u5BA2\u6237progress\uFF1B\u53EA\u5F15\u7528C/F/P\u4E2D\u7684\u5BA2\u6237\u539F\u8BDD\u6216\u660E\u786E\u5BA2\u6237\u80CC\u666F\u3002");
155
+ if (customerOnly && s?.authority !== "customer") throw Error("progress.artifacts\u6765\u6E90 " + String(id) + " \u4E0D\u662F\u5BA2\u6237\u539F\u8BDD\uFF0C\u4E0D\u80FD\u8BC1\u660E\u5BA2\u6237\u5DF2\u6536\u5230\u6216\u770B\u8FC7\u6750\u6599\u3002\u53EA\u5F15\u7528sources\u4E2Dauthority\u4E3Acustomer\u7684\u6765\u6E90\uFF1B\u516C\u53F8\u8BF4\u660E\u6216deal\u80CC\u666F\u4E0D\u80FD\u66FF\u4EE3\u3002\u6CA1\u6709\u6B64\u7C7B\u6765\u6E90\u7684\u65E7\u6750\u6599\u72B6\u6001\u7559\u7A7A\u3002");
156
+ if (!s || !["customer", "deal"].includes(s.authority)) throw Error("progress\u6765\u6E90 " + String(id) + " \u4E0D\u662F\u5BA2\u6237\u8BC1\u636E\u3002Q/V/O\u516C\u53F8\u6761\u4EF6\u5DF2\u4FDD\u7559\u5728approved_offer/current_company_facts\uFF0C\u4E0D\u653E\u5165\u5BA2\u6237progress\uFF1B\u53EA\u5F15\u7528C/F/P\u4E2D\u7684\u5BA2\u6237\u539F\u8BDD\u6216\u660E\u786E\u5BA2\u6237\u80CC\u666F\u3002");
153
157
  return { source_id: id, quote: s.text };
154
158
  };
155
159
  const stage = bind(p.source_id), topics = /* @__PURE__ */ new Set(), artifacts = /* @__PURE__ */ new Set();
@@ -158,14 +162,14 @@ function bindProgress(raw, packet) {
158
162
  topics.add(v.topic);
159
163
  return { ...bind(v.source_id), topic: v.topic, meaning: v.meaning };
160
164
  }), artifacts: p.artifacts.map((v) => {
161
- if (!v || Object.keys(v).sort().join(",") !== "kind,source_id,status" || !["sample", "intro", "confirmation"].includes(v.kind) || !["requested", "received", "reviewed"].includes(v.status) || artifacts.has(v.kind)) throw Error("progress.artifacts\u6BCF\u9879\u53EA\u80FD\u542Bkind\u3001status\u3001source_id\uFF1Btopic/meaning\u5C5E\u4E8Edecisions\uFF0C\u4E0D\u80FD\u653E\u8FDBartifacts\uFF0C\u72B6\u6001\u4EC5requested/received/reviewed\u3002");
165
+ if (!v || Object.keys(v).sort().join(",") !== "kind,source_id,status" || !["sample", "intro", "confirmation"].includes(v.kind) || !["requested", "received", "reviewed"].includes(v.status) || artifacts.has(v.kind)) throw Error("progress.artifacts\u6BCF\u9879\u53EA\u80FD\u542Bkind\u3001status\u3001source_id\uFF1Bkind\u4EC5sample/intro/confirmation\uFF0C\u64CD\u4F5C\u6587\u6863\u3001\u89C6\u9891\u548C\u56FE\u7247\u7EDF\u4E00\u5F52intro\uFF0C\u4E0D\u80FD\u586Bdocument/video/image\uFF1B\u540C\u7C7B\u6700\u591A\u4E00\u9879\u3002topic/meaning\u5C5E\u4E8Edecisions\uFF0C\u4E0D\u80FD\u653E\u8FDBartifacts\uFF0C\u72B6\u6001\u4EC5requested/received/reviewed\u3002");
162
166
  artifacts.add(v.kind);
163
167
  return { ...bind(v.source_id, true), kind: v.kind, status: v.status };
164
168
  }) };
165
169
  }
166
170
  function parseSavedProgress(raw) {
167
171
  const p = raw;
168
- if (!p || typeof p !== "object" || Object.keys(p).sort().join(",") !== "artifacts,decisions,quote,source_id,stage" || !Array.isArray(p.decisions) || !Array.isArray(p.artifacts)) throw Error("INVALID_PROGRESS");
172
+ if (!p || typeof p !== "object" || Object.keys(p).filter((k) => k !== "pending").sort().join(",") !== "artifacts,decisions,quote,source_id,stage" || !Array.isArray(p.decisions) || !Array.isArray(p.artifacts)) throw Error("INVALID_PROGRESS");
169
173
  const sources = /* @__PURE__ */ Object.create(null);
170
174
  const source = (item, keys) => {
171
175
  if (!item || Object.keys(item).sort().join(",") !== keys || typeof item.quote !== "string" || !item.quote.trim() || typeof item.source_id !== "string" || !/^[CFP]\d+$/.test(item.source_id) || sources[item.source_id] && sources[item.source_id].text !== item.quote) throw Error("INVALID_PROGRESS");
@@ -174,12 +178,40 @@ function parseSavedProgress(raw) {
174
178
  source({ source_id: p.source_id, quote: p.quote }, "quote,source_id");
175
179
  for (const d of p.decisions) source(d, "meaning,quote,source_id,topic");
176
180
  for (const a of p.artifacts) source(a, "kind,quote,source_id,status");
177
- return bindProgress({ stage: p.stage, source_id: p.source_id, decisions: p.decisions.map(({ quote, ...d }) => d), artifacts: p.artifacts.map(({ quote, ...a }) => a) }, { sources });
181
+ if (p.pending !== void 0) {
182
+ if (!Array.isArray(p.pending) || p.pending.length > 4) throw Error("INVALID_PROGRESS");
183
+ for (const task of p.pending) {
184
+ if (!task || Object.keys(task).sort().join(",") !== "basis,quote,source_id,topic" || !["returns", "timing", "fees", "permissions", "scope"].includes(task.topic) || typeof task.basis !== "string" || !/^[a-f0-9]{1,8}$/.test(task.basis) || typeof task.quote !== "string" || task.quote.length > 6e3 || !/^C\d+$|^P\d+$/.test(task.source_id)) throw Error("INVALID_PROGRESS");
185
+ source({ source_id: task.source_id, quote: task.quote }, "quote,source_id");
186
+ }
187
+ }
188
+ const bound = bindProgress({ stage: p.stage, source_id: p.source_id, decisions: p.decisions.map(({ quote, ...d }) => d), artifacts: p.artifacts.map(({ quote, ...a }) => a) }, { sources });
189
+ return p.pending ? { ...bound, pending: structuredClone(p.pending) } : bound;
190
+ }
191
+
192
+ // src/wechat-draft-input.ts
193
+ var attachmentReplies = /* @__PURE__ */ new Map([
194
+ ["voice", "\u8BED\u97F3\u6536\u5230\u4E86\uFF0C\u65B9\u4FBF\u7684\u8BDD\u628A\u91CD\u70B9\u6253\u51E0\u4E2A\u5B57\u7ED9\u6211\uFF0C\u6211\u597D\u63A5\u7740\u5E2E\u4F60\u770B\u3002"],
195
+ ["file", "\u6587\u4EF6\u6536\u5230\u4E86\uFF0C\u4F60\u60F3\u8BA9\u6211\u91CD\u70B9\u770B\u54EA\u4E00\u5757\uFF1F"],
196
+ ["image", "\u56FE\u6536\u5230\u4E86\uFF0C\u4F60\u60F3\u8BA9\u6211\u5E2E\u4F60\u770B\u56FE\u91CC\u7684\u54EA\u4E00\u5904\uFF1F"],
197
+ ["video", "\u89C6\u9891\u6536\u5230\u4E86\uFF0C\u4F60\u60F3\u8BA9\u6211\u91CD\u70B9\u770B\u54EA\u4E00\u6BB5\uFF1F"]
198
+ ]);
199
+ function attachmentReply(kind) {
200
+ return attachmentReplies.get(kind);
178
201
  }
179
202
 
180
203
  // src/wechat/repository.ts
181
204
  var hash = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex");
182
205
  var previewLabels = { image: "\u56FE\u7247", voice: "\u8BED\u97F3", video: "\u89C6\u9891", location: "\u4F4D\u7F6E", call: "\u901A\u8BDD", emoji: "\u8868\u60C5", link: "\u94FE\u63A5", file: "\u6587\u4EF6", mini_program: "\u5C0F\u7A0B\u5E8F", transfer: "\u8F6C\u8D26", red_packet: "\u7EA2\u5305", quote: "\u5F15\u7528", system: "\u7CFB\u7EDF\u6D88\u606F", unknown: "\u672A\u77E5\u6D88\u606F" };
206
+ var replyText = (message) => {
207
+ const text = message.text?.trim();
208
+ if (message.kind === "emoji") return !text || text.startsWith("<") || /^\[(?:emoji|表情|动画表情|动态表情|自定义表情)\]$/i.test(text) ? "[emoji]" : text;
209
+ return text && ["text", "quote", "link"].includes(message.kind) ? message.text : void 0;
210
+ };
211
+ function replyInputChanged(previous, incoming) {
212
+ if (incoming.direction === "system" && (!previous || previous.direction === "system")) return false;
213
+ return !previous || previous.direction !== incoming.direction || previous.kind !== incoming.kind || previous.sent_at !== incoming.sent_at || previous.sort_seq !== incoming.sort_seq || previous.local_id !== incoming.local_id || replyText(previous) !== replyText(incoming);
214
+ }
183
215
  var WechatRepository = class _WechatRepository {
184
216
  db;
185
217
  closed = false;
@@ -187,6 +219,7 @@ var WechatRepository = class _WechatRepository {
187
219
  this.db = new DatabaseSync(path);
188
220
  this.db.exec(`
189
221
  PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
222
+ CREATE TABLE IF NOT EXISTS deliveries(id TEXT PRIMARY KEY,workspace TEXT NOT NULL,contact_id TEXT NOT NULL,message_id TEXT NOT NULL,text TEXT NOT NULL,status TEXT NOT NULL,created TEXT NOT NULL,baseline TEXT NOT NULL,receipt TEXT);
190
223
  CREATE TABLE IF NOT EXISTS active(workspace TEXT PRIMARY KEY,account TEXT NOT NULL);
191
224
  CREATE TABLE IF NOT EXISTS chats(id TEXT PRIMARY KEY,workspace TEXT NOT NULL,account TEXT NOT NULL,chat_key TEXT NOT NULL,name TEXT NOT NULL,history_state TEXT,version INTEGER NOT NULL DEFAULT 0,handled INTEGER NOT NULL DEFAULT 0,crm TEXT,state TEXT NOT NULL DEFAULT '{}');
192
225
  CREATE INDEX IF NOT EXISTS chats_scope ON chats(workspace,account);
@@ -198,9 +231,19 @@ var WechatRepository = class _WechatRepository {
198
231
  CREATE TABLE IF NOT EXISTS runs(workspace TEXT NOT NULL,run_id TEXT NOT NULL,digest TEXT NOT NULL,result TEXT NOT NULL,PRIMARY KEY(workspace,run_id));
199
232
  CREATE TABLE IF NOT EXISTS checkpoints(scope TEXT PRIMARY KEY,revision TEXT,active_revision TEXT,next_part INTEGER,part_count INTEGER);
200
233
  CREATE TABLE IF NOT EXISTS pairing(workspace TEXT PRIMARY KEY,token TEXT NOT NULL);
234
+ CREATE TABLE IF NOT EXISTS customer_intents(
235
+ chat_id TEXT PRIMARY KEY REFERENCES chats(id), revision INTEGER NOT NULL DEFAULT 1,
236
+ assessed INTEGER NOT NULL DEFAULT 0, due INTEGER NOT NULL, result TEXT
237
+ );
238
+ CREATE TABLE IF NOT EXISTS intent_quota_pause(workspace TEXT PRIMARY KEY,resume_at INTEGER NOT NULL);
239
+ CREATE TABLE IF NOT EXISTS intent_seed(workspace TEXT NOT NULL,account TEXT NOT NULL,PRIMARY KEY(workspace,account));
201
240
  `);
202
241
  if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "source_revision")) this.db.exec("ALTER TABLE messages ADD COLUMN source_revision TEXT");
203
242
  for (const table of ["chats", "messages", "sources", "media"]) if (!this.rows("PRAGMA table_info(" + table + ")").some((c) => c.name === "metadata")) this.db.exec("ALTER TABLE " + table + " ADD COLUMN metadata TEXT NOT NULL DEFAULT '{}'");
243
+ if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "intent_revision")) {
244
+ this.db.exec("ALTER TABLE messages ADD COLUMN intent_revision INTEGER NOT NULL DEFAULT 0");
245
+ }
246
+ if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "auto_draft_arrival")) this.db.exec("ALTER TABLE messages ADD COLUMN auto_draft_arrival INTEGER NOT NULL DEFAULT 0");
204
247
  this.db.exec(`INSERT OR IGNORE INTO avatars(workspace,account,owner,media_id,observed_at)
205
248
  SELECT c.workspace,c.account,c.chat_key,m.id,0 FROM chats c JOIN media m
206
249
  ON m.id=json_extract(c.metadata,'$.avatarId') AND m.workspace=c.workspace AND m.account=c.account`);
@@ -225,7 +268,7 @@ var WechatRepository = class _WechatRepository {
225
268
  if (!row) throw Error("WECHAT_ACCOUNT_SCOPE");
226
269
  return row;
227
270
  }
228
- importBatch(workspace, raw) {
271
+ importBatch(workspace, raw, trackIntent = false, initial = false) {
229
272
  if (typeof workspace !== "string" || !workspace.trim() || workspace.length > 256) throw Error("WECHAT_WORKSPACE_INVALID");
230
273
  const encoded = JSON.stringify(raw);
231
274
  if (encoded.length > 65 * 1024 * 1024) throw Error("WECHAT_BATCH_TOO_LARGE");
@@ -247,8 +290,13 @@ var WechatRepository = class _WechatRepository {
247
290
  const source = hash([workspace, account, batch.source.kind ?? "", batch.source.device_id ?? ""]);
248
291
  const active = this.row("SELECT account FROM active WHERE workspace=?", workspace)?.account;
249
292
  if (batch.delivery && active !== account) throw Error("WANJI_RESYNC_REQUIRED: media account baseline missing");
250
- const changed = /* @__PURE__ */ new Set();
293
+ const changed = /* @__PURE__ */ new Set(), replyChanges = /* @__PURE__ */ new Set(), voiceChanges = /* @__PURE__ */ new Map();
251
294
  let messages = 0, avatarsUpdated = 0;
295
+ const trackVoiceChange = (chatId, id) => {
296
+ const voices = voiceChanges.get(chatId) ?? /* @__PURE__ */ new Set();
297
+ voices.add(id);
298
+ voiceChanges.set(chatId, voices);
299
+ };
252
300
  const receipt = batch.sync ? { protocol: batch.sync.protocol, scope: batch.sync.scope, revision: batch.sync.revision, part_index: batch.sync.part_index, part_count: batch.sync.part_count, committed: batch.sync.part_index === batch.sync.part_count - 1 } : void 0;
253
301
  this.db.exec("BEGIN IMMEDIATE");
254
302
  try {
@@ -280,7 +328,9 @@ var WechatRepository = class _WechatRepository {
280
328
  if (batch.delivery && !existing) throw Error("WANJI_RESYNC_REQUIRED: media chat missing");
281
329
  const metadata = { ...existing ? JSON.parse(existing.metadata) : {}, ...Object.fromEntries(["remark", "nickname", "alias"].filter((key) => Object.hasOwn(chat, key)).map((key) => [key, chat[key]])) }, encodedMetadata = JSON.stringify(metadata);
282
330
  if (!batch.delivery) this.db.prepare("INSERT INTO chats(id,workspace,account,chat_key,name,history_state,metadata) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,history_state=excluded.history_state,metadata=excluded.metadata").run(chatId, workspace, account, chat.chat_key, chat.display_name, chat.history_state ?? null, encodedMetadata);
283
- if (!batch.delivery && (!existing || existing.name !== chat.display_name || existing.metadata !== encodedMetadata)) changed.add(chatId);
331
+ if (!batch.delivery && (!existing || existing.name !== chat.display_name || existing.history_state !== (chat.history_state ?? null) || existing.metadata !== encodedMetadata)) changed.add(chatId);
332
+ const advanceIntent = trackIntent && (!(initial || active !== account || batch.sync?.mode === "full") || !!this.row("SELECT 1 FROM customer_intents WHERE chat_id=?", chatId));
333
+ let intentRevision;
284
334
  for (const m of chat.messages) {
285
335
  const oldSource = this.row("SELECT * FROM sources WHERE scope=? AND chat_id=? AND message_key=?", source, chatId, m.message_key);
286
336
  if (batch.delivery) {
@@ -291,6 +341,7 @@ var WechatRepository = class _WechatRepository {
291
341
  if (old2.media_id !== mediaId2) {
292
342
  this.db.prepare("UPDATE messages SET media_id=? WHERE id=?").run(mediaId2, old2.id);
293
343
  changed.add(chatId);
344
+ if (old2.kind === "voice" && old2.direction === "inbound" && old2.auto_draft_arrival === 1) trackVoiceChange(chatId, old2.id);
294
345
  }
295
346
  continue;
296
347
  }
@@ -298,15 +349,33 @@ var WechatRepository = class _WechatRepository {
298
349
  const id = server ? hash([chatId, "server", server]) : hash([chatId, "local", source, m.message_key]);
299
350
  const old = this.row("SELECT * FROM messages WHERE id=?", id), revisionChanged = !!old && old.source_revision !== (m.source_revision ?? null), mediaId = m.media_key ? hash([source, m.media_key]) : revisionChanged ? null : old?.media_id ?? null;
300
351
  if (!old || old.text !== m.text || old.direction !== m.direction || old.kind !== m.kind || old.sent_at !== m.sent_at || old.media_id !== mediaId || revisionChanged || old.metadata !== JSON.stringify(m)) {
352
+ if (replyInputChanged(old, m)) replyChanges.add(chatId);
353
+ if (m.kind === "voice" && m.direction === "inbound" && old?.auto_draft_arrival === 1 && old.media_id !== mediaId) trackVoiceChange(chatId, id);
301
354
  this.db.prepare("INSERT INTO messages(id,chat_id,sent_at,sort_seq,local_id,direction,kind,text,media_id,source_revision,metadata) VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET sent_at=excluded.sent_at,sort_seq=excluded.sort_seq,local_id=excluded.local_id,direction=excluded.direction,kind=excluded.kind,text=excluded.text,media_id=excluded.media_id,source_revision=excluded.source_revision,metadata=excluded.metadata").run(id, chatId, m.sent_at, m.sort_seq, m.local_id, m.direction, m.kind, m.text, mediaId, m.source_revision ?? null, JSON.stringify(m));
302
355
  changed.add(chatId);
303
356
  if (!old) messages++;
304
357
  }
358
+ if (!old && !initial && active === account && batch.sync?.mode !== "full" && m.direction === "inbound" && (replyText(m) || attachmentReply(m.kind))) {
359
+ this.db.prepare("UPDATE messages SET auto_draft_arrival=1 WHERE id=?").run(id);
360
+ }
361
+ const meaningful = (row) => row.direction !== "system" && ["text", "quote", "link"].includes(row.kind) && typeof row.text === "string" && !!row.text.trim();
362
+ const intentChanged = !old ? meaningful(m) : (meaningful(m) || meaningful(old)) && (old.text !== m.text || old.direction !== m.direction || old.kind !== m.kind);
363
+ if (advanceIntent && intentChanged) {
364
+ intentRevision ??= this.queueIntentRow(chatId, Date.now() + 3500, true);
365
+ this.db.prepare("UPDATE messages SET intent_revision=? WHERE id=?").run(intentRevision, id);
366
+ }
305
367
  this.db.prepare("INSERT INTO sources(scope,chat_id,message_key,message_id,source_revision,metadata) VALUES(?,?,?,?,?,?) ON CONFLICT(scope,chat_id,message_key) DO UPDATE SET message_id=excluded.message_id,source_revision=excluded.source_revision,metadata=excluded.metadata").run(source, chatId, m.message_key, id, m.source_revision ?? null, JSON.stringify(m));
306
368
  }
307
369
  }
308
370
  for (const id of changed) {
309
- const row = this.row("SELECT state FROM chats WHERE id=?", id), state = JSON.parse(row.state);
371
+ const row = this.row("SELECT version,state,handled FROM chats WHERE id=?", id), state = JSON.parse(row.state);
372
+ const latest = voiceChanges.has(id) && active === account ? this.listMessages(workspace, id, void 0, 1, true)[0] : void 0;
373
+ const refreshVoice = !!latest && row.version > row.handled && voiceChanges.get(id)?.has(latest.id);
374
+ if (!replyChanges.has(id) && !refreshVoice) continue;
375
+ delete state.autoDraftSuggestion;
376
+ delete state.autoDraftedMessageId;
377
+ delete state.generationError;
378
+ delete state.generationNoReply;
310
379
  if (state.draftKind === "agent") {
311
380
  state.draft = "";
312
381
  state.draftKind = "empty";
@@ -324,6 +393,97 @@ var WechatRepository = class _WechatRepository {
324
393
  throw error;
325
394
  }
326
395
  }
396
+ queueIntentRow(id, due, overwrite) {
397
+ const onConflict = overwrite ? "DO UPDATE SET revision=revision+1,due=excluded.due" : "DO NOTHING";
398
+ this.db.prepare(`INSERT INTO customer_intents(chat_id,due) VALUES(?,?) ON CONFLICT(chat_id) ${onConflict}`).run(id, due);
399
+ return this.row("SELECT revision FROM customer_intents WHERE chat_id=?", id).revision;
400
+ }
401
+ queueIntent(workspace, id) {
402
+ this.scope(workspace, id);
403
+ this.queueIntentRow(id, Date.now(), false);
404
+ this.requeueLegacyIntents(workspace, id);
405
+ }
406
+ requeueLegacyIntents(workspace, contactId) {
407
+ this.db.prepare(`UPDATE customer_intents SET revision=revision+1,due=?
408
+ WHERE assessed=revision AND (
409
+ (json_extract(result,'$.status')='ready' AND COALESCE(json_extract(result,'$.policyVersion'),1)<?)
410
+ OR (json_extract(result,'$.status')='failed' AND json_extract(result,'$.policyVersion')=?)
411
+ )
412
+ AND json_extract(result,'$.products')='{}' AND json_type(result,'$.crm') IS NULL
413
+ AND EXISTS(SELECT 1 FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account
414
+ WHERE c.id=customer_intents.chat_id AND c.workspace=? AND c.crm IS NULL)
415
+ ${contactId === void 0 ? "" : "AND chat_id=?"}`).run(Date.now(), intentSemanticPolicyVersion, intentSemanticPolicyVersion, workspace, ...contactId === void 0 ? [] : [contactId]);
416
+ }
417
+ seedIntents(workspace) {
418
+ const active = this.row("SELECT account FROM active WHERE workspace=?", workspace);
419
+ if (!active) return;
420
+ this.requeueLegacyIntents(workspace);
421
+ if (this.row("SELECT 1 FROM intent_seed WHERE workspace=? AND account=?", workspace, active.account)) return;
422
+ const contacts = this.rows(`SELECT c.id FROM chats c WHERE c.workspace=? AND c.account=?
423
+ AND (c.crm IS NOT NULL OR EXISTS(SELECT 1 FROM messages m WHERE m.chat_id=c.id AND m.direction='inbound' AND m.kind IN ('text','quote','link') AND length(trim(m.text))>0))
424
+ ORDER BY c.crm IS NULL,(SELECT MAX(sent_at) FROM messages m WHERE m.chat_id=c.id) DESC,c.id LIMIT 10`, workspace, active.account);
425
+ if (!contacts.length) return;
426
+ this.db.exec("BEGIN IMMEDIATE");
427
+ try {
428
+ for (const contact of contacts) this.queueIntentRow(contact.id, Date.now(), false);
429
+ this.db.prepare("INSERT OR IGNORE INTO intent_seed VALUES(?,?)").run(workspace, active.account);
430
+ this.db.exec("COMMIT");
431
+ } catch (error) {
432
+ this.db.exec("ROLLBACK");
433
+ throw error;
434
+ }
435
+ }
436
+ nextIntent(workspace) {
437
+ const row = this.row(`SELECT i.chat_id,i.revision,MAX(i.due,COALESCE(p.resume_at,0)) AS due FROM customer_intents i
438
+ JOIN chats c ON c.id=i.chat_id JOIN active a ON a.workspace=c.workspace AND a.account=c.account
439
+ LEFT JOIN intent_quota_pause p ON p.workspace=c.workspace
440
+ WHERE c.workspace=? AND i.assessed<i.revision ORDER BY i.due,c.id LIMIT 1`, workspace);
441
+ if (row) return { contactId: row.chat_id, version: row.revision, due: row.due };
442
+ }
443
+ getIntentInput(workspace, job) {
444
+ const chat = this.scope(workspace, job.contactId);
445
+ const row = this.row("SELECT * FROM customer_intents WHERE chat_id=? AND revision=? AND assessed<revision", chat.id, job.version);
446
+ if (!row) return;
447
+ const messages = this.rows(`SELECT id,sent_at,direction,text,intent_revision FROM messages WHERE chat_id=? AND direction IN ('inbound','outbound')
448
+ AND kind IN ('text','quote','link') AND length(trim(text))>0 ORDER BY sent_at DESC,length(sort_seq) DESC,sort_seq DESC,length(local_id) DESC,local_id DESC,id DESC LIMIT 36`, chat.id);
449
+ const previous = row.result ? JSON.parse(row.result) : void 0;
450
+ const needsLegacyEvidence = previous && (previous.policyVersion ?? 1) < intentSemanticPolicyVersion && !chat.crm && !Object.keys(previous.products).length;
451
+ const evaluated = needsLegacyEvidence ? 0 : previous?.evaluatedVersion ?? 0;
452
+ return {
453
+ ...job,
454
+ crm: chat.crm ? JSON.parse(chat.crm) : void 0,
455
+ previous,
456
+ messages: messages.reverse().map((m) => ({ id: m.id, time: m.sent_at, direction: m.direction === "inbound" ? "in" : "out", text: m.text.slice(0, 2e3), changed: !evaluated || m.intent_revision > evaluated }))
457
+ };
458
+ }
459
+ finishIntent(workspace, id, result) {
460
+ const scope = `chat_id=? AND revision=? AND assessed<revision
461
+ AND EXISTS(SELECT 1 FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account WHERE c.id=? AND c.workspace=?)`;
462
+ const params = [JSON.stringify(result), id, result.version, id, workspace];
463
+ if (!result.retryAt) {
464
+ return Number(this.db.prepare(`UPDATE customer_intents SET assessed=?,result=? WHERE ${scope}`).run(result.version, ...params).changes) > 0;
465
+ }
466
+ this.db.exec("BEGIN IMMEDIATE");
467
+ try {
468
+ const saved = Number(this.db.prepare(`UPDATE customer_intents SET due=?,result=? WHERE ${scope}`).run(result.retryAt, ...params).changes) > 0;
469
+ if (saved) this.db.prepare(`INSERT INTO intent_quota_pause VALUES(?,?) ON CONFLICT(workspace)
470
+ DO UPDATE SET resume_at=MAX(resume_at,excluded.resume_at)`).run(workspace, result.retryAt);
471
+ this.db.exec("COMMIT");
472
+ return saved;
473
+ } catch (error) {
474
+ this.db.exec("ROLLBACK");
475
+ throw error;
476
+ }
477
+ }
478
+ intentFor(id) {
479
+ const row = this.row(`SELECT i.revision,i.assessed,i.result,p.resume_at FROM customer_intents i JOIN chats c ON c.id=i.chat_id
480
+ LEFT JOIN intent_quota_pause p ON p.workspace=c.workspace WHERE i.chat_id=?`, id);
481
+ if (!row) return;
482
+ const last = row.result ? JSON.parse(row.result) : void 0;
483
+ if (row.assessed === row.revision) return last;
484
+ const retryAt = row.resume_at > Date.now() ? row.resume_at : void 0;
485
+ return { ...last, products: last?.products ?? {}, version: row.revision, status: "pending", retryAt };
486
+ }
327
487
  listContacts(workspace, limit = 200, offset = 0) {
328
488
  return this.rows("SELECT c.* FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account WHERE c.workspace=? ORDER BY (SELECT MAX(sent_at) FROM messages WHERE chat_id=c.id) DESC,c.id LIMIT ? OFFSET ?", workspace, Math.max(1, Math.min(200, limit)), Math.max(0, offset)).map((c) => this.project(c, 2));
329
489
  }
@@ -331,47 +491,113 @@ var WechatRepository = class _WechatRepository {
331
491
  return this.project(this.scope(workspace, id), 100);
332
492
  }
333
493
  project(c, limit) {
334
- const recent = this.listMessages(c.workspace, c.id, void 0, limit), latest = recent.at(-1), last = recent.filter((m) => m.direction !== "system").at(-1);
494
+ const recent = this.listMessages(c.workspace, c.id, void 0, limit, true), last = recent.at(-1);
495
+ const latest = this.listMessages(c.workspace, c.id, void 0, 1)[0];
335
496
  let budget = 16e3;
336
497
  const messages = [];
337
498
  for (const m of [...recent].reverse()) {
338
- if (!["text", "quote", "link"].includes(m.kind) || m.direction === "system" || !m.text?.trim()) continue;
339
- if (m.text.length > budget) break;
340
- budget -= m.text.length;
341
- messages.unshift({ id: m.id, direction: m.direction === "inbound" ? "in" : "out", text: m.text, time: m.sentAt });
499
+ const text = replyText(m);
500
+ if (m.direction === "system" || !text) continue;
501
+ if (text.length > budget) break;
502
+ budget -= text.length;
503
+ messages.unshift({ id: m.id, direction: m.direction === "inbound" ? "in" : "out", text, time: m.sentAt });
342
504
  }
505
+ const latestInbound = recent.filter((m) => m.direction === "inbound").at(-1);
343
506
  const state = JSON.parse(c.state);
507
+ const hasText = !!latestInbound && messages.some((m) => m.id === latestInbound.id);
508
+ const settled = state.sourceVersion === c.version && (state.draftKind === "agent" || state.generationError || state.generationNoReply || state.draftKind === "edited" && state.autoDraftedMessageId === latestInbound?.id && !!latestInbound);
509
+ const canDraft = latestInbound && last?.id === latestInbound.id && c.version > c.handled && !settled && (hasText || attachmentReply(latestInbound.kind)) && this.row("SELECT auto_draft_arrival FROM messages WHERE id=?", latestInbound.id)?.auto_draft_arrival === 1;
510
+ const intent = this.intentFor(c.id);
344
511
  const avatar = this.row("SELECT media_id,observed_at FROM avatars WHERE workspace=? AND account=? AND owner=?", c.workspace, c.account, c.chat_key);
345
512
  const self = this.row("SELECT media_id,observed_at FROM avatars WHERE workspace=? AND account=? AND owner=?", c.workspace, c.account, c.account);
346
- return { id: c.id, name: c.name, initials: Array.from(String(c.name))[0] ?? "\u5FAE", segment: "\u5FAE\u4FE1", time: latest?.sentAt ?? "", preview: latest ? latest.text || `[${previewLabels[latest.kind] ?? latest.kind}]` : "", status: last?.direction === "inbound" && c.version > c.handled ? "pending" : "handled", unread: last?.direction === "inbound" && c.version > c.handled ? 1 : 0, product: "\u4E07\u673A\u7BA1\u5BB6 ERP / \u4E07\u673A\u5858", budget: "\u5F85\u786E\u8BA4", moneyAmounts: [], tags: [], facts: [], messages, candidates: [], wechat: { accountId: c.account, chatKey: c.chat_key, version: c.version, ...avatar ? { avatarId: avatar.media_id, avatarUpdatedAt: avatar.observed_at } : JSON.parse(c.metadata).avatarId ? { avatarId: JSON.parse(c.metadata).avatarId } : {}, ...self ? { selfAvatarId: self.media_id, selfAvatarUpdatedAt: self.observed_at } : {}, ...c.history_state ? { historyState: c.history_state } : {} }, ...c.crm ? { crm: JSON.parse(c.crm) } : {}, ...state.progress ? { progress: state.progress } : {} };
513
+ return { id: c.id, name: c.name, initials: Array.from(String(c.name))[0] ?? "\u5FAE", segment: "\u5FAE\u4FE1", time: latest?.sentAt ?? "", preview: latest ? latest.text || `[${previewLabels[latest.kind] ?? latest.kind}]` : "", status: last?.direction === "inbound" && c.version > c.handled ? "pending" : "handled", unread: last?.direction === "inbound" && c.version > c.handled ? 1 : 0, product: "\u4E07\u673A\u7BA1\u5BB6 ERP / \u4E07\u673A\u5858", budget: "\u5F85\u786E\u8BA4", moneyAmounts: [], tags: [], facts: [], messages, candidates: [], wechat: { accountId: c.account, chatKey: c.chat_key, version: c.version, ...canDraft ? { autoDraftMessageId: latestInbound.id } : {}, ...latestInbound ? { latestInbound: { id: latestInbound.id, kind: latestInbound.kind, hasText, ...latestInbound.kind === "voice" && latestInbound.mediaId ? { voiceMediaId: latestInbound.mediaId } : {} } } : {}, ...avatar ? { avatarId: avatar.media_id, avatarUpdatedAt: avatar.observed_at } : JSON.parse(c.metadata).avatarId ? { avatarId: JSON.parse(c.metadata).avatarId } : {}, ...self ? { selfAvatarId: self.media_id, selfAvatarUpdatedAt: self.observed_at } : {}, ...c.history_state ? { historyState: c.history_state } : {} }, ...c.crm ? { crm: JSON.parse(c.crm) } : {}, ...state.progress ? { progress: state.progress } : {}, ...intent ? { intent } : {} };
347
514
  }
348
- listMessages(workspace, id, before, limit = 100) {
515
+ listMessages(workspace, id, before, limit = 100, excludeSystem = false) {
349
516
  this.scope(workspace, id);
350
517
  const anchor = before ? this.row("SELECT sent_at,sort_seq,local_id,id FROM messages WHERE id=? AND chat_id=?", before, id) : void 0;
351
518
  if (before && !anchor) throw Error("WECHAT_MESSAGE_CURSOR");
352
- return this.rows(`SELECT * FROM messages WHERE chat_id=? ${anchor ? "AND (sent_at,length(sort_seq),sort_seq,length(local_id),local_id,id)<(?,?,?,?,?,?)" : ""} ORDER BY sent_at DESC,length(sort_seq) DESC,sort_seq DESC,length(local_id) DESC,local_id DESC,id DESC LIMIT ?`, id, ...anchor ? [anchor.sent_at, anchor.sort_seq.length, anchor.sort_seq, anchor.local_id.length, anchor.local_id, anchor.id] : [], Math.max(1, Math.min(200, limit))).reverse().map((m) => ({ id: m.id, direction: m.direction, kind: m.kind, text: m.text, sentAt: m.sent_at, sortSeq: m.sort_seq, localId: m.local_id, ...m.media_id ? { mediaId: m.media_id } : {}, rawType: JSON.parse(m.metadata).raw_type, senderId: JSON.parse(m.metadata).sender_wxid }));
519
+ return this.rows(`SELECT * FROM messages WHERE chat_id=? ${excludeSystem ? "AND direction<>'system'" : ""} ${anchor ? "AND (sent_at,length(sort_seq),sort_seq,length(local_id),local_id,id)<(?,?,?,?,?,?)" : ""} ORDER BY sent_at DESC,length(sort_seq) DESC,sort_seq DESC,length(local_id) DESC,local_id DESC,id DESC LIMIT ?`, id, ...anchor ? [anchor.sent_at, anchor.sort_seq.length, anchor.sort_seq, anchor.local_id.length, anchor.local_id, anchor.id] : [], Math.max(1, Math.min(200, limit))).reverse().map((m) => ({ id: m.id, direction: m.direction, kind: m.kind, text: m.text, sentAt: m.sent_at, sortSeq: m.sort_seq, localId: m.local_id, ...m.media_id ? { mediaId: m.media_id } : {}, rawType: JSON.parse(m.metadata).raw_type, senderId: JSON.parse(m.metadata).sender_wxid }));
520
+ }
521
+ getDeliverySource(workspace, id) {
522
+ const row = this.scope(workspace, id), contact = this.getContact(workspace, id), state = this.getState(workspace, id), meta = JSON.parse(row.metadata), inbound = contact.messages.filter((m) => m.direction === "in").at(-1);
523
+ return { accountId: row.account, chatKey: row.chat_key, version: row.version, messageId: contact.wechat?.latestInbound?.id ?? "", pending: contact.status === "pending", text: inbound?.text ?? "", draft: state.sourceVersion === row.version ? state.draft ?? "" : "", kind: state.draftKind ?? "empty", alias: meta.alias, name: row.name };
524
+ }
525
+ claimDelivery(workspace, key, input) {
526
+ if (workspace !== input.workspaceId) throw Error("WECHAT_DELIVERY_SCOPE");
527
+ const source = this.getDeliverySource(input.workspaceId, input.contactId);
528
+ if (source.version !== input.version || source.messageId !== input.messageId || source.draft !== input.text || !source.pending) throw Error("WECHAT_DELIVERY_STALE");
529
+ if (this.row("SELECT id FROM deliveries WHERE contact_id=? AND status IN ('unknown','awaiting-receipt','claimed')", input.contactId)) throw Error("WECHAT_DELIVERY_UNRESOLVED");
530
+ const previous = this.row("SELECT status FROM deliveries WHERE id=?", key);
531
+ if (previous?.status === "blocked" && !input.automatic) {
532
+ this.db.prepare("DELETE FROM deliveries WHERE id=? AND status='blocked'").run(key);
533
+ }
534
+ return Number(this.db.prepare("INSERT OR IGNORE INTO deliveries VALUES(?,?,?,?,?,?,?,?,NULL)").run(key, input.workspaceId, input.contactId, input.messageId, input.text, "claimed", (/* @__PURE__ */ new Date()).toISOString(), JSON.stringify(this.listMessages(input.workspaceId, input.contactId, void 0, 200).map((m) => m.id))).changes) === 1;
535
+ }
536
+ settleDelivery(workspace, key, status) {
537
+ this.db.prepare("UPDATE deliveries SET status=? WHERE id=? AND workspace=?").run(status, key, workspace);
538
+ }
539
+ deliveryStatus(workspace, id) {
540
+ this.scope(workspace, id);
541
+ const rows = this.rows("SELECT * FROM deliveries WHERE workspace=? AND contact_id=? ORDER BY created DESC", workspace, id);
542
+ for (const row of rows) {
543
+ if (row.status === "sent") continue;
544
+ const baseline = new Set(JSON.parse(row.baseline)), receipt = this.listMessages(workspace, id, void 0, 200).find((m) => m.direction === "outbound" && m.text === row.text && !baseline.has(m.id) && Date.parse(m.sentAt) >= Date.parse(row.created) - 1e4);
545
+ if (receipt) {
546
+ this.db.prepare("UPDATE deliveries SET status='sent',receipt=? WHERE id=?").run(receipt.id, row.id);
547
+ row.status = "sent";
548
+ } else if (row.status === "claimed") row.status = "unknown";
549
+ }
550
+ return rows[0] ? { status: rows[0].status, messageId: rows[0].message_id } : { status: "idle" };
353
551
  }
354
552
  getMedia(workspace, id) {
355
553
  const row = this.row("SELECT m.* FROM media m JOIN active a ON a.workspace=m.workspace AND a.account=m.account WHERE m.workspace=? AND m.id=?", workspace, id);
356
554
  if (!row) throw Error("WECHAT_MEDIA_SCOPE");
357
555
  return { mimeType: row.mime, data: Buffer.from(row.data).toString("base64") };
358
556
  }
359
- bindCrm(workspace, id, binding) {
557
+ getDraftVoice(workspace, contactId, messageId, version) {
558
+ const contact = this.getContact(workspace, contactId), inbound = contact.wechat?.latestInbound;
559
+ if (contact.wechat?.version !== version || inbound?.id !== messageId) throw Error("WECHAT_STATE_STALE");
560
+ if (!inbound.voiceMediaId) return;
561
+ const row = this.row("SELECT data FROM media WHERE workspace=? AND account=? AND id=? AND mime='audio/wav'", workspace, contact.wechat.accountId, inbound.voiceMediaId);
562
+ return row?.data;
563
+ }
564
+ bindCrm(workspace, id, binding, trackIntent = false) {
360
565
  const c = this.scope(workspace, id);
361
566
  if (!binding || binding.conversationId !== id || !/^1\d{10}$/.test(binding.customerPhone) || ![binding.salesName, binding.salesPhone].some((x) => typeof x === "string" && !!x.trim())) throw Error("WECHAT_CRM_BINDING_INVALID");
362
567
  const normalized = { conversationId: id, customerPhone: binding.customerPhone, ...binding.salesName ? { salesName: binding.salesName } : {}, ...binding.salesPhone ? { salesPhone: binding.salesPhone } : {} };
363
568
  if (c.crm && JSON.stringify(JSON.parse(c.crm)) !== JSON.stringify(normalized)) throw Error("CONVERSATION_IDENTITY_CHANGED");
364
- this.db.prepare("UPDATE chats SET crm=? WHERE id=?").run(JSON.stringify(normalized), id);
569
+ if (c.crm) return;
570
+ this.db.exec("BEGIN IMMEDIATE");
571
+ try {
572
+ this.db.prepare("UPDATE chats SET crm=? WHERE id=?").run(JSON.stringify(normalized), id);
573
+ if (trackIntent) this.queueIntentRow(id, Date.now(), true);
574
+ this.db.exec("COMMIT");
575
+ } catch (error) {
576
+ this.db.exec("ROLLBACK");
577
+ throw error;
578
+ }
365
579
  }
366
580
  getState(workspace, id) {
367
581
  return JSON.parse(this.scope(workspace, id).state);
368
582
  }
369
583
  saveState(workspace, id, state) {
370
584
  const c = this.scope(workspace, id);
371
- if (!state || Object.keys(state).some((k) => !["draft", "draftKind", "progress", "sourceVersion"].includes(k)) || state.draft !== void 0 && (typeof state.draft !== "string" || state.draft.length > 5e4) || state.draftKind !== void 0 && !["edited", "agent", "empty"].includes(state.draftKind) || state.sourceVersion !== void 0 && (!Number.isSafeInteger(state.sourceVersion) || state.sourceVersion < 0)) throw Error("WECHAT_STATE_INVALID");
372
- if (state.draftKind === "agent" && state.sourceVersion !== c.version) throw Error("WECHAT_STATE_STALE");
585
+ if (!state || Object.keys(state).some((k) => !["draft", "draftKind", "progress", "sourceVersion", "generationError", "generationNoReply", "autoDraftedMessageId", "autoDraftSuggestion"].includes(k)) || state.draft !== void 0 && (typeof state.draft !== "string" || state.draft.length > 5e4) || state.draftKind !== void 0 && !["edited", "agent", "empty"].includes(state.draftKind) || state.sourceVersion !== void 0 && (!Number.isSafeInteger(state.sourceVersion) || state.sourceVersion < 0)) throw Error("WECHAT_STATE_INVALID");
586
+ if (state.generationError !== void 0 && (typeof state.generationError !== "string" || state.generationError.length > 1e3)) throw Error("WECHAT_STATE_INVALID");
587
+ if (state.generationNoReply !== void 0 && state.generationNoReply !== true) throw Error("WECHAT_STATE_INVALID");
588
+ if ((state.draftKind === "agent" || state.generationError || state.generationNoReply) && state.sourceVersion !== c.version) throw Error("WECHAT_STATE_STALE");
589
+ const prior = JSON.parse(c.state);
590
+ if (state.autoDraftedMessageId !== void 0 && (state.sourceVersion !== c.version || typeof state.autoDraftedMessageId !== "string" || this.project(c, 100).wechat?.autoDraftMessageId !== state.autoDraftedMessageId && prior.autoDraftedMessageId !== state.autoDraftedMessageId)) throw Error("WECHAT_STATE_STALE");
591
+ if (state.autoDraftSuggestion !== void 0) {
592
+ const suggestion = state.autoDraftSuggestion;
593
+ if (state.sourceVersion !== c.version || state.draftKind !== "edited" || !suggestion || Object.keys(suggestion).sort().join(",") !== "judgment,next_step,no_send,wechat" || typeof suggestion.no_send !== "boolean" || ["judgment", "wechat", "next_step"].some((key) => typeof suggestion[key] !== "string" || suggestion[key].length > 5e4)) throw Error("WECHAT_STATE_INVALID");
594
+ }
595
+ if (prior.autoDraftedMessageId && state.autoDraftedMessageId === void 0) state = { ...state, autoDraftedMessageId: prior.autoDraftedMessageId };
373
596
  if (state.progress) state = { ...state, progress: parseSavedProgress(state.progress) };
374
- this.db.prepare("UPDATE chats SET state=? WHERE id=?").run(JSON.stringify(state), id);
597
+ const encoded = JSON.stringify(state);
598
+ if (encoded === c.state) return false;
599
+ this.db.prepare("UPDATE chats SET state=? WHERE id=?").run(encoded, id);
600
+ return true;
375
601
  }
376
602
  markHandled(workspace, id) {
377
603
  this.scope(workspace, id);
@@ -394,7 +620,7 @@ var WechatRepository = class _WechatRepository {
394
620
 
395
621
  // src/wechat/repository-worker.ts
396
622
  var repository = await WechatRepository.open(workerData.root);
397
- var allowed = /* @__PURE__ */ new Set(["importBatch", "listContacts", "getContact", "listMessages", "getMedia", "bindCrm", "getState", "saveState", "markHandled", "getPairing"]);
623
+ var allowed = /* @__PURE__ */ new Set(["importBatch", "listContacts", "getContact", "listMessages", "getMedia", "getDraftVoice", "bindCrm", "getState", "saveState", "markHandled", "getPairing", "getDeliverySource", "claimDelivery", "settleDelivery", "deliveryStatus", "queueIntent", "seedIntents", "nextIntent", "getIntentInput", "finishIntent"]);
398
624
  parentPort.on("message", ({ id, method, args }) => {
399
625
  try {
400
626
  if (!allowed.has(method)) throw Error("WECHAT_OPERATION_INVALID");
@@ -1,5 +1,40 @@
1
1
  # Agent 自动记录与检索质量
2
2
 
3
+ ## 当前版本:2026-11-17 评估器 v2
4
+
5
+ 测试项目为 [wanji-sales-test](http://192.168.3.94:3300/project/wanji-sales-test/evals),本机通过既有 13300 隧道访问。共享配置 `~/.config/wanji-sales/langfuse.json` 中 `knowledgeEvaluationV2:true` 启用新版;必须同时提供已有的私有 `redactionKeyFile`,读取失败时关闭采集,不退回明文。手机号、邮件及显式秘密字段在写队列前处理;这不是完备的敏感内容识别系统。
6
+
7
+ 当前原生评估器仅保留五项:`AI_检索相关性_v2`、`AI_上下文充分性_v2`、`AI_资料适用性_v1`、`AI_回答证据支持度_v1`、`AI_缺证据处理_v1`。原相关性/充分性 v1 和旧规则已按用户要求删除,74 条已有评分保留。旧安装命令转入新版安装器,不会重建旧评估器。
8
+
9
+ Host 监听正式 `session/event`,前瞻记录原始用户问题、同会话同轮次的实际检索及已确认原文读取、完成后的最终回答;不读取历史会话快照或思维链。仅当前内部销售测试库在白名单内,生产关闭规则不变;素材库尚未开启日常 Agent 自动评分。缺原始问题/回答、取消、中断、超限、来源范围不明或同 ID 正文变化时不生成完整回答评分。通过已授权文档 ID 的分页读取纳入本轮证据;不同轮次不继承旧证据。
10
+
11
+ 原生检索相关性仍是 AI 自报分。其 `scoreExplanation` 必须包含序列化 JSON `{"chunks":[{"id":"实际复合ID","score":0.5,"quote":"真实短引文"}]}`。后台独立验证 ID、片段覆盖、0/0.5/1 档位及逐字引文后,才写入 `retrieval_relevance_valid_v2=1`、`retrieval_relevance_mean_v2`、`retrieval_relevance_top1_v2`、`retrieval_relevance_top3_v2`。Top3 是实际前三片段的平均相关性,分母为 min(3, 实际片段数),不等于有标注的 Precision@3。空结果不生成无意义均值;非法理由记校验失败,不伪造均值。原生评分异步产生,缺分保留队列并公平重试,不重新检索;验证队列满时也先尝试排空。私有队列新增 `judgments/`,沿用原目标隔离。
12
+
13
+ 充分性区分已支持、缺失、冲突,仅评价业务问题;空证据为 0 仅表示不足。资料适用性返回“适用 / 不适用 / 无法核实”。最终回答在独立的 `knowledge_answer` observation 上评估事实支持及缺证据处理;纯工具执行说明不要求知识正文证明,对“全库不存在”之类结论仍要求相应覆盖证据。人工校准待完成,不能把 HEALTHY 当作评分准确性认证。
14
+
15
+ 从本仓库根目录安装/检查:
16
+
17
+ ```sh
18
+ node plugins/sales-assistant/scripts/install-knowledge-judges.mjs wanji-knowledge-judge deepseek-v4.1-flash
19
+ node plugins/sales-assistant/scripts/langfuse-target.mjs check-agent remote
20
+ ```
21
+
22
+ 安装器仅处理当前测试项目;默认定义冲突即停止,明确使用 `--revise` 才创建新的原生定义版本,旧评分不改写。不能再传旧版 config/target 位置参数。目标切换检查新版五项及两条规则。
23
+
24
+ 可对已保存数据只读复核或显式写入校验指标(无需模型或重新检索):
25
+
26
+ ```sh
27
+ node plugins/sales-assistant/scripts/validate-knowledge-judgments.mjs --session=<session-id>
28
+ node plugins/sales-assistant/scripts/validate-knowledge-judgments.mjs --session=<session-id> --write
29
+ node plugins/sales-assistant/scripts/audit-knowledge-storage.mjs <source.json> <live.json> <report.json> --write
30
+ ```
31
+
32
+ 存储审计输入必须区分发布源清单和现场快照;比较实际正文摘要、解析状态、唯一切块、正文覆盖、真实向量条目、明确版本/归档/删除和实测链接/权限。直接正文比对允许精确复制的 Markdown 标题/表头和重叠;生成摘要不当原文。缺证据为 unknown,归档状态不代表实际检索隔离;链接 Range 可达不等于完整文件哈希一致。Langfuse v4 events_only 使用 `/api/public/v2/observations` 和 `/api/public/v3/scores` 读回,旧 traces/scores GET 不适用。
33
+
34
+ 实际验证与限制见 [本轮回执](verification/knowledge-judges-v2-2026-11-17.md)。下文保留旧 v1 路径的历史背景;当前接入及安装以本节为准。
35
+
36
+ ## 旧 v1 路径历史说明
37
+
3
38
  当前实现位于销售助手 Host,监听 Harness 官方 `tools/execute` 和 `tools/result`。不修改 dsh-weknora、Harness 核心或 Langfuse 源码,也不重新检索来凑评测结果。
4
39
 
5
40
  ## 当前启用范围
@@ -76,3 +111,26 @@ node plugins/sales-assistant/scripts/langfuse-target.mjs switch remote
76
111
  私有回执目录 `/Users/imac/Code/万机/langfuse/.state/agent-knowledge-20261113/` 保存 observations、scores、配置回滚备份和界面验收。自动化覆盖真实 Harness Native/PTC、重复调用、子 Agent 身份、拒绝/取消、测试页隔离、离线重试、目标冻结、崩溃恢复和迁移前校验。
77
112
 
78
113
  最终追加验收:重复同一个问题实际生成新调用,总计 3 次 Agent 搜索、1 次读取、6 个 AI 分数;采集参数及模型可见内容逐条与 Harness 会话日志完全一致。两个原搜索的同 ID 重传未新增评测任务。独立审查发现的满队列恢复问题已用 1000 条积压复现并修复;销售测试 129/129、Harness 集成 2/2、打包消费 1/1、Python 6/6,类型检查与构建通过。当前捕获开销的 30 次本地空结果夹具测量中位数约 9.9ms,不代表真实搜索/模型的整体延迟保证。
114
+
115
+ ## 2026-11-18 本机问答采集
116
+
117
+ 本地测试 profile 配置 `salesQuestionTracing: true`、`agentKnowledgeTracing: true` 和 Host 私有 `langfuseConfigFile`,目标为 `wanji-sales-test`。目标凭据引用由本机钥匙串解析。局域网 HTTP 地址需要在目标配置显式设置 `allowPrivateHttp: true`。默认仍要求 HTTPS 或回环地址。
118
+
119
+ - 销售工作台手动和自动起草共用采集入口。按客户匿名标识分组,保存本轮问题、审核后的草稿或失败、不需回复、取消等状态。
120
+ - 销售知识 Agent 的合格回答复用现有 V2 评估。显式调用销售技能、使用销售检索工具或继续本次已识别的销售会话时,未进入 V2 的问答仍可作为会话记录查看。
121
+ - 知识库测试页直接搜索保存查询和有限结果摘要。工作台内部搜索与独立检索测试批次保留各自原有职责。
122
+ - 所有新增问答都在 `knowledge-agent` 下查看。采集不等同打分,完整的知识证据仍是触发现有 V2 评估的条件。问题和回复在写入本机上传队列前掩码;中断、失败和重试不会重新运行模型或再查知识库。
123
+
124
+ 本机实际生成 16 字草稿,Langfuse 读回对应问题和答案。独立真实 Harness 另外验证了销售回复、知识搜索和知识 Agent 的问答。已补录两条能与 SQLite 当前草稿及消息版本一一对应的历史记录。历史 DSH 日志混有批量评测、模型提示和内部执行,未将其整体导入。原始客户内容、密钥和诊断回执保存在本机。
125
+
126
+ ## 测试环境默认同步
127
+
128
+ 测试安装使用支持转发的销售助手与 WeKnora 连接插件。连接到现有测试知识库后,新产生的销售回复、销售 Agent 问答和知识库测试搜索默认进入 Langfuse 的 `wanji-sales-test` 项目,环境为 `knowledge-agent`。电脑沿用原有的知识库连接及限定权限的 API Key,Langfuse 项目密钥由测试服务保存。
129
+
130
+ 销售助手先掩码电话、邮箱、链接和凭据,再将问答写入本机队列。断网和转发故障期间保留记录,恢复后以同一个事件 ID 补传。服务端再次掩码,访问日志只记录该接口的请求元信息。已有显式 `langfuseConfigFile` 的测试配置继续使用原直连路径。设置 `salesQuestionTracing: false` 可关闭问答采集。
131
+
132
+ 此功能作用于配置了指定测试知识库的销售环境。生产环境及其他知识库默认关闭。默认路径可查看问答和完成状态,现有 V2 自动评估仍按知识证据规则执行。
133
+
134
+ 2026-11-18 验收使用发布 `20261118-sales-question-relay-02`。独立 macOS DSH 加载两份测试安装包,仍使用原有知识库鉴权,本机没有配置 Langfuse。服务启用前生成的草稿在 Host 重启后补传。Langfuse 分别读回一条草稿、一条知识库测试搜索和一条销售 Agent 问答,待传队列归零。验收使用合成问题,实际执行销售生成和知识库检索。Windows 同用 Host 代码,真机专项验收待补。
135
+
136
+ 第一次测试发布发现容器进程读取不了 root 所有的凭据文件,且旧访问日志会捕获请求正文。第二版按应用进程 UID 1000 装载私有文件,并禁止该路径的请求和响应正文日志。上线后匿名访问返回 401,原有知识库检索返回 200,三条转发请求返回 200,访问日志中无正文。
@@ -0,0 +1,48 @@
1
+ # 客户素材库独立召回 · 2026-11-17
2
+
3
+ 用户明确要求:当前操作问题,或前置电话中客户已提及且未撤回的相关需求,可以提供对应视频/文档;素材须单独从“万机客户素材库”检索。基础修复已通过449项单测、50个真实DSH临时会话释放、真实操作资料版本绑定API验收;全量回答效果仍受当前Flash通道额度耗尽阻断,不能宣称语义验收全部完成。
4
+
5
+ ## 已确认来源和边界
6
+
7
+ - 文本库:`3e6f197b-30a5-41bb-8c2b-228e47026762`,当前256篇/247启用;素材库:`1f93aee2-6d66-42d7-8b7a-b5fe5d094550`,73张素材卡,35视频、35文档页、3图片,对应39个文件。
8
+ - 沿用当前DSH、Flash、WeKnora工具和本仓库插件。同级WeKnora工具已补充已知来源/素材元数据传递,62项回归通过。复用现有仅retrieve权限的双库连接,不新建或扩大密钥权限;凭据仅存Host私有文件。
9
+ - 草稿提供素材卡中的可打开/下载链接,文档保留页码;发送仍使用既有微信链路。本轮不向真实客户发测试消息,不修改现有发送器和授权流程。
10
+ - 素材不批准价格、权益、现版功能开通或执行结果。门店/标准/专业版严格匹配;“企业版”不自动等于“专业版”。版本不明时先说明缺项,不错配。
11
+
12
+ ## 实施契约
13
+
14
+ 1. `turn-plan.ts`增加可选`material_need`:查询、类型、版本、客户来源ID。现有七字段协议兼容;只有客户证据可触发,旧销售/公司话不能冒充客户需求。当前停联/拒发优先于电话旧需求,查询不带手机号/账号。
15
+ 2. `material-retrieval.ts`单独调用配置的素材工具前缀与唯一素材库ID;不会拿文本库链接充数。返回来源绑定的候选,限制最多6张;停用、错版、截断、伪造URL/哈希/版本及非公开卡拒绝。
16
+ 3. `runtime/customer-materials.json`保留实际73张卡的版本快照用于复现;同版本内容/身份冲突拒绝。新发布卡或明确升版的卡按当前素材库的公开权限、发布状态、版本及文件身份契约直接使用,不要求修改代码。HEAD核验文件可读,PDF保留页码;同一文件不重复推荐,明确重发可再次提供。
17
+ 4. `agent.ts`在已有规划后按需召回,将候选作为有边界的资料来源交给生成与复核。`{{MATERIAL_n}}`由程序绑定标题/链接,不让模型创造URL;最多2份,保持最终四字段输出。没有匹配或链接不可用时继续回答可知内容,不伪造已发送附件。
18
+ 5. `knowledge-host.ts`新增独立materials读取端点和显式配置,强制素材库范围与当前测试环境;生产测试行为继续关闭。不会重取CRM或电话录音。
19
+
20
+ ## 独立验收
21
+
22
+ 当前要操作视频、电话先提后续未撤回、当前拒发覆盖旧需求、已收资料不重发/明确重发、错误版本拒绝、无匹配、伪造源与链接、失效文件、文本库/素材库分离、真实DSH工具取回及公开文件可读。单测/API与Flash完整生成、真实客户发送分别报告;后两者缺条件时如实待验。
23
+
24
+ 实施状态:功能已接入本地插件,接口夹具及真实DSH素材检索、公开文件HEAD、已发/重发控制通过;完整Flash生成因429套餐额度耗尽待验,未做真实微信外发。仅隔离官方Host配置启用此功能,未修改桌面运行配置或部署。所有开发留在本仓库plugins/sales-assistant,桥接字段修改在同级WeKnora;不提交、推送或部署。
25
+
26
+ 实际案例:门店版盘点视频、标准版销售出库PDF第20页、专业版员工权限视频;未知版本不猜成专业版。证据保存在 `outputs/sales-eval-2000-20261117/live-run1/material-retrieval-api.json`。HEAD可读不等于视频内容已经逐帧复核,也不是微信发送回执。
27
+
28
+
29
+ ## 2026-11-17 真实生成验收补充
30
+
31
+ 独立素材接口之外,增加12个真实Flash生成场景:三版本对应视频/PDF、已加载电话需求、微信撤回、已发去重、明确重发、企业版不冒充专业版、未知版本、只要PDF、销售电话不当客户需求、微信版本更正。最终完整一轮12/12通过,所有先前失败批保留在live-run1/material-generation-attempt1..5。不是把各轮最好回答拼成12/12。无CRM重复拉取、无真实客户发送。
32
+
33
+ 已修复的机制:明确要文档不能选择video/any;明确素材请求不能只写在next_action而漏material_need;素材grant状态高于模型计划,版本未知允许先问必要版本,不要求编造“通用视频”;同片段引用超过5条真实依据不再被当协议错;PDF页码/中文括号/逗号不属于URL,实际链接独立换行。所有真实来源、权限、版本及交付前HEAD仍保留。素材只进入现有草稿发送机制,本次没有验收真实微信外发或部署。
34
+
35
+
36
+ 最终补充:无工具内部生成后,素材未匹配状态新增M0/retrieval_observation同源证据。edition_required不代表已经搜过全库;not_found仅指本轮未召回通过校验的条目;unavailable不等于产品不存在。状态既进入沟通复核也进入事实/蕴含复核,不批准产品条款。修复后最新完整一轮12/12通过且每条无模型tool-call,source-snapshot与核心200题单独留存。
37
+
38
+
39
+ ## 2026-11-17 第二轮召回优化
40
+
41
+ 素材查询同时保留原始主题和指定形态查询(PDF文字指南、视频教程或界面截图),每一路均限定同一素材库与测试冻结ID。启用现有semanticRerank时,只对实际返回且通过来源/版本/权限绑定的候选做主题筛选:优先一份,最多两份直接补充资料,无匹配不拿相似模块充数。PDF页码先参与相关性排序,再按文件去重;链接仍须HEAD检查、宿主grant和交付前重验。未开启semanticRerank时不新增模型调用,类型双路检索仍生效。
42
+
43
+ 本轮初始阶段仅同步73个既有卡片的官方当前正文;逐一核实新增内容仅为资料类别和用途边界,文件哈希、版本、权限、页码及原操作说明未改变,没有远程知识库写入。固定语料与本机快照的修订必须单独留存,不把同步恢复计为代码涨分。正式评测见expanded-2000/optimization/ROUND2-PLAN.md及outputs/sales-round2-20261117/final;人工金标与逐帧视频内容认证尚不由自动通过代替。
44
+
45
+
46
+ 后续按用户已授权的知识补充范围,对3张既有截图卡追加来自逐图视觉核对的可见控件描述,来源文件SHA256、访问权限及产品范围不变,release_version明确更新为20261117-source-image-caption-v11,正文哈希同步;没有新增卡片或将截图当现行账号授权。官方正文、metadata回读及索引completed均留存。最终200题使用这些修订,不能把代码与知识补充的综合效果称为纯代码A/B增益。
47
+
48
+ 下一步投影保留已审核回复中完整的具体建议,或实际选中素材名称;不凭自由计划编造公司条件、回执或新承诺。等待/停联沿用有限动作,投影仍过数据与承诺边界;格式损坏的完整草稿最多补一次JSON修正,修正后仍须经过全部业务审核。
@@ -0,0 +1,24 @@
1
+ ccount@2.0.1
2
+
3
+ (The MIT License)
4
+
5
+ Copyright (c) 2015 Titus Wormer <tituswormer@gmail.com>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining
8
+ a copy of this software and associated documentation files (the
9
+ 'Software'), to deal in the Software without restriction, including
10
+ without limitation the rights to use, copy, modify, merge, publish,
11
+ distribute, sublicense, and/or sell copies of the Software, and to
12
+ permit persons to whom the Software is furnished to do so, subject to
13
+ the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be
16
+ included in all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
19
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,24 @@
1
+ character-entities@2.0.2
2
+
3
+ (The MIT License)
4
+
5
+ Copyright (c) 2015 Titus Wormer <tituswormer@gmail.com>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining
8
+ a copy of this software and associated documentation files (the
9
+ 'Software'), to deal in the Software without restriction, including
10
+ without limitation the rights to use, copy, modify, merge, publish,
11
+ distribute, sublicense, and/or sell copies of the Software, and to
12
+ permit persons to whom the Software is furnished to do so, subject to
13
+ the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be
16
+ included in all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
19
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.