@asd2233996/dsh-auto-context 0.0.0-stage → 1.15.0
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.
- package/LICENSE +21 -0
- package/README.en.md +113 -0
- package/README.md +250 -2
- package/cordis.patch.yml +23 -0
- package/docs/product-introduction.md +282 -0
- package/docs/structured-kb-notes.md +179 -0
- package/lib/actions.js +2758 -0
- package/lib/extract.js +1647 -0
- package/lib/graph.js +1628 -0
- package/lib/groups.js +307 -0
- package/lib/impl.js +170 -0
- package/lib/index.js +43 -0
- package/lib/kb-tools.js +384 -0
- package/lib/kb.js +254 -0
- package/lib/kg-archive.js +1042 -0
- package/lib/kg-store.js +1427 -0
- package/lib/recall.js +62 -0
- package/lib/scan.js +2537 -0
- package/lib/segments.js +660 -0
- package/lib/store.js +365 -0
- package/lib/util.js +64 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +87 -4
package/lib/extract.js
ADDED
|
@@ -0,0 +1,1647 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context-manager — 事实抽取模块(信息库长期记忆的基础)。
|
|
3
|
+
*
|
|
4
|
+
* 职责:把「阶段卡」(用户/助手对话按轮次切出的语义分组)交给一次 AI 调用,
|
|
5
|
+
* 抽取**项目级持久事实**(需求/约束/结构/决策/交付结果/接口/约定),供上层
|
|
6
|
+
* 信息库长期记忆与检索。过程流水账、工具输出、闲聊、临时状态一律不抽。
|
|
7
|
+
*
|
|
8
|
+
* 设计要点(与 lib/scan.js 同风格,但保持独立、不互相 import):
|
|
9
|
+
*
|
|
10
|
+
* 1. **纯函数优先**:prompt 构建、响应解析、字段归一化、稳定 id 都是不碰 IO 的
|
|
11
|
+
* 纯函数;唯一副作用是 `extractFacts` 通过参数注入的 `llm.stream` 发请求。
|
|
12
|
+
* 模块绝不访问 Cordis 的 `ctx`,可直接在 `node --test` 里用假 llm 覆盖。
|
|
13
|
+
*
|
|
14
|
+
* 2. **绝不拖垮宿主**:单批超时 / 模型报错 / 坏 JSON 只记 `lastError` 并让该批
|
|
15
|
+
* 返回 `[]`(降级),整次抽取永远 resolve;唯一例外是调用方主动 abort。
|
|
16
|
+
*
|
|
17
|
+
* 3. **幂等**:事实 id 由 `statement + scopePath + sourceCardId` 稳定哈希得到,
|
|
18
|
+
* 重复抽取同一批卡片得到相同 id,上层可安全去重/更新图谱。
|
|
19
|
+
*
|
|
20
|
+
* 4. **防御式解析**:模型输出常带 ```json 围栏、前后废话、对象包装、尾逗号、
|
|
21
|
+
* 字段大小写差异;解析器逐层降级并做字段归一化,非法条目进 `invalid` 不抛错。
|
|
22
|
+
*
|
|
23
|
+
* 独立测试:`node --test tests/extract.test.mjs`。
|
|
24
|
+
* @module context-manager/extract
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { createHash } from 'node:crypto'
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 事实种类词表(信息库节点 kind)。
|
|
31
|
+
* - requirement:需求与目标(用户对整个项目要做什么/为什么)
|
|
32
|
+
* - constraint:约束与规则(必须/禁止/技术原则)
|
|
33
|
+
* - structure:项目结构(目录、模块、分层、关键组成)
|
|
34
|
+
* - decision:关键决策(方案取舍及原因)
|
|
35
|
+
* - result:交付结果(已交付、验证通过、验收结论)
|
|
36
|
+
* - interface:接口契约(API/函数签名/数据结构/协议)
|
|
37
|
+
* - convention:约定与规范(命名、风格、流程约定)
|
|
38
|
+
*/
|
|
39
|
+
export const FACT_KINDS = [
|
|
40
|
+
{ id: 'requirement', label: '需求与目标' },
|
|
41
|
+
{ id: 'constraint', label: '约束与规则' },
|
|
42
|
+
{ id: 'structure', label: '项目结构' },
|
|
43
|
+
{ id: 'decision', label: '关键决策' },
|
|
44
|
+
{ id: 'result', label: '交付结果' },
|
|
45
|
+
{ id: 'interface', label: '接口契约' },
|
|
46
|
+
{ id: 'convention', label: '约定与规范' },
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
/** 置信度三档(供图谱层排序/衰减用)。 */
|
|
50
|
+
export const CONFIDENCES = [
|
|
51
|
+
{ id: 'high', label: '高' },
|
|
52
|
+
{ id: 'medium', label: '中' },
|
|
53
|
+
{ id: 'low', label: '低' },
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
/** 事实状态:新抽取默认 active;superseded/archived 由上层图谱演进时使用。 */
|
|
57
|
+
export const FACT_STATUSES = ['active', 'superseded', 'archived']
|
|
58
|
+
|
|
59
|
+
/** Prompt 语义版本:prompt 规则变化时递增,宿主可据此决定是否重抽(不影响事实 id)。 */
|
|
60
|
+
export const EXTRACT_PROMPT_VERSION = 'fact-v2'
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 默认抽取配置。宿主可以只覆盖其中几项;内部会把缺省项补齐并校验非法值。
|
|
64
|
+
*/
|
|
65
|
+
export const DEFAULT_EXTRACT_CONFIG = {
|
|
66
|
+
batchSize: 20, // 每批卡片数
|
|
67
|
+
maxTokens: 2000, // 单批模型输出上限
|
|
68
|
+
previewChars: 900, // 每张卡片送进 prompt 的预览字符数上限
|
|
69
|
+
temperature: 0.1, // 抽取要稳定,温度低
|
|
70
|
+
timeoutMs: 90_000, // 单批超时
|
|
71
|
+
maxConcurrentBatches: 1, // 默认串行:同一 session 网关通常只允许单并发流
|
|
72
|
+
maxCardsPerPass: 200, // 单次抽取最多处理的卡片数
|
|
73
|
+
retries: 2, // 每批失败后的重试次数(不含首次尝试)
|
|
74
|
+
retryDelayMs: 1500, // 重试退避基数:第 n 次重试前等待 retryDelayMs * 2^(n-1)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** statement 的字符上限(按 code point)。 */
|
|
78
|
+
const STATEMENT_MAX_CHARS = 80
|
|
79
|
+
|
|
80
|
+
/** scopePath 最多保留几段。 */
|
|
81
|
+
const SCOPE_MAX_SEGMENTS = 8
|
|
82
|
+
|
|
83
|
+
/** scopePath 单段字符上限。 */
|
|
84
|
+
const SCOPE_SEGMENT_MAX_CHARS = 48
|
|
85
|
+
|
|
86
|
+
/** entities 最多保留几个。 */
|
|
87
|
+
const ENTITY_MAX = 8
|
|
88
|
+
|
|
89
|
+
/** 单个 entity 字符上限。 */
|
|
90
|
+
const ENTITY_MAX_CHARS = 48
|
|
91
|
+
|
|
92
|
+
/** 事实 id 的 16 进制前缀长度。 */
|
|
93
|
+
const FACT_ID_HEX_CHARS = 16
|
|
94
|
+
|
|
95
|
+
/** 预览截断标记。 */
|
|
96
|
+
const TRUNCATED_MARK = '…(已截断)'
|
|
97
|
+
|
|
98
|
+
/** 合法 kind / confidence / status 集合。 */
|
|
99
|
+
const FACT_KIND_SET = new Set(FACT_KINDS.map(kind => kind.id))
|
|
100
|
+
const CONFIDENCE_SET = new Set(CONFIDENCES.map(confidence => confidence.id))
|
|
101
|
+
const FACT_STATUS_SET = new Set(FACT_STATUSES)
|
|
102
|
+
|
|
103
|
+
/** kind 的中文/同义写法 → id(模型偶尔不按词表输出)。 */
|
|
104
|
+
const FACT_KIND_ALIASES = new Map([
|
|
105
|
+
['goal', 'requirement'],
|
|
106
|
+
['需求', 'requirement'],
|
|
107
|
+
['目标', 'requirement'],
|
|
108
|
+
['要求', 'requirement'],
|
|
109
|
+
['rule', 'constraint'],
|
|
110
|
+
['约束', 'constraint'],
|
|
111
|
+
['规则', 'constraint'],
|
|
112
|
+
['限制', 'constraint'],
|
|
113
|
+
['architecture', 'structure'],
|
|
114
|
+
['结构', 'structure'],
|
|
115
|
+
['架构', 'structure'],
|
|
116
|
+
['选择', 'decision'],
|
|
117
|
+
['决定', 'decision'],
|
|
118
|
+
['方案', 'decision'],
|
|
119
|
+
['决策', 'decision'],
|
|
120
|
+
['deliverable', 'result'],
|
|
121
|
+
['交付', 'result'],
|
|
122
|
+
['结果', 'result'],
|
|
123
|
+
['结论', 'result'],
|
|
124
|
+
['outcome', 'result'],
|
|
125
|
+
['api', 'interface'],
|
|
126
|
+
['接口', 'interface'],
|
|
127
|
+
['契约', 'interface'],
|
|
128
|
+
['contract', 'interface'],
|
|
129
|
+
['约定', 'convention'],
|
|
130
|
+
['规范', 'convention'],
|
|
131
|
+
['惯例', 'convention'],
|
|
132
|
+
])
|
|
133
|
+
|
|
134
|
+
/** confidence 中文/同义写法 → id。 */
|
|
135
|
+
const CONFIDENCE_ALIASES = new Map([
|
|
136
|
+
['高', 'high'],
|
|
137
|
+
['中', 'medium'],
|
|
138
|
+
['低', 'low'],
|
|
139
|
+
['mid', 'medium'],
|
|
140
|
+
['normal', 'medium'],
|
|
141
|
+
['medium-confidence', 'medium'],
|
|
142
|
+
['strong', 'high'],
|
|
143
|
+
['weak', 'low'],
|
|
144
|
+
])
|
|
145
|
+
|
|
146
|
+
/** 解析结果文档的字段别名(大小写/下划线/连字符由 normalizeFieldKey 抹平)。 */
|
|
147
|
+
const STATEMENT_KEYS = ['statement', 'text', 'fact', 'content', 'claim', '事实', '陈述']
|
|
148
|
+
const KIND_KEYS = ['kind', 'factkind', 'facttype', 'type', 'category', '种类', '类型']
|
|
149
|
+
const SCOPE_KEYS = ['scopepath', 'scope', 'path', 'hierarchy', '层级', '作用域', '路径']
|
|
150
|
+
const ENTITY_KEYS = ['entities', 'entity', 'keywords', 'tags', '实体', '关键实体']
|
|
151
|
+
const CONFIDENCE_KEYS = ['confidence', 'certainty', 'level', '置信度', '可信度']
|
|
152
|
+
const STATUS_KEYS = ['status', 'state', '状态']
|
|
153
|
+
const SOURCE_CARD_KEYS = ['sourcecardid', 'sourceid', 'cardid', 'card', 'source', '来源卡片']
|
|
154
|
+
const SOURCE_DIRECT_KEYS = ['cardid', 'sourceid', 'sourcecardid', 'card']
|
|
155
|
+
const PROJECT_KEYS = ['projectid', 'project', '项目id', '项目']
|
|
156
|
+
const VALID_FROM_KEYS = ['validfrom', 'validfromat', '生效时间', '起始时间']
|
|
157
|
+
const VALID_UNTIL_KEYS = ['validuntil', 'validto', '失效时间', '结束时间']
|
|
158
|
+
const SUPERSEDED_BY_KEYS = ['supersededby', 'replacedby', '取代者', '被取代为']
|
|
159
|
+
const CREATED_AT_KEYS = ['createdat', 'created', '创建时间']
|
|
160
|
+
const UPDATED_AT_KEYS = ['updatedat', 'updated', '更新时间']
|
|
161
|
+
const LAST_USED_AT_KEYS = ['lastusedat', 'lastused', '最近使用时间']
|
|
162
|
+
const HIT_COUNT_KEYS = ['hitcount', 'hits', 'hittimes', '命中次数']
|
|
163
|
+
const LINEAGE_KEY_KEYS = ['lineagekey', 'lineage', '血统']
|
|
164
|
+
const SEQS_KEYS = ['seqs', 'sequences', 'seq', '序列']
|
|
165
|
+
const SESSION_ID_KEYS = ['sessionid', 'session', '会话id', '会话']
|
|
166
|
+
|
|
167
|
+
/* -------------------------------------------------------------------------- */
|
|
168
|
+
/* 通用小工具 */
|
|
169
|
+
/* -------------------------------------------------------------------------- */
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* 是不是「普通对象」(排除 null / 数组)。
|
|
173
|
+
* @param {unknown} value - 任意值。
|
|
174
|
+
* @returns {boolean} 判断结果。
|
|
175
|
+
*/
|
|
176
|
+
function isRecord(value) {
|
|
177
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 把任意异常转成一行可读文本(绝不抛出)。
|
|
182
|
+
* @param {unknown} error - 任意异常。
|
|
183
|
+
* @returns {string} 文本。
|
|
184
|
+
*/
|
|
185
|
+
function toErrorMessage(error) {
|
|
186
|
+
if (error instanceof Error) return error.message === '' ? error.name : error.message
|
|
187
|
+
try {
|
|
188
|
+
return String(error)
|
|
189
|
+
} catch {
|
|
190
|
+
return '未知错误'
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 把文本压成一行:换行/制表符/连续空白折叠为单个空格并 trim。
|
|
196
|
+
* @param {unknown} value - 任意值。
|
|
197
|
+
* @returns {string} 一行文本。
|
|
198
|
+
*/
|
|
199
|
+
function cleanInline(value) {
|
|
200
|
+
if (typeof value !== 'string') return ''
|
|
201
|
+
return value.replace(/\s+/gu, ' ').trim()
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 找到按 code point 截断的最大 UTF-16 下标(不拆分代理对)。
|
|
206
|
+
* @param {string} text - 文本。
|
|
207
|
+
* @param {number} maxChars - 最大 code point 数。
|
|
208
|
+
* @returns {number} 可安全 slice 的下标。
|
|
209
|
+
*/
|
|
210
|
+
function codePointCutIndex(text, maxChars) {
|
|
211
|
+
if (maxChars <= 0) return 0
|
|
212
|
+
let count = 0
|
|
213
|
+
let index = 0
|
|
214
|
+
while (index < text.length && count < maxChars) {
|
|
215
|
+
const code = text.codePointAt(index)
|
|
216
|
+
index += code !== undefined && code > 0xffff ? 2 : 1
|
|
217
|
+
count += 1
|
|
218
|
+
}
|
|
219
|
+
return index
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 按 code point 截断(不加省略号)。
|
|
224
|
+
* @param {string} text - 文本。
|
|
225
|
+
* @param {number} maxChars - 最大 code point 数。
|
|
226
|
+
* @returns {string} 截断结果。
|
|
227
|
+
*/
|
|
228
|
+
function truncateCodePoints(text, maxChars) {
|
|
229
|
+
if (typeof text !== 'string' || text === '') return ''
|
|
230
|
+
if (maxChars <= 0) return ''
|
|
231
|
+
const cut = codePointCutIndex(text, maxChars)
|
|
232
|
+
return cut >= text.length ? text : text.slice(0, cut)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 截断卡片预览并追加「…(已截断)」标记。
|
|
237
|
+
* @param {string} text - 预览文本。
|
|
238
|
+
* @param {number} maxChars - 上限。
|
|
239
|
+
* @returns {string} 截断结果。
|
|
240
|
+
*/
|
|
241
|
+
function truncatePreview(text, maxChars) {
|
|
242
|
+
if (typeof text !== 'string' || text === '') return ''
|
|
243
|
+
if (maxChars <= 0) return TRUNCATED_MARK
|
|
244
|
+
const cut = codePointCutIndex(text, maxChars)
|
|
245
|
+
return cut >= text.length ? text : `${text.slice(0, cut)}${TRUNCATED_MARK}`
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 依次取第一个非空字符串(数字会转字符串)。
|
|
250
|
+
* @param {...unknown} values - 候选值。
|
|
251
|
+
* @returns {string} 结果或空串。
|
|
252
|
+
*/
|
|
253
|
+
function pickString(...values) {
|
|
254
|
+
for (const value of values) {
|
|
255
|
+
if (typeof value === 'string' && value.trim() !== '') return value
|
|
256
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
257
|
+
}
|
|
258
|
+
return ''
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 读取非负整数,非法返回 null。
|
|
263
|
+
* @param {unknown} value - 原始值。
|
|
264
|
+
* @returns {number | null} 整数或 null。
|
|
265
|
+
*/
|
|
266
|
+
function readNonNegativeInt(value) {
|
|
267
|
+
let number = NaN
|
|
268
|
+
if (typeof value === 'number') number = value
|
|
269
|
+
else if (typeof value === 'string' && value.trim() !== '') number = Number(value)
|
|
270
|
+
if (!Number.isFinite(number) || number < 0) return null
|
|
271
|
+
return Math.round(number)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* config 里读正整数,非法回退默认值。
|
|
276
|
+
* @param {unknown} value - 原始值。
|
|
277
|
+
* @param {number} fallback - 默认值。
|
|
278
|
+
* @returns {number} 合法正整数。
|
|
279
|
+
*/
|
|
280
|
+
function readPositiveInt(value, fallback) {
|
|
281
|
+
const number = typeof value === 'number' ? value : NaN
|
|
282
|
+
return Number.isFinite(number) && number >= 1 ? Math.floor(number) : fallback
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* config 里读非负整数(0 合法,用于 retries / retryDelayMs)。
|
|
287
|
+
* @param {unknown} value - 原始值。
|
|
288
|
+
* @param {number} fallback - 默认值。
|
|
289
|
+
* @returns {number} 合法非负整数。
|
|
290
|
+
*/
|
|
291
|
+
function readNonNegativeConfigInt(value, fallback) {
|
|
292
|
+
const number = typeof value === 'number' ? value : NaN
|
|
293
|
+
return Number.isFinite(number) && number >= 0 ? Math.floor(number) : fallback
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* config 里读闭区间数字。
|
|
298
|
+
* @param {unknown} value - 原始值。
|
|
299
|
+
* @param {number} fallback - 默认值。
|
|
300
|
+
* @param {number} min - 下界。
|
|
301
|
+
* @param {number} max - 上界。
|
|
302
|
+
* @returns {number} 合法数字。
|
|
303
|
+
*/
|
|
304
|
+
function readBoundedNumber(value, fallback, min, max) {
|
|
305
|
+
const number = typeof value === 'number' ? value : NaN
|
|
306
|
+
return Number.isFinite(number) && number >= min && number <= max ? number : fallback
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* 合并用户配置与默认配置,逐项校验非法值。
|
|
311
|
+
* @param {unknown} config - 调用方传入的部分配置。
|
|
312
|
+
* @returns {typeof DEFAULT_EXTRACT_CONFIG} 完整且合法的配置。
|
|
313
|
+
*/
|
|
314
|
+
function resolveExtractConfig(config) {
|
|
315
|
+
const source = isRecord(config) ? config : {}
|
|
316
|
+
return {
|
|
317
|
+
batchSize: readPositiveInt(source.batchSize, DEFAULT_EXTRACT_CONFIG.batchSize),
|
|
318
|
+
maxTokens: readPositiveInt(source.maxTokens, DEFAULT_EXTRACT_CONFIG.maxTokens),
|
|
319
|
+
previewChars: readPositiveInt(source.previewChars, DEFAULT_EXTRACT_CONFIG.previewChars),
|
|
320
|
+
temperature: readBoundedNumber(source.temperature, DEFAULT_EXTRACT_CONFIG.temperature, 0, 2),
|
|
321
|
+
timeoutMs: readPositiveInt(source.timeoutMs, DEFAULT_EXTRACT_CONFIG.timeoutMs),
|
|
322
|
+
maxConcurrentBatches: readPositiveInt(source.maxConcurrentBatches, DEFAULT_EXTRACT_CONFIG.maxConcurrentBatches),
|
|
323
|
+
maxCardsPerPass: readPositiveInt(source.maxCardsPerPass, DEFAULT_EXTRACT_CONFIG.maxCardsPerPass),
|
|
324
|
+
retries: readNonNegativeConfigInt(source.retries, DEFAULT_EXTRACT_CONFIG.retries),
|
|
325
|
+
retryDelayMs: readNonNegativeConfigInt(source.retryDelayMs, DEFAULT_EXTRACT_CONFIG.retryDelayMs),
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 把数组按 size 切成批(保持顺序,不修改入参)。
|
|
331
|
+
* @template T
|
|
332
|
+
* @param {T[]} list - 原数组。
|
|
333
|
+
* @param {number} size - 每批大小。
|
|
334
|
+
* @returns {T[][]} 批次数组。
|
|
335
|
+
*/
|
|
336
|
+
function chunk(list, size) {
|
|
337
|
+
const batches = []
|
|
338
|
+
for (let index = 0; index < list.length; index += size) {
|
|
339
|
+
batches.push(list.slice(index, index + size))
|
|
340
|
+
}
|
|
341
|
+
return batches
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/* -------------------------------------------------------------------------- */
|
|
345
|
+
/* 字段归一化 */
|
|
346
|
+
/* -------------------------------------------------------------------------- */
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* 归一化字段名:大小写、空格、下划线、连字符都不敏感。
|
|
350
|
+
* @param {string} key - 原始字段名。
|
|
351
|
+
* @returns {string} 归一化字段名。
|
|
352
|
+
*/
|
|
353
|
+
function normalizeFieldKey(key) {
|
|
354
|
+
return String(key).toLowerCase().replace(/[\s_-]+/gu, '')
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* 按别名读取条目字段(大小写不敏感,取第一个命中的别名)。
|
|
359
|
+
* @param {Record<string, unknown>} record - 模型输出的一条事实。
|
|
360
|
+
* @param {string[]} keys - 字段别名(优先顺序)。
|
|
361
|
+
* @returns {unknown} 字段值。
|
|
362
|
+
*/
|
|
363
|
+
function readFieldValue(record, keys) {
|
|
364
|
+
const normalized = new Map()
|
|
365
|
+
for (const [key, value] of Object.entries(record)) {
|
|
366
|
+
const canonical = normalizeFieldKey(key)
|
|
367
|
+
if (!normalized.has(canonical)) normalized.set(canonical, value)
|
|
368
|
+
}
|
|
369
|
+
for (const key of keys) {
|
|
370
|
+
const canonical = normalizeFieldKey(key)
|
|
371
|
+
if (normalized.has(canonical)) return normalized.get(canonical)
|
|
372
|
+
}
|
|
373
|
+
return undefined
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* 读取并清洗 statement(折叠空白 + 按 code point 截断到 80);空返回空串。
|
|
378
|
+
* @param {unknown} value - 原始值。
|
|
379
|
+
* @returns {string} 归一化后的 statement。
|
|
380
|
+
*/
|
|
381
|
+
function normalizeStatement(value) {
|
|
382
|
+
if (typeof value !== 'string' && typeof value !== 'number') return ''
|
|
383
|
+
const text = cleanInline(String(value))
|
|
384
|
+
if (text === '') return ''
|
|
385
|
+
return truncateCodePoints(text, STATEMENT_MAX_CHARS)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* 把 kind 映射到合法 id:非法 → null(调用方跳过该条)。
|
|
390
|
+
* @param {unknown} value - 模型输出里的 kind。
|
|
391
|
+
* @returns {string | null} 合法 kind 或 null。
|
|
392
|
+
*/
|
|
393
|
+
function normalizeFactKind(value) {
|
|
394
|
+
if (typeof value !== 'string') return null
|
|
395
|
+
const text = value.trim()
|
|
396
|
+
if (text === '') return null
|
|
397
|
+
const lower = text.toLowerCase()
|
|
398
|
+
if (FACT_KIND_SET.has(lower)) return lower
|
|
399
|
+
const compact = lower.replace(/[\s_-]+/gu, '')
|
|
400
|
+
if (FACT_KIND_SET.has(compact)) return compact
|
|
401
|
+
return FACT_KIND_ALIASES.get(lower) ?? FACT_KIND_ALIASES.get(compact) ?? null
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* 归一化 confidence:非法/缺失 → 'medium';中文/同义写法也能接住。
|
|
406
|
+
* @param {unknown} value - 模型输出里的 confidence。
|
|
407
|
+
* @returns {'high' | 'medium' | 'low'} 合法置信度。
|
|
408
|
+
*/
|
|
409
|
+
function normalizeConfidence(value) {
|
|
410
|
+
if (typeof value !== 'string') return 'medium'
|
|
411
|
+
const text = value.trim()
|
|
412
|
+
if (text === '') return 'medium'
|
|
413
|
+
const lower = text.toLowerCase()
|
|
414
|
+
if (CONFIDENCE_SET.has(lower)) return lower
|
|
415
|
+
const compact = lower.replace(/[\s_-]+/gu, '')
|
|
416
|
+
if (CONFIDENCE_SET.has(compact)) return compact
|
|
417
|
+
return CONFIDENCE_ALIASES.get(text) ?? CONFIDENCE_ALIASES.get(lower) ?? CONFIDENCE_ALIASES.get(compact) ?? 'medium'
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* 归一化 status:非法/缺失 → 'active'(新抽取的事实默认有效)。
|
|
422
|
+
* @param {unknown} value - 模型输出里的 status。
|
|
423
|
+
* @returns {'active' | 'superseded'} 合法状态。
|
|
424
|
+
*/
|
|
425
|
+
function normalizeStatus(value) {
|
|
426
|
+
if (typeof value !== 'string') return 'active'
|
|
427
|
+
const lower = value.trim().toLowerCase()
|
|
428
|
+
if (FACT_STATUS_SET.has(lower)) return lower
|
|
429
|
+
if (lower === 'archive' || lower === '归档' || lower === '已归档') return 'archived'
|
|
430
|
+
if (lower === 'deprecated' || lower === '过时' || lower === '已取代' || lower === 'supersede') return 'superseded'
|
|
431
|
+
return 'active'
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* 归一化 scopePath:数组或带分隔符的字符串 → 干净的相对层级路径。
|
|
436
|
+
* @param {unknown} value - 模型输出里的 scopePath。
|
|
437
|
+
* @returns {string[]} 路径段数组。
|
|
438
|
+
*/
|
|
439
|
+
function normalizeScopePath(value) {
|
|
440
|
+
let parts = []
|
|
441
|
+
if (Array.isArray(value)) {
|
|
442
|
+
parts = value
|
|
443
|
+
} else if (typeof value === 'string' && value.trim() !== '') {
|
|
444
|
+
parts = value.trim().split(/\s*(?:\/|>|→|::|、|,|,|;|;|\|)\s*/u)
|
|
445
|
+
} else if (typeof value === 'number') {
|
|
446
|
+
parts = [String(value)]
|
|
447
|
+
}
|
|
448
|
+
const path = []
|
|
449
|
+
for (const part of parts) {
|
|
450
|
+
if (typeof part !== 'string') continue
|
|
451
|
+
let segment = cleanInline(part)
|
|
452
|
+
// 去掉首尾的 ./ 与 /,以及路径引导符。
|
|
453
|
+
segment = segment.replace(/^(?:\.?\/+)+/u, '').replace(/\/+$/u, '')
|
|
454
|
+
segment = truncateCodePoints(segment, SCOPE_SEGMENT_MAX_CHARS)
|
|
455
|
+
if (segment === '' || segment === '.' || segment === '..') continue
|
|
456
|
+
if (path.includes(segment)) continue
|
|
457
|
+
path.push(segment)
|
|
458
|
+
if (path.length >= SCOPE_MAX_SEGMENTS) break
|
|
459
|
+
}
|
|
460
|
+
return path
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* 归一化 entities:字符串/数组 → 去重、清洗、最多 8 个。
|
|
465
|
+
* @param {unknown} value - 模型输出里的 entities。
|
|
466
|
+
* @returns {string[]} 实体数组。
|
|
467
|
+
*/
|
|
468
|
+
function normalizeEntities(value) {
|
|
469
|
+
const entities = []
|
|
470
|
+
/**
|
|
471
|
+
* 追加一个实体。
|
|
472
|
+
* @param {unknown} raw - 原始实体。
|
|
473
|
+
*/
|
|
474
|
+
const push = raw => {
|
|
475
|
+
if (typeof raw !== 'string' && typeof raw !== 'number') return
|
|
476
|
+
const text = truncateCodePoints(cleanInline(String(raw)), ENTITY_MAX_CHARS)
|
|
477
|
+
if (text === '' || entities.includes(text)) return
|
|
478
|
+
entities.push(text)
|
|
479
|
+
}
|
|
480
|
+
const walk = raw => {
|
|
481
|
+
if (typeof raw === 'string') {
|
|
482
|
+
for (const part of raw.split(/[,,、;;|/]+/u)) push(part)
|
|
483
|
+
return
|
|
484
|
+
}
|
|
485
|
+
if (Array.isArray(raw)) {
|
|
486
|
+
for (const item of raw) walk(item)
|
|
487
|
+
return
|
|
488
|
+
}
|
|
489
|
+
if (isRecord(raw)) push(pickString(raw.name, raw.text, raw.id))
|
|
490
|
+
}
|
|
491
|
+
walk(value)
|
|
492
|
+
return entities.slice(0, ENTITY_MAX)
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* 读取事实的来源卡片 id(容忍 source 对象 / 各种别名)。
|
|
497
|
+
* @param {Record<string, unknown>} record - 模型输出的一条事实。
|
|
498
|
+
* @returns {string} 来源卡片 id(缺失为空串)。
|
|
499
|
+
*/
|
|
500
|
+
function normalizeSourceCardId(record) {
|
|
501
|
+
const source = readFieldValue(record, SOURCE_CARD_KEYS)
|
|
502
|
+
if (typeof source === 'string' && source.trim() !== '') return source.trim()
|
|
503
|
+
if (typeof source === 'number' && Number.isFinite(source)) return String(Math.round(source))
|
|
504
|
+
if (isRecord(source)) {
|
|
505
|
+
const nested = pickString(source.cardId, source.cardid, source.sourceCardId, source.id, source.card)
|
|
506
|
+
if (nested.trim() !== '') return nested.trim()
|
|
507
|
+
}
|
|
508
|
+
const direct = pickString(readFieldValue(record, SOURCE_DIRECT_KEYS))
|
|
509
|
+
return direct.trim()
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/* -------------------------------------------------------------------------- */
|
|
513
|
+
/* v15.1 FACT 契约扩展:时间/生存、血缘、projectId 归一化 */
|
|
514
|
+
/* -------------------------------------------------------------------------- */
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* 时间戳归一化:数字(毫秒;10 位秒级自动 ×1000)或 ISO 字符串 → 毫秒时间戳;
|
|
518
|
+
* 非法/缺失返回 fallback。
|
|
519
|
+
* @param {unknown} value - 原始时间值。
|
|
520
|
+
* @param {number | null} fallback - 兜底值(null 表示「没有」)。
|
|
521
|
+
* @returns {number | null} 毫秒时间戳或 null。
|
|
522
|
+
*/
|
|
523
|
+
function normalizeTimestamp(value, fallback) {
|
|
524
|
+
if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {
|
|
525
|
+
return Math.round(value < 1e12 ? value * 1000 : value)
|
|
526
|
+
}
|
|
527
|
+
if (typeof value === 'string' && value.trim() !== '') {
|
|
528
|
+
const text = value.trim()
|
|
529
|
+
const parsed = Date.parse(text)
|
|
530
|
+
if (Number.isFinite(parsed)) return parsed
|
|
531
|
+
const numeric = Number(text)
|
|
532
|
+
if (Number.isFinite(numeric) && numeric >= 0) return Math.round(numeric < 1e12 ? numeric * 1000 : numeric)
|
|
533
|
+
}
|
|
534
|
+
return fallback
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* 归一化 seqs(对话序号数组):支持数组 / 逗号分隔字符串,去重并升序。
|
|
539
|
+
* @param {unknown} value - 原始值。
|
|
540
|
+
* @returns {number[]} 合法序号数组(最多 500 个)。
|
|
541
|
+
*/
|
|
542
|
+
function normalizeSeqList(value) {
|
|
543
|
+
const seqs = []
|
|
544
|
+
const push = raw => {
|
|
545
|
+
const number = readNonNegativeInt(raw)
|
|
546
|
+
if (number === null || seqs.includes(number)) return
|
|
547
|
+
seqs.push(number)
|
|
548
|
+
}
|
|
549
|
+
const walk = raw => {
|
|
550
|
+
if (Array.isArray(raw)) {
|
|
551
|
+
for (const item of raw) walk(item)
|
|
552
|
+
return
|
|
553
|
+
}
|
|
554
|
+
if (typeof raw === 'string') {
|
|
555
|
+
for (const part of raw.split(/[,,、;;\s]+/u)) push(part)
|
|
556
|
+
return
|
|
557
|
+
}
|
|
558
|
+
push(raw)
|
|
559
|
+
}
|
|
560
|
+
walk(value)
|
|
561
|
+
return seqs.sort((a, b) => a - b).slice(0, 500)
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* 归一化 lineageKey(卡片血统稳定标识,restore 后 group id 变化也能追溯)。
|
|
566
|
+
* @param {unknown} value - 原始值。
|
|
567
|
+
* @returns {string} 清理后的字符串(缺失为空串)。
|
|
568
|
+
*/
|
|
569
|
+
function normalizeLineageKey(value) {
|
|
570
|
+
if (typeof value !== 'string' && typeof value !== 'number') return ''
|
|
571
|
+
return truncateCodePoints(cleanInline(String(value)), 120)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* 归一化 projectId(顶层与 source 共用)。
|
|
576
|
+
* @param {unknown} value - 原始值。
|
|
577
|
+
* @returns {string} 清理后的 projectId(缺失为空串)。
|
|
578
|
+
*/
|
|
579
|
+
function normalizeProjectId(value) {
|
|
580
|
+
if (typeof value !== 'string' && typeof value !== 'number') return ''
|
|
581
|
+
return truncateCodePoints(cleanInline(String(value)), 120)
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* 归一化可选字符串 id(sessionId 等)。
|
|
586
|
+
* @param {unknown} value - 原始值。
|
|
587
|
+
* @returns {string} 清理后的 id(缺失为空串)。
|
|
588
|
+
*/
|
|
589
|
+
function normalizeOptionalId(value) {
|
|
590
|
+
return normalizeProjectId(value)
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* 从输入卡片推导 lineageKey:优先 card.lineageKey/card.lineage,其次 units[].lineage。
|
|
595
|
+
* @param {Record<string, unknown>} card - 输入卡片。
|
|
596
|
+
* @returns {string} lineageKey(缺失为空串)。
|
|
597
|
+
*/
|
|
598
|
+
function deriveLineageKey(card) {
|
|
599
|
+
const direct = normalizeLineageKey(card.lineageKey ?? card.lineage)
|
|
600
|
+
if (direct !== '') return direct
|
|
601
|
+
const units = Array.isArray(card.units) ? card.units : []
|
|
602
|
+
for (const unit of units) {
|
|
603
|
+
if (!isRecord(unit)) continue
|
|
604
|
+
const lineage = normalizeLineageKey(unit.lineage ?? unit.lineageKey)
|
|
605
|
+
if (lineage !== '') return lineage
|
|
606
|
+
}
|
|
607
|
+
return ''
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* 从输入卡片推导 seqs:优先 card.seqs,其次汇总 units[].seqs。
|
|
612
|
+
* @param {Record<string, unknown>} card - 输入卡片。
|
|
613
|
+
* @returns {number[]} 去重升序的序号数组。
|
|
614
|
+
*/
|
|
615
|
+
function deriveSeqs(card) {
|
|
616
|
+
const direct = normalizeSeqList(card.seqs)
|
|
617
|
+
if (direct.length > 0) return direct
|
|
618
|
+
const units = Array.isArray(card.units) ? card.units : []
|
|
619
|
+
const collected = []
|
|
620
|
+
for (const unit of units) {
|
|
621
|
+
if (!isRecord(unit)) continue
|
|
622
|
+
collected.push(...normalizeSeqList(unit.seqs))
|
|
623
|
+
}
|
|
624
|
+
return normalizeSeqList(collected)
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* 从输入卡片读取 projectId。
|
|
629
|
+
* @param {Record<string, unknown>} card - 输入卡片。
|
|
630
|
+
* @returns {string} projectId(缺失为空串)。
|
|
631
|
+
*/
|
|
632
|
+
function readCardProjectId(card) {
|
|
633
|
+
return normalizeProjectId(card.projectId ?? card.project)
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/* -------------------------------------------------------------------------- */
|
|
637
|
+
/* 稳定事实 id */
|
|
638
|
+
/* -------------------------------------------------------------------------- */
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* 计算事实的稳定 id:`statement + scopePath + sourceCardId` 的 sha1 前缀。
|
|
642
|
+
*
|
|
643
|
+
* 同一事实重复抽取得到相同 id(幂等);statement / 路径 / 来源卡任一变化都会
|
|
644
|
+
* 产生新 id(图谱层据此更新或保留旧版本)。
|
|
645
|
+
*
|
|
646
|
+
* @param {unknown} statement - 事实陈述。
|
|
647
|
+
* @param {unknown} scopePath - 项目层级路径(数组或字符串)。
|
|
648
|
+
* @param {unknown} sourceCardId - 来源卡片 id。
|
|
649
|
+
* @returns {string} `fact_` + 16 位 16 进制。
|
|
650
|
+
*/
|
|
651
|
+
export function factId(statement, scopePath, sourceCardId) {
|
|
652
|
+
const hash = createHash('sha1')
|
|
653
|
+
const parts = [
|
|
654
|
+
'context-manager/fact',
|
|
655
|
+
cleanInline(typeof statement === 'string' ? statement : String(statement ?? '')),
|
|
656
|
+
normalizeScopePath(scopePath).join('/'),
|
|
657
|
+
typeof sourceCardId === 'string' ? sourceCardId.trim() : String(sourceCardId ?? ''),
|
|
658
|
+
]
|
|
659
|
+
for (const part of parts) {
|
|
660
|
+
hash.update(String(part.length))
|
|
661
|
+
hash.update(':')
|
|
662
|
+
hash.update(part)
|
|
663
|
+
hash.update('\u0000')
|
|
664
|
+
}
|
|
665
|
+
return `fact_${hash.digest('hex').slice(0, FACT_ID_HEX_CHARS)}`
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/* -------------------------------------------------------------------------- */
|
|
669
|
+
/* Prompt */
|
|
670
|
+
/* -------------------------------------------------------------------------- */
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* 读取卡片的原始内容文本(未截断、保留换行)。
|
|
674
|
+
* @param {Record<string, unknown>} card - 卡片。
|
|
675
|
+
* @returns {string} 内容文本。
|
|
676
|
+
*/
|
|
677
|
+
function readCardPreview(card) {
|
|
678
|
+
for (const candidate of [card.preview, card.text, card.body, card.snippet, card.excerpt, card.content]) {
|
|
679
|
+
if (typeof candidate === 'string' && candidate.trim() !== '') return candidate
|
|
680
|
+
if (Array.isArray(candidate)) {
|
|
681
|
+
const text = candidate
|
|
682
|
+
.map(item => (typeof item === 'string' ? item : (isRecord(item) && typeof item.text === 'string' ? item.text : '')))
|
|
683
|
+
.filter(part => part !== '')
|
|
684
|
+
.join('\n')
|
|
685
|
+
if (text.trim() !== '') return text
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return ''
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* 把一张卡片归一化成 prompt 里的展示信息。
|
|
693
|
+
* @param {unknown} card - 输入卡片。
|
|
694
|
+
* @param {typeof DEFAULT_EXTRACT_CONFIG} config - 已解析的配置。
|
|
695
|
+
* @returns {{ id: string, turn: number | null, title: string, summary: string, preview: string }} 展示信息。
|
|
696
|
+
*/
|
|
697
|
+
function normalizeCardForPrompt(card, config) {
|
|
698
|
+
const raw = isRecord(card) ? card : {}
|
|
699
|
+
return {
|
|
700
|
+
id: cleanInline(pickString(raw.id, raw.cardId)),
|
|
701
|
+
turn: readNonNegativeInt(raw.turn ?? raw.turnIndex),
|
|
702
|
+
title: truncateCodePoints(cleanInline(pickString(raw.title, raw.name)), 120),
|
|
703
|
+
summary: truncateCodePoints(cleanInline(pickString(raw.summary, raw.desc, raw.description)), 240),
|
|
704
|
+
preview: truncatePreview(readCardPreview(raw), config.previewChars),
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* 构造事实抽取 prompt(单个中文 user 文本,要求模型只输出 JSON 数组)。
|
|
710
|
+
*
|
|
711
|
+
* @param {unknown} cards - 阶段卡数组(id/turn/title/summary/preview)。
|
|
712
|
+
* @param {unknown} [config] - 部分抽取配置(previewChars 等)。
|
|
713
|
+
* @returns {string} prompt 文本。
|
|
714
|
+
*/
|
|
715
|
+
export function buildFactExtractionPrompt(cards, config = DEFAULT_EXTRACT_CONFIG) {
|
|
716
|
+
const settings = resolveExtractConfig(config)
|
|
717
|
+
const list = Array.isArray(cards) ? cards.filter(card => isRecord(card)) : []
|
|
718
|
+
const normalized = list.map(card => normalizeCardForPrompt(card, settings))
|
|
719
|
+
const lines = []
|
|
720
|
+
|
|
721
|
+
lines.push('你是「上下文管理器」信息库的事实抽取引擎。输入是一段对话按轮次切出的「阶段卡」;你的任务是从中抽取**项目级持久事实**,供信息库长期记忆与后续检索。')
|
|
722
|
+
lines.push('')
|
|
723
|
+
lines.push('抽取规则(必须严格遵守):')
|
|
724
|
+
lines.push('1. 只抽取「项目级、跨会话仍然成立」的事实,kind 只能取以下 7 种:')
|
|
725
|
+
lines.push(' - "requirement":需求与目标(用户对整个项目要做什么、为什么做)')
|
|
726
|
+
lines.push(' - "constraint":约束与规则(必须遵守 / 禁止 / 技术原则 / 不能违反的限制)')
|
|
727
|
+
lines.push(' - "structure":项目结构(目录、模块、分层、关键组成部分)')
|
|
728
|
+
lines.push(' - "decision":关键决策(方案取舍及原因)')
|
|
729
|
+
lines.push(' - "result":交付结果(已交付、验证通过、验收结论)')
|
|
730
|
+
lines.push(' - "interface":接口契约(API / 函数签名 / 数据结构 / 协议)')
|
|
731
|
+
lines.push(' - "convention":约定与规范(命名、风格、流程约定)')
|
|
732
|
+
lines.push('2. **不要**抽取:实现过程流水账、工具/命令输出、普通闲聊与确认、临时状态(等待/进行中/本次尝试)、一次性调试细节。这些不是持久事实。')
|
|
733
|
+
lines.push('3. statement 必须**自包含**:写清「主语 + 结论/原因」,脱离上下文也能独立读懂;禁止用“它 / 该功能 / 此方案 / 刚才 / 如上”等指代;只从卡片原文抽取,不补充、不猜测、不推断未写明的信息;≤80 个汉字/字符。')
|
|
734
|
+
lines.push('4. scopePath 是项目内相对层级路径(字符串数组,如 ["context-manager","host","scan"];无法判断时用 []),不要写绝对路径。')
|
|
735
|
+
lines.push('5. entities 列出事实涉及的关键实体(模块名 / 文件名 / 函数名 / 接口名 / 技术名),最多 8 个,去重。')
|
|
736
|
+
lines.push('6. confidence 只能取 "high" | "medium" | "low"(明确且关键=high;一般=medium;推断=low)。')
|
|
737
|
+
lines.push('7. 每条事实必须带 sourceCardId(就是下方卡片的 id,原样照抄)。')
|
|
738
|
+
lines.push('8. 没有可抽取的持久事实时只输出 [],不要输出空对象或解释。')
|
|
739
|
+
lines.push('9. 只输出一个严格的 JSON 数组,不要 Markdown 代码围栏,不要任何解释/前后缀。')
|
|
740
|
+
lines.push('')
|
|
741
|
+
lines.push('每个元素的格式:{"sourceCardId":"卡片id","statement":"≤80字的自包含事实","kind":"requirement","scopePath":["context-manager","host"],"entities":["scan.js"],"confidence":"high"}')
|
|
742
|
+
lines.push('')
|
|
743
|
+
lines.push(`卡片共 ${normalized.length} 张:`)
|
|
744
|
+
|
|
745
|
+
for (let index = 0; index < normalized.length; index += 1) {
|
|
746
|
+
const card = normalized[index]
|
|
747
|
+
lines.push('')
|
|
748
|
+
lines.push(`--- 卡片 ${index + 1} / ${normalized.length} ---`)
|
|
749
|
+
lines.push(`id: ${card.id === '' ? '(缺失)' : card.id}`)
|
|
750
|
+
lines.push(`turn: ${card.turn === null ? '未知' : String(card.turn)}`)
|
|
751
|
+
lines.push(`标题: ${card.title === '' ? '(未提供)' : card.title}`)
|
|
752
|
+
lines.push(`简介: ${card.summary === '' ? '(未提供)' : card.summary}`)
|
|
753
|
+
lines.push('内容预览:')
|
|
754
|
+
lines.push(card.preview === '' ? '(无预览内容)' : card.preview)
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
lines.push('')
|
|
758
|
+
lines.push('请现在输出 JSON 数组(没有持久事实就输出 []):')
|
|
759
|
+
return lines.join('\n')
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/* -------------------------------------------------------------------------- */
|
|
763
|
+
/* 响应解析 */
|
|
764
|
+
/* -------------------------------------------------------------------------- */
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* 去掉 JSON 里对象/数组末尾多余的逗号(字符串内部的逗号不动)。
|
|
768
|
+
* @param {string} text - 原始 JSON 文本。
|
|
769
|
+
* @returns {string} 修复后的文本。
|
|
770
|
+
*/
|
|
771
|
+
function stripTrailingCommas(text) {
|
|
772
|
+
let out = ''
|
|
773
|
+
let inString = false
|
|
774
|
+
let escaped = false
|
|
775
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
776
|
+
const char = text[index]
|
|
777
|
+
if (inString) {
|
|
778
|
+
out += char
|
|
779
|
+
if (escaped) escaped = false
|
|
780
|
+
else if (char === '\\') escaped = true
|
|
781
|
+
else if (char === '"') inString = false
|
|
782
|
+
continue
|
|
783
|
+
}
|
|
784
|
+
if (char === '"') {
|
|
785
|
+
inString = true
|
|
786
|
+
out += char
|
|
787
|
+
continue
|
|
788
|
+
}
|
|
789
|
+
if (char === ',') {
|
|
790
|
+
let next = index + 1
|
|
791
|
+
while (next < text.length && /\s/u.test(text[next])) next += 1
|
|
792
|
+
if (text[next] === ']' || text[next] === '}') continue
|
|
793
|
+
}
|
|
794
|
+
out += char
|
|
795
|
+
}
|
|
796
|
+
return out
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* 单次 JSON.parse(失败时试一次去尾逗号的修复版)。
|
|
801
|
+
* @param {string} candidate - JSON 候选文本。
|
|
802
|
+
* @returns {unknown} 解析结果;失败 undefined。
|
|
803
|
+
*/
|
|
804
|
+
function tryParseJson(candidate) {
|
|
805
|
+
try {
|
|
806
|
+
return JSON.parse(candidate)
|
|
807
|
+
} catch {
|
|
808
|
+
/* 继续尝试修复版 */
|
|
809
|
+
}
|
|
810
|
+
try {
|
|
811
|
+
return JSON.parse(stripTrailingCommas(candidate))
|
|
812
|
+
} catch {
|
|
813
|
+
return undefined
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* 把解析出的 JSON 值拉平成「事实数组」:数组直接用;对象则找 facts/results
|
|
819
|
+
* 之类的包装数组,或把单条事实对象包成数组;都不是返回 null。
|
|
820
|
+
* @param {unknown} parsed - JSON.parse 的结果。
|
|
821
|
+
* @param {number} [depth] - 递归深度。
|
|
822
|
+
* @returns {unknown[] | null} 事实数组或 null。
|
|
823
|
+
*/
|
|
824
|
+
function coerceItems(parsed, depth = 0) {
|
|
825
|
+
if (Array.isArray(parsed)) return parsed
|
|
826
|
+
if (!isRecord(parsed)) return null
|
|
827
|
+
const wrapperKeys = ['facts', 'results', 'items', 'data', 'knowledge', 'factslist']
|
|
828
|
+
for (const key of wrapperKeys) {
|
|
829
|
+
const value = parsed[key]
|
|
830
|
+
if (Array.isArray(value)) return value
|
|
831
|
+
}
|
|
832
|
+
for (const value of Object.values(parsed)) {
|
|
833
|
+
if (Array.isArray(value) && value.length > 0) return value
|
|
834
|
+
}
|
|
835
|
+
if (depth < 3) {
|
|
836
|
+
for (const value of Object.values(parsed)) {
|
|
837
|
+
if (isRecord(value)) {
|
|
838
|
+
const nested = coerceItems(value, depth + 1)
|
|
839
|
+
if (nested !== null) return nested
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
// 单条事实对象包装。
|
|
844
|
+
if (readFieldValue(parsed, STATEMENT_KEYS) !== undefined) return [parsed]
|
|
845
|
+
return null
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* 从可能被截断的文本里抢救完整的 JSON 对象(按括号配平、跳过字符串内部)。
|
|
850
|
+
* @param {string} text - 模型原始输出。
|
|
851
|
+
* @returns {unknown[]} 可解析的对象数组(保持出现顺序)。
|
|
852
|
+
*/
|
|
853
|
+
function salvageCompleteObjects(text) {
|
|
854
|
+
const objects = []
|
|
855
|
+
let depth = 0
|
|
856
|
+
let start = -1
|
|
857
|
+
let inString = false
|
|
858
|
+
let escaped = false
|
|
859
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
860
|
+
const char = text[index]
|
|
861
|
+
if (inString) {
|
|
862
|
+
if (escaped) escaped = false
|
|
863
|
+
else if (char === '\\') escaped = true
|
|
864
|
+
else if (char === '"') inString = false
|
|
865
|
+
continue
|
|
866
|
+
}
|
|
867
|
+
if (char === '"') {
|
|
868
|
+
inString = true
|
|
869
|
+
continue
|
|
870
|
+
}
|
|
871
|
+
if (char === '{') {
|
|
872
|
+
if (depth === 0) start = index
|
|
873
|
+
depth += 1
|
|
874
|
+
continue
|
|
875
|
+
}
|
|
876
|
+
if (char === '}') {
|
|
877
|
+
if (depth === 0) continue
|
|
878
|
+
depth -= 1
|
|
879
|
+
if (depth === 0 && start >= 0) {
|
|
880
|
+
const parsed = tryParseJson(text.slice(start, index + 1))
|
|
881
|
+
if (isRecord(parsed)) objects.push(parsed)
|
|
882
|
+
start = -1
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
return objects
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* 从模型输出里提取事实数组:容忍 ```json 围栏、前后解释文字、对象包装、
|
|
891
|
+
* 单对象、尾逗号,以及被 maxTokens 截断时的完整对象抢救。
|
|
892
|
+
* @param {unknown} text - 模型原始输出。
|
|
893
|
+
* @returns {unknown[] | null} 事实数组或 null(完全解析不出来)。
|
|
894
|
+
*/
|
|
895
|
+
function extractFactItems(text) {
|
|
896
|
+
if (typeof text !== 'string') return null
|
|
897
|
+
const cleaned = text.replace(/^\uFEFF/u, '').trim()
|
|
898
|
+
if (cleaned === '') return null
|
|
899
|
+
|
|
900
|
+
const candidates = [cleaned]
|
|
901
|
+
|
|
902
|
+
// 1) Markdown 代码围栏(```json / ``` 都认)。
|
|
903
|
+
const fencePattern = /```[^\n`]*\n?([\s\S]*?)```/gu
|
|
904
|
+
let match
|
|
905
|
+
while ((match = fencePattern.exec(cleaned)) !== null) {
|
|
906
|
+
const body = match[1].trim()
|
|
907
|
+
if (body !== '') candidates.push(body)
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// 2) 前后带解释文字:截取第一个 '[' 到最后一个 ']',或第一个 '{' 到最后一个 '}'。
|
|
911
|
+
const arrayStart = cleaned.indexOf('[')
|
|
912
|
+
const arrayEnd = cleaned.lastIndexOf(']')
|
|
913
|
+
if (arrayStart >= 0 && arrayEnd > arrayStart) candidates.push(cleaned.slice(arrayStart, arrayEnd + 1))
|
|
914
|
+
const objectStart = cleaned.indexOf('{')
|
|
915
|
+
const objectEnd = cleaned.lastIndexOf('}')
|
|
916
|
+
if (objectStart >= 0 && objectEnd > objectStart) candidates.push(cleaned.slice(objectStart, objectEnd + 1))
|
|
917
|
+
|
|
918
|
+
for (const candidate of candidates) {
|
|
919
|
+
const items = coerceItems(tryParseJson(candidate))
|
|
920
|
+
if (items !== null) return items
|
|
921
|
+
}
|
|
922
|
+
// 3) 被 maxTokens 截断(数组没闭合):抢救已完整生成的事实对象。
|
|
923
|
+
const salvaged = salvageCompleteObjects(cleaned)
|
|
924
|
+
if (salvaged.length > 0) return salvaged
|
|
925
|
+
return null
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* 解析事实抽取响应,返回「有效事实 + 无效条目」。
|
|
930
|
+
*
|
|
931
|
+
* 容错规则:
|
|
932
|
+
* - 裸 JSON 数组、```json 围栏、前后解释文字、{ facts: [...] } 包装、单对象、
|
|
933
|
+
* 尾逗号、被截断时抢救完整对象;字段名大小写/下划线/连字符不敏感;
|
|
934
|
+
* - 非法 kind → 跳过该条(进 invalid);缺 statement 或 sourceCardId → 跳过;
|
|
935
|
+
* - statement 折叠空白并截断到 80 个字符;scopePath 清洗为相对层级路径;
|
|
936
|
+
* entities 去重且最多 8 个;confidence 非法/缺失 → medium;status 缺省 active
|
|
937
|
+
* (合法值 active / superseded / archived);
|
|
938
|
+
* - 同一响应内 id 重复只保留第一条(幂等去重)。
|
|
939
|
+
*
|
|
940
|
+
* v15.1 扩展字段(全部可选、缺失安全降级,不影响既有字段与 id 规则):
|
|
941
|
+
* - 时间/生存:`validFrom`(缺省=抽取时间)、`validUntil?`、`supersededBy?`、
|
|
942
|
+
* `createdAt`、`updatedAt`、`lastUsedAt?`、`hitCount?`(缺省 0);
|
|
943
|
+
* - 顶层 `projectId?`(模型值 > options.projectId > scopePath[0] 回退);
|
|
944
|
+
* - `source` 扩展:`lineageKey?`、`seqs?`、`projectId?`、`sessionId?`。
|
|
945
|
+
*
|
|
946
|
+
* 注意:`source.turn`/`source.at` 在解析阶段先用 null/now,`extractFacts` 会按
|
|
947
|
+
* 输入卡片与批次时间补全。
|
|
948
|
+
*
|
|
949
|
+
* @param {unknown} text - 模型原始输出。
|
|
950
|
+
* @param {{ now?: number, sessionId?: string, projectId?: string }} [options] - 上下文(抽取时间/会话/项目)。
|
|
951
|
+
* @returns {{ facts: object[], invalid: Array<{ index: number, reason: string, statement?: string }> }} 解析结果。
|
|
952
|
+
*/
|
|
953
|
+
export function parseFactExtractionResponse(text, options = {}) {
|
|
954
|
+
const context = isRecord(options) ? options : {}
|
|
955
|
+
const now = Number.isFinite(context.now) ? Math.round(context.now) : Date.now()
|
|
956
|
+
const contextSessionId = normalizeOptionalId(context.sessionId)
|
|
957
|
+
const contextProjectId = normalizeProjectId(context.projectId)
|
|
958
|
+
const facts = []
|
|
959
|
+
const invalid = []
|
|
960
|
+
const seen = new Set()
|
|
961
|
+
const items = extractFactItems(text)
|
|
962
|
+
if (items === null) {
|
|
963
|
+
return { facts, invalid: [{ index: -1, reason: 'unparseable' }] }
|
|
964
|
+
}
|
|
965
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
966
|
+
const item = items[index]
|
|
967
|
+
if (!isRecord(item)) {
|
|
968
|
+
invalid.push({ index, reason: 'not-object' })
|
|
969
|
+
continue
|
|
970
|
+
}
|
|
971
|
+
const statement = normalizeStatement(readFieldValue(item, STATEMENT_KEYS))
|
|
972
|
+
if (statement === '') {
|
|
973
|
+
invalid.push({ index, reason: 'statement-missing' })
|
|
974
|
+
continue
|
|
975
|
+
}
|
|
976
|
+
const kind = normalizeFactKind(readFieldValue(item, KIND_KEYS))
|
|
977
|
+
if (kind === null) {
|
|
978
|
+
invalid.push({ index, reason: 'kind-invalid', statement })
|
|
979
|
+
continue
|
|
980
|
+
}
|
|
981
|
+
const sourceCardId = normalizeSourceCardId(item)
|
|
982
|
+
if (sourceCardId === '') {
|
|
983
|
+
invalid.push({ index, reason: 'source-missing', statement })
|
|
984
|
+
continue
|
|
985
|
+
}
|
|
986
|
+
const scopePath = normalizeScopePath(readFieldValue(item, SCOPE_KEYS))
|
|
987
|
+
const entities = normalizeEntities(readFieldValue(item, ENTITY_KEYS))
|
|
988
|
+
const confidence = normalizeConfidence(readFieldValue(item, CONFIDENCE_KEYS))
|
|
989
|
+
const status = normalizeStatus(readFieldValue(item, STATUS_KEYS))
|
|
990
|
+
const id = factId(statement, scopePath, sourceCardId)
|
|
991
|
+
if (seen.has(id)) continue
|
|
992
|
+
seen.add(id)
|
|
993
|
+
|
|
994
|
+
// ── v15.1 扩展字段(全部可选,缺失时不报错、走安全缺省)───────────────
|
|
995
|
+
const projectId = normalizeProjectId(readFieldValue(item, PROJECT_KEYS))
|
|
996
|
+
|| contextProjectId
|
|
997
|
+
|| (scopePath.length > 0 ? scopePath[0] : '')
|
|
998
|
+
|
|
999
|
+
// 时间/生存字段:模型给值则尽量归一化,否则用抽取时间缺省。
|
|
1000
|
+
const validFrom = normalizeTimestamp(readFieldValue(item, VALID_FROM_KEYS), now)
|
|
1001
|
+
const rawValidUntil = readFieldValue(item, VALID_UNTIL_KEYS)
|
|
1002
|
+
const validUntil = rawValidUntil === undefined || rawValidUntil === null || rawValidUntil === ''
|
|
1003
|
+
? null
|
|
1004
|
+
: normalizeTimestamp(rawValidUntil, null)
|
|
1005
|
+
const rawSupersededBy = readFieldValue(item, SUPERSEDED_BY_KEYS)
|
|
1006
|
+
const supersededBy = typeof rawSupersededBy === 'string'
|
|
1007
|
+
? rawSupersededBy.trim()
|
|
1008
|
+
: (isRecord(rawSupersededBy) && typeof rawSupersededBy.id === 'string' ? rawSupersededBy.id.trim() : '')
|
|
1009
|
+
const createdAt = normalizeTimestamp(readFieldValue(item, CREATED_AT_KEYS), now)
|
|
1010
|
+
const updatedAt = normalizeTimestamp(readFieldValue(item, UPDATED_AT_KEYS), createdAt)
|
|
1011
|
+
const rawLastUsedAt = readFieldValue(item, LAST_USED_AT_KEYS)
|
|
1012
|
+
const lastUsedAt = rawLastUsedAt === undefined || rawLastUsedAt === null || rawLastUsedAt === ''
|
|
1013
|
+
? null
|
|
1014
|
+
: normalizeTimestamp(rawLastUsedAt, null)
|
|
1015
|
+
const hitCount = readNonNegativeInt(readFieldValue(item, HIT_COUNT_KEYS)) ?? 0
|
|
1016
|
+
|
|
1017
|
+
// source 血缘扩展:lineageKey / seqs / projectId / sessionId 均可选。
|
|
1018
|
+
// 注意:不能用 SOURCE_CARD_KEYS 读 source 对象(顶层 sourceCardId 会先命中字符串),
|
|
1019
|
+
// 这里专门取 `source` 字段本身,容忍它被写成对象/字符串。
|
|
1020
|
+
const rawSourceValue = readFieldValue(item, ['source', '来源卡片'])
|
|
1021
|
+
const modelSource = isRecord(rawSourceValue) ? rawSourceValue : {}
|
|
1022
|
+
const lineageKey = normalizeLineageKey(modelSource.lineageKey ?? modelSource.lineage ?? readFieldValue(item, LINEAGE_KEY_KEYS))
|
|
1023
|
+
const sourceSeqs = normalizeSeqList(modelSource.seqs ?? readFieldValue(item, SEQS_KEYS))
|
|
1024
|
+
const sourceProjectId = normalizeProjectId(modelSource.projectId)
|
|
1025
|
+
const sourceSessionId = normalizeOptionalId(modelSource.sessionId ?? readFieldValue(item, SESSION_ID_KEYS))
|
|
1026
|
+
|| contextSessionId
|
|
1027
|
+
|
|
1028
|
+
const source = { cardId: sourceCardId, turn: null, at: now }
|
|
1029
|
+
if (lineageKey !== '') source.lineageKey = lineageKey
|
|
1030
|
+
if (sourceSeqs.length > 0) source.seqs = sourceSeqs
|
|
1031
|
+
if (sourceProjectId !== '') source.projectId = sourceProjectId
|
|
1032
|
+
else if (projectId !== '') source.projectId = projectId
|
|
1033
|
+
if (sourceSessionId !== '') source.sessionId = sourceSessionId
|
|
1034
|
+
|
|
1035
|
+
const fact = {
|
|
1036
|
+
id,
|
|
1037
|
+
statement,
|
|
1038
|
+
kind,
|
|
1039
|
+
scopePath,
|
|
1040
|
+
entities,
|
|
1041
|
+
confidence,
|
|
1042
|
+
source,
|
|
1043
|
+
status,
|
|
1044
|
+
validFrom: validFrom === null ? now : validFrom,
|
|
1045
|
+
createdAt: createdAt === null ? now : createdAt,
|
|
1046
|
+
updatedAt: updatedAt === null ? createdAt : updatedAt,
|
|
1047
|
+
hitCount,
|
|
1048
|
+
}
|
|
1049
|
+
if (projectId !== '') fact.projectId = projectId
|
|
1050
|
+
if (validUntil !== null) fact.validUntil = validUntil
|
|
1051
|
+
if (supersededBy !== '') fact.supersededBy = supersededBy
|
|
1052
|
+
if (lastUsedAt !== null) fact.lastUsedAt = lastUsedAt
|
|
1053
|
+
facts.push(fact)
|
|
1054
|
+
}
|
|
1055
|
+
return { facts, invalid }
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/* -------------------------------------------------------------------------- */
|
|
1059
|
+
/* 模型流读取与取消 */
|
|
1060
|
+
/* -------------------------------------------------------------------------- */
|
|
1061
|
+
|
|
1062
|
+
/**
|
|
1063
|
+
* 构造取消错误:优先原样返回 `signal.reason`(若它像错误对象),否则造 AbortError。
|
|
1064
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1065
|
+
* @returns {Error | DOMException} 可抛出的取消错误。
|
|
1066
|
+
*/
|
|
1067
|
+
function abortErrorFrom(signal) {
|
|
1068
|
+
let reason
|
|
1069
|
+
try {
|
|
1070
|
+
reason = signal !== null && signal !== undefined ? signal.reason : undefined
|
|
1071
|
+
} catch {
|
|
1072
|
+
reason = undefined
|
|
1073
|
+
}
|
|
1074
|
+
if (reason !== undefined && reason !== null
|
|
1075
|
+
&& (reason instanceof Error || (typeof reason === 'object' && typeof reason.name === 'string' && reason.name !== ''))) {
|
|
1076
|
+
return reason
|
|
1077
|
+
}
|
|
1078
|
+
const error = new Error(reason === undefined || reason === null ? '事实抽取已取消' : `事实抽取已取消:${String(reason)}`)
|
|
1079
|
+
error.name = 'AbortError'
|
|
1080
|
+
return error
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/**
|
|
1084
|
+
* 信号已中止时立即抛出取消错误。
|
|
1085
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1086
|
+
*/
|
|
1087
|
+
function throwIfAborted(signal) {
|
|
1088
|
+
if (signal !== null && signal !== undefined && signal.aborted === true) throw abortErrorFrom(signal)
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* 只接受「看起来像 AbortSignal」的对象。
|
|
1093
|
+
* @param {unknown} value - 候选值。
|
|
1094
|
+
* @returns {AbortSignal | null} 合法信号或 null。
|
|
1095
|
+
*/
|
|
1096
|
+
function normalizeAbortSignal(value) {
|
|
1097
|
+
if (value === undefined || value === null || typeof value !== 'object') return null
|
|
1098
|
+
try {
|
|
1099
|
+
if (typeof value.aborted !== 'boolean' || typeof value.addEventListener !== 'function') return null
|
|
1100
|
+
return value
|
|
1101
|
+
} catch {
|
|
1102
|
+
return null
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* 让一个 promise 与 AbortSignal 赛跑:signal 一 abort 就立即 reject。
|
|
1108
|
+
* @template T
|
|
1109
|
+
* @param {Promise<T>} promise - 底层 promise。
|
|
1110
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1111
|
+
* @returns {Promise<T>} 与信号联动后的 promise。
|
|
1112
|
+
*/
|
|
1113
|
+
function raceWithSignal(promise, signal) {
|
|
1114
|
+
if (signal === undefined || signal === null || typeof signal.addEventListener !== 'function') return promise
|
|
1115
|
+
if (signal.aborted) return Promise.reject(abortErrorFrom(signal))
|
|
1116
|
+
return new Promise((resolve, reject) => {
|
|
1117
|
+
const cleanup = () => {
|
|
1118
|
+
try {
|
|
1119
|
+
signal.removeEventListener('abort', onAbort)
|
|
1120
|
+
} catch {
|
|
1121
|
+
/* 忽略 */
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
const onAbort = () => {
|
|
1125
|
+
cleanup()
|
|
1126
|
+
reject(abortErrorFrom(signal))
|
|
1127
|
+
}
|
|
1128
|
+
try {
|
|
1129
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
1130
|
+
} catch {
|
|
1131
|
+
resolve(promise)
|
|
1132
|
+
return
|
|
1133
|
+
}
|
|
1134
|
+
promise.then(
|
|
1135
|
+
value => {
|
|
1136
|
+
cleanup()
|
|
1137
|
+
resolve(value)
|
|
1138
|
+
},
|
|
1139
|
+
error => {
|
|
1140
|
+
cleanup()
|
|
1141
|
+
reject(error)
|
|
1142
|
+
},
|
|
1143
|
+
)
|
|
1144
|
+
})
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
/**
|
|
1148
|
+
* 读取异步迭代器的下一步,并与 signal 赛跑。
|
|
1149
|
+
* @param {AsyncIterator<unknown>} iterator - 异步迭代器。
|
|
1150
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1151
|
+
* @returns {Promise<IteratorResult<unknown>>} 迭代结果。
|
|
1152
|
+
*/
|
|
1153
|
+
function nextWithSignal(iterator, signal) {
|
|
1154
|
+
return raceWithSignal(Promise.resolve().then(() => iterator.next()), signal)
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* 可被 signal 打断的 sleep(用于重试退避)。
|
|
1159
|
+
* @param {number} ms - 等待毫秒数(<=0 直接返回)。
|
|
1160
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1161
|
+
* @returns {Promise<void>} 等待结束。
|
|
1162
|
+
*/
|
|
1163
|
+
function sleepWithSignal(ms, signal) {
|
|
1164
|
+
if (!(typeof ms === 'number' && Number.isFinite(ms) && ms > 0)) return Promise.resolve()
|
|
1165
|
+
return new Promise((resolve, reject) => {
|
|
1166
|
+
let timer
|
|
1167
|
+
const cleanup = () => {
|
|
1168
|
+
clearTimeout(timer)
|
|
1169
|
+
try {
|
|
1170
|
+
if (signal !== null && signal !== undefined && typeof signal.removeEventListener === 'function') {
|
|
1171
|
+
signal.removeEventListener('abort', onAbort)
|
|
1172
|
+
}
|
|
1173
|
+
} catch {
|
|
1174
|
+
/* 忽略 */
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
const onAbort = () => {
|
|
1178
|
+
cleanup()
|
|
1179
|
+
reject(abortErrorFrom(signal))
|
|
1180
|
+
}
|
|
1181
|
+
if (signal !== null && signal !== undefined && typeof signal.addEventListener === 'function') {
|
|
1182
|
+
if (signal.aborted) {
|
|
1183
|
+
reject(abortErrorFrom(signal))
|
|
1184
|
+
return
|
|
1185
|
+
}
|
|
1186
|
+
try {
|
|
1187
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
1188
|
+
} catch {
|
|
1189
|
+
/* 加不上监听则退化为普通 sleep */
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
timer = setTimeout(() => {
|
|
1193
|
+
cleanup()
|
|
1194
|
+
resolve()
|
|
1195
|
+
}, ms)
|
|
1196
|
+
})
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/**
|
|
1200
|
+
* finish reason 的失败原因文本。
|
|
1201
|
+
* @param {unknown} failure - FinishReason.failure。
|
|
1202
|
+
* @returns {string} 可读原因。
|
|
1203
|
+
*/
|
|
1204
|
+
function failureText(failure) {
|
|
1205
|
+
if (typeof failure === 'string' && failure !== '') return failure
|
|
1206
|
+
if (isRecord(failure) && typeof failure.message === 'string' && failure.message !== '') return failure.message
|
|
1207
|
+
return '未知原因'
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
/**
|
|
1211
|
+
* 把 finish reason 翻译成需要抛出的错误;'stop' / 缺失都放行。
|
|
1212
|
+
* @param {unknown} reason - finish reason。
|
|
1213
|
+
* @returns {Error | null} 失败错误或 null。
|
|
1214
|
+
*/
|
|
1215
|
+
function finishFailure(reason) {
|
|
1216
|
+
if (!isRecord(reason) || typeof reason.kind !== 'string') return null
|
|
1217
|
+
switch (reason.kind) {
|
|
1218
|
+
case 'error':
|
|
1219
|
+
return new Error(`模型返回错误:${failureText(reason.failure)}`)
|
|
1220
|
+
case 'aborted':
|
|
1221
|
+
return new Error(`模型调用被中止:${failureText(reason.failure)}`)
|
|
1222
|
+
case 'max-tokens':
|
|
1223
|
+
return new Error('模型输出触达 maxTokens 上限,结果被截断')
|
|
1224
|
+
default:
|
|
1225
|
+
return null
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/**
|
|
1230
|
+
* 调用注入的 `llm.stream(options)` 并把流里的文本拼起来。
|
|
1231
|
+
*
|
|
1232
|
+
* options 按宿主 GenerateOptions 构造(provider/model/messages/maxTokens/
|
|
1233
|
+
* temperature/signal,可选 sessionId);兼容:
|
|
1234
|
+
* - `llm.stream` 同步抛错;返回 Promise<AsyncIterable>;只有 text-delta 没有 finish;
|
|
1235
|
+
* - 只有 block-end 没有 text-delta;
|
|
1236
|
+
* - signal 中止(立即 reject,不依赖适配器配合)。
|
|
1237
|
+
*
|
|
1238
|
+
* @param {{
|
|
1239
|
+
* streamFn: (options: object) => unknown,
|
|
1240
|
+
* target: { provider: string, model: string },
|
|
1241
|
+
* prompt: string,
|
|
1242
|
+
* maxTokens: number,
|
|
1243
|
+
* temperature: number,
|
|
1244
|
+
* signal: AbortSignal,
|
|
1245
|
+
* sessionId?: string,
|
|
1246
|
+
* }} options - 调用参数。
|
|
1247
|
+
* @returns {Promise<string>} 模型输出的完整文本。
|
|
1248
|
+
*/
|
|
1249
|
+
async function collectModelText(options) {
|
|
1250
|
+
const generateOptions = {
|
|
1251
|
+
provider: options.target.provider,
|
|
1252
|
+
model: options.target.model,
|
|
1253
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: options.prompt }] }],
|
|
1254
|
+
maxTokens: options.maxTokens,
|
|
1255
|
+
temperature: options.temperature,
|
|
1256
|
+
signal: options.signal,
|
|
1257
|
+
}
|
|
1258
|
+
if (typeof options.sessionId === 'string' && options.sessionId !== '') {
|
|
1259
|
+
generateOptions.sessionId = options.sessionId
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
let stream
|
|
1263
|
+
try {
|
|
1264
|
+
stream = options.streamFn(generateOptions)
|
|
1265
|
+
} catch (error) {
|
|
1266
|
+
throw error instanceof Error ? error : new Error(toErrorMessage(error))
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
if (stream !== null && typeof stream === 'object' && typeof stream.then === 'function'
|
|
1270
|
+
&& typeof stream[Symbol.asyncIterator] !== 'function') {
|
|
1271
|
+
stream = await raceWithSignal(stream, options.signal)
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
const iterable = stream
|
|
1275
|
+
if (iterable === null || iterable === undefined
|
|
1276
|
+
|| (typeof iterable !== 'object' && typeof iterable !== 'function')
|
|
1277
|
+
|| typeof iterable[Symbol.asyncIterator] !== 'function') {
|
|
1278
|
+
throw new Error('模型调用接口没有返回可迭代的输出流')
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
const iterator = iterable[Symbol.asyncIterator]()
|
|
1282
|
+
const textParts = []
|
|
1283
|
+
const blockTextParts = []
|
|
1284
|
+
let finishReason = null
|
|
1285
|
+
let drained = false
|
|
1286
|
+
|
|
1287
|
+
try {
|
|
1288
|
+
while (true) {
|
|
1289
|
+
const step = await nextWithSignal(iterator, options.signal)
|
|
1290
|
+
if (!isRecord(step)) continue
|
|
1291
|
+
if (step.done === true) {
|
|
1292
|
+
drained = true
|
|
1293
|
+
break
|
|
1294
|
+
}
|
|
1295
|
+
const responseChunk = step.value
|
|
1296
|
+
if (!isRecord(responseChunk)) continue
|
|
1297
|
+
if (responseChunk.type === 'text-delta') {
|
|
1298
|
+
if (typeof responseChunk.text === 'string' && responseChunk.text !== '') textParts.push(responseChunk.text)
|
|
1299
|
+
continue
|
|
1300
|
+
}
|
|
1301
|
+
if (responseChunk.type === 'block-end') {
|
|
1302
|
+
const block = responseChunk.block
|
|
1303
|
+
if (isRecord(block) && block.type === 'text' && typeof block.text === 'string' && block.text !== '') {
|
|
1304
|
+
blockTextParts.push(block.text)
|
|
1305
|
+
}
|
|
1306
|
+
continue
|
|
1307
|
+
}
|
|
1308
|
+
if (responseChunk.type === 'finish') {
|
|
1309
|
+
finishReason = isRecord(responseChunk.reason) ? responseChunk.reason : null
|
|
1310
|
+
break
|
|
1311
|
+
}
|
|
1312
|
+
// 其余 chunk(block-start / reasoning-delta / tool-call-delta / usage)与文本无关。
|
|
1313
|
+
}
|
|
1314
|
+
} finally {
|
|
1315
|
+
if (!drained) {
|
|
1316
|
+
try {
|
|
1317
|
+
const returned = typeof iterator.return === 'function' ? iterator.return() : undefined
|
|
1318
|
+
if (returned !== null && returned !== undefined && typeof returned.then === 'function') {
|
|
1319
|
+
returned.then(() => undefined, () => undefined)
|
|
1320
|
+
}
|
|
1321
|
+
} catch {
|
|
1322
|
+
/* 关闭失败不影响结果 */
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
const failure = finishFailure(finishReason)
|
|
1328
|
+
if (failure !== null) throw failure
|
|
1329
|
+
const direct = textParts.join('')
|
|
1330
|
+
return direct.trim() === '' ? blockTextParts.join('') : direct
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
/* -------------------------------------------------------------------------- */
|
|
1334
|
+
/* 批量抽取 */
|
|
1335
|
+
/* -------------------------------------------------------------------------- */
|
|
1336
|
+
|
|
1337
|
+
/**
|
|
1338
|
+
* 读取模型目标(provider/model 同时存在才算合法)。
|
|
1339
|
+
* @param {unknown} model - { provider, model }。
|
|
1340
|
+
* @returns {{ provider: string, model: string, label: string } | null} 目标或 null。
|
|
1341
|
+
*/
|
|
1342
|
+
function resolveModelTarget(model) {
|
|
1343
|
+
const source = isRecord(model) ? model : {}
|
|
1344
|
+
const provider = typeof source.provider === 'string' ? source.provider.trim() : ''
|
|
1345
|
+
const name = typeof source.model === 'string' ? source.model.trim() : ''
|
|
1346
|
+
if (provider === '' || name === '') return null
|
|
1347
|
+
return { provider, model: name, label: `${provider}/${name}` }
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* 从「看起来像 ctx.llm」的对象里取 stream 调用器(绑定 this)。
|
|
1352
|
+
* @param {unknown} llm - 注入的 llm。
|
|
1353
|
+
* @returns {((options: object) => unknown) | null} stream 调用器或 null。
|
|
1354
|
+
*/
|
|
1355
|
+
function resolveStreamFn(llm) {
|
|
1356
|
+
try {
|
|
1357
|
+
if (!isRecord(llm) || typeof llm.stream !== 'function') return null
|
|
1358
|
+
return options => llm.stream(options)
|
|
1359
|
+
} catch {
|
|
1360
|
+
return null
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
/**
|
|
1365
|
+
* 预处理输入卡片:只保留带合法 id 的对象,按 id 去重并截断到 maxCardsPerPass。
|
|
1366
|
+
* @param {unknown} cards - 原始卡片数组。
|
|
1367
|
+
* @param {number} maxCards - 单次上限。
|
|
1368
|
+
* @returns {Array<{ id: string, raw: Record<string, unknown> }>} 待抽取卡片。
|
|
1369
|
+
*/
|
|
1370
|
+
function prepareCards(cards, maxCards) {
|
|
1371
|
+
if (!Array.isArray(cards)) return []
|
|
1372
|
+
const seen = new Set()
|
|
1373
|
+
const items = []
|
|
1374
|
+
for (const raw of cards) {
|
|
1375
|
+
if (!isRecord(raw)) continue
|
|
1376
|
+
const id = cleanInline(pickString(raw.id, raw.cardId))
|
|
1377
|
+
if (id === '' || seen.has(id)) continue
|
|
1378
|
+
seen.add(id)
|
|
1379
|
+
items.push({ id, raw })
|
|
1380
|
+
if (items.length >= maxCards) break
|
|
1381
|
+
}
|
|
1382
|
+
return items
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
/**
|
|
1386
|
+
* 在一批卡片上执行一次抽取(已解析的文本 → 事实数组)。
|
|
1387
|
+
*
|
|
1388
|
+
* @param {{
|
|
1389
|
+
* batchCards: Record<string, unknown>[],
|
|
1390
|
+
* config: typeof DEFAULT_EXTRACT_CONFIG,
|
|
1391
|
+
* target: { provider: string, model: string, label: string },
|
|
1392
|
+
* streamFn: (options: object) => unknown,
|
|
1393
|
+
* sessionId: string,
|
|
1394
|
+
* projectId: string,
|
|
1395
|
+
* cardsById: Map<string, Record<string, unknown>>,
|
|
1396
|
+
* callerSignal: AbortSignal | null,
|
|
1397
|
+
* batchNumber: number,
|
|
1398
|
+
* activeControllers: Set<AbortController>,
|
|
1399
|
+
* }} options - 批次执行参数。
|
|
1400
|
+
* @returns {Promise<object[]>} 该批抽到的事实(失败时由调用方兜底为 [])。
|
|
1401
|
+
*/
|
|
1402
|
+
async function runExtractionAttempt(options) {
|
|
1403
|
+
const {
|
|
1404
|
+
batchCards, config, target, streamFn, sessionId, projectId, cardsById, callerSignal, batchNumber, activeControllers,
|
|
1405
|
+
} = options
|
|
1406
|
+
|
|
1407
|
+
const controller = new AbortController()
|
|
1408
|
+
activeControllers.add(controller)
|
|
1409
|
+
let timedOut = false
|
|
1410
|
+
const handleCallerAbort = () => {
|
|
1411
|
+
try {
|
|
1412
|
+
controller.abort(callerSignal === null ? undefined : callerSignal.reason)
|
|
1413
|
+
} catch {
|
|
1414
|
+
try {
|
|
1415
|
+
controller.abort()
|
|
1416
|
+
} catch {
|
|
1417
|
+
/* 已经中止过 */
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
if (callerSignal !== null) callerSignal.addEventListener('abort', handleCallerAbort, { once: true })
|
|
1422
|
+
const timer = setTimeout(() => {
|
|
1423
|
+
timedOut = true
|
|
1424
|
+
const error = new Error(`事实抽取请求超时(超过 ${config.timeoutMs}ms,批次 ${batchNumber})`)
|
|
1425
|
+
error.name = 'TimeoutError'
|
|
1426
|
+
try {
|
|
1427
|
+
controller.abort(error)
|
|
1428
|
+
} catch {
|
|
1429
|
+
/* 已经中止过 */
|
|
1430
|
+
}
|
|
1431
|
+
}, config.timeoutMs)
|
|
1432
|
+
|
|
1433
|
+
try {
|
|
1434
|
+
const prompt = buildFactExtractionPrompt(batchCards, config)
|
|
1435
|
+
const text = await collectModelText({
|
|
1436
|
+
streamFn,
|
|
1437
|
+
target,
|
|
1438
|
+
prompt,
|
|
1439
|
+
maxTokens: config.maxTokens,
|
|
1440
|
+
temperature: config.temperature,
|
|
1441
|
+
signal: controller.signal,
|
|
1442
|
+
sessionId,
|
|
1443
|
+
})
|
|
1444
|
+
const at = Date.now()
|
|
1445
|
+
const parsed = parseFactExtractionResponse(text, { now: at, sessionId, projectId })
|
|
1446
|
+
// 完全无法解析成 JSON → 视为该批失败(触发重试)。
|
|
1447
|
+
if (parsed.invalid.some(entry => entry.reason === 'unparseable')) {
|
|
1448
|
+
throw new Error('模型输出无法解析为 JSON 数组')
|
|
1449
|
+
}
|
|
1450
|
+
const facts = []
|
|
1451
|
+
for (const fact of parsed.facts) {
|
|
1452
|
+
const card = cardsById.get(fact.source.cardId)
|
|
1453
|
+
// 补全 source:turn 来自输入卡片;血缘/序号/项目/会话用卡片与调用上下文回退。
|
|
1454
|
+
const source = {
|
|
1455
|
+
cardId: fact.source.cardId,
|
|
1456
|
+
turn: card === undefined ? null : readNonNegativeInt(card.turn ?? card.turnIndex),
|
|
1457
|
+
at,
|
|
1458
|
+
}
|
|
1459
|
+
if (typeof fact.source.lineageKey === 'string' && fact.source.lineageKey !== '') source.lineageKey = fact.source.lineageKey
|
|
1460
|
+
if (Array.isArray(fact.source.seqs) && fact.source.seqs.length > 0) source.seqs = fact.source.seqs
|
|
1461
|
+
if (typeof fact.source.projectId === 'string' && fact.source.projectId !== '') source.projectId = fact.source.projectId
|
|
1462
|
+
if (typeof fact.source.sessionId === 'string' && fact.source.sessionId !== '') source.sessionId = fact.source.sessionId
|
|
1463
|
+
if (card !== undefined) {
|
|
1464
|
+
if (source.lineageKey === undefined) {
|
|
1465
|
+
const lineageKey = deriveLineageKey(card)
|
|
1466
|
+
if (lineageKey !== '') source.lineageKey = lineageKey
|
|
1467
|
+
}
|
|
1468
|
+
if (source.seqs === undefined) {
|
|
1469
|
+
const seqs = deriveSeqs(card)
|
|
1470
|
+
if (seqs.length > 0) source.seqs = seqs
|
|
1471
|
+
}
|
|
1472
|
+
if (source.projectId === undefined) {
|
|
1473
|
+
const cardProjectId = readCardProjectId(card)
|
|
1474
|
+
if (cardProjectId !== '') source.projectId = cardProjectId
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
if (source.sessionId === undefined && sessionId !== '') source.sessionId = sessionId
|
|
1478
|
+
const next = { ...fact, source }
|
|
1479
|
+
if ((typeof next.projectId !== 'string' || next.projectId === '') && typeof source.projectId === 'string') {
|
|
1480
|
+
next.projectId = source.projectId
|
|
1481
|
+
}
|
|
1482
|
+
facts.push(next)
|
|
1483
|
+
}
|
|
1484
|
+
return facts
|
|
1485
|
+
} catch (error) {
|
|
1486
|
+
if (timedOut) {
|
|
1487
|
+
const timeoutError = new Error(`事实抽取请求超时(超过 ${config.timeoutMs}ms)`)
|
|
1488
|
+
timeoutError.name = 'TimeoutError'
|
|
1489
|
+
throw timeoutError
|
|
1490
|
+
}
|
|
1491
|
+
throw error
|
|
1492
|
+
} finally {
|
|
1493
|
+
clearTimeout(timer)
|
|
1494
|
+
activeControllers.delete(controller)
|
|
1495
|
+
if (callerSignal !== null) {
|
|
1496
|
+
try {
|
|
1497
|
+
callerSignal.removeEventListener('abort', handleCallerAbort)
|
|
1498
|
+
} catch {
|
|
1499
|
+
/* 忽略 */
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/**
|
|
1506
|
+
* 事实抽取主入口:把阶段卡分批交给注入的 `llm.stream`,抽取项目级持久事实。
|
|
1507
|
+
*
|
|
1508
|
+
* 行为契约:
|
|
1509
|
+
* - 卡片按 `batchSize` 分批,`maxConcurrentBatches` 控制并发(默认 1);
|
|
1510
|
+
* - 每批单独超时;失败(模型 error/aborted/max-tokens、超时、坏 JSON、流抛错)
|
|
1511
|
+
* 按 `retries` 重试(指数退避 `retryDelayMs * 2^(attempt-1)`);
|
|
1512
|
+
* 调用方 abort 不重试、整次抽取抛出取消错误;
|
|
1513
|
+
* - 重试耗尽 → 该批返回 [](降级),记 `lastError`,**绝不 reject**;
|
|
1514
|
+
* - 解析出的每条事实用输入卡片补全 `source.turn`,`source.at` 为抽取时间;
|
|
1515
|
+
* - 事实 id 由 `statement+scopePath+sourceCardId` 稳定哈希,跨批次/多次抽取去重;
|
|
1516
|
+
* - 统计:`requested` 输入卡片数、`extracted` 抽出事实数、`failed` 失败批数、
|
|
1517
|
+
* `batches` 总批数。
|
|
1518
|
+
*
|
|
1519
|
+
* @param {{
|
|
1520
|
+
* cards?: unknown,
|
|
1521
|
+
* llm?: unknown,
|
|
1522
|
+
* model?: unknown,
|
|
1523
|
+
* sessionId?: string,
|
|
1524
|
+
* projectId?: string,
|
|
1525
|
+
* config?: unknown,
|
|
1526
|
+
* signal?: AbortSignal,
|
|
1527
|
+
* }} [options] - 抽取参数(全部可缺省;缺省时返回空结果而不是抛错)。
|
|
1528
|
+
* `projectId`/`sessionId` 会写入事实(顶层与 source),便于图谱按项目/会话索引。
|
|
1529
|
+
* @returns {Promise<{
|
|
1530
|
+
* facts: object[],
|
|
1531
|
+
* stats: { requested: number, extracted: number, failed: number, batches: number },
|
|
1532
|
+
* lastError: { batch: number, message: string } | null,
|
|
1533
|
+
* }>} 抽取结果。
|
|
1534
|
+
* @throws {Error|DOMException} 仅当调用方 signal 被 abort 时抛出取消错误。
|
|
1535
|
+
*/
|
|
1536
|
+
export async function extractFacts(options = {}) {
|
|
1537
|
+
const params = isRecord(options) ? options : {}
|
|
1538
|
+
const config = resolveExtractConfig(params.config)
|
|
1539
|
+
const callerSignal = normalizeAbortSignal(params.signal)
|
|
1540
|
+
|
|
1541
|
+
const prepared = prepareCards(params.cards, config.maxCardsPerPass)
|
|
1542
|
+
const stats = { requested: prepared.length, extracted: 0, failed: 0, batches: 0 }
|
|
1543
|
+
/** @type {{ batch: number, message: string } | null} */
|
|
1544
|
+
let lastError = null
|
|
1545
|
+
/** @type {Map<string, object>} */
|
|
1546
|
+
const factsById = new Map()
|
|
1547
|
+
|
|
1548
|
+
/** 记录批次错误:并发下以批次号更大的为准,保证结果确定。 */
|
|
1549
|
+
const recordError = (batchNumber, message) => {
|
|
1550
|
+
if (lastError === null || batchNumber >= lastError.batch) {
|
|
1551
|
+
lastError = { batch: batchNumber, message: message === '' ? '事实抽取失败' : message }
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
try {
|
|
1556
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
1557
|
+
|
|
1558
|
+
const cards = prepared.map(item => item.raw)
|
|
1559
|
+
const batches = chunk(cards, config.batchSize)
|
|
1560
|
+
stats.batches = batches.length
|
|
1561
|
+
if (batches.length === 0) return { facts: [], stats, lastError: null }
|
|
1562
|
+
|
|
1563
|
+
const target = resolveModelTarget(params.model)
|
|
1564
|
+
const streamFn = resolveStreamFn(params.llm)
|
|
1565
|
+
if (target === null || streamFn === null) {
|
|
1566
|
+
stats.failed = batches.length
|
|
1567
|
+
const message = target === null ? '没有可用的抽取模型(缺少 provider/model)' : '模型调用接口不可用(缺少 llm.stream)'
|
|
1568
|
+
recordError(1, message)
|
|
1569
|
+
return { facts: [], stats, lastError }
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
const sessionId = typeof params.sessionId === 'string' ? params.sessionId : ''
|
|
1573
|
+
const contextProjectId = normalizeProjectId(params.projectId)
|
|
1574
|
+
const cardsById = new Map(prepared.map(item => [item.id, item.raw]))
|
|
1575
|
+
const activeControllers = new Set()
|
|
1576
|
+
const total = batches.length
|
|
1577
|
+
let cursor = 0
|
|
1578
|
+
|
|
1579
|
+
/** 执行一批(含重试)。除调用方 abort 外不向外抛错。 */
|
|
1580
|
+
const runBatch = async (batchNumber) => {
|
|
1581
|
+
const batchCards = batches[batchNumber - 1]
|
|
1582
|
+
throwIfAborted(callerSignal)
|
|
1583
|
+
const totalAttempts = config.retries + 1
|
|
1584
|
+
for (let attempt = 1; attempt <= totalAttempts; attempt += 1) {
|
|
1585
|
+
throwIfAborted(callerSignal)
|
|
1586
|
+
try {
|
|
1587
|
+
const facts = await runExtractionAttempt({
|
|
1588
|
+
batchCards,
|
|
1589
|
+
config,
|
|
1590
|
+
target,
|
|
1591
|
+
streamFn,
|
|
1592
|
+
sessionId,
|
|
1593
|
+
projectId: contextProjectId,
|
|
1594
|
+
cardsById,
|
|
1595
|
+
callerSignal,
|
|
1596
|
+
batchNumber,
|
|
1597
|
+
activeControllers,
|
|
1598
|
+
})
|
|
1599
|
+
for (const fact of facts) {
|
|
1600
|
+
if (factsById.has(fact.id)) continue
|
|
1601
|
+
factsById.set(fact.id, fact)
|
|
1602
|
+
stats.extracted += 1
|
|
1603
|
+
}
|
|
1604
|
+
return
|
|
1605
|
+
} catch (error) {
|
|
1606
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
1607
|
+
if (attempt < totalAttempts) {
|
|
1608
|
+
await sleepWithSignal(config.retryDelayMs * 2 ** (attempt - 1), callerSignal)
|
|
1609
|
+
throwIfAborted(callerSignal)
|
|
1610
|
+
continue
|
|
1611
|
+
}
|
|
1612
|
+
// 重试耗尽:该批降级为 [],不拖垮整次抽取。
|
|
1613
|
+
stats.failed += 1
|
|
1614
|
+
recordError(
|
|
1615
|
+
batchNumber,
|
|
1616
|
+
config.retries > 0
|
|
1617
|
+
? `${toErrorMessage(error)}(已尝试 ${attempt} 次仍失败)`
|
|
1618
|
+
: toErrorMessage(error),
|
|
1619
|
+
)
|
|
1620
|
+
return
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
const worker = async () => {
|
|
1626
|
+
while (true) {
|
|
1627
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
1628
|
+
const index = cursor
|
|
1629
|
+
cursor += 1
|
|
1630
|
+
if (index >= total) return
|
|
1631
|
+
await runBatch(index + 1)
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
const workerCount = Math.max(1, Math.min(config.maxConcurrentBatches, total))
|
|
1635
|
+
const workers = []
|
|
1636
|
+
for (let index = 0; index < workerCount; index += 1) workers.push(worker())
|
|
1637
|
+
await Promise.all(workers)
|
|
1638
|
+
|
|
1639
|
+
throwIfAborted(callerSignal)
|
|
1640
|
+
return { facts: [...factsById.values()], stats, lastError }
|
|
1641
|
+
} catch (error) {
|
|
1642
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
1643
|
+
// 最后兜底:任何意外异常都不让整次抽取 reject。
|
|
1644
|
+
recordError(stats.batches === 0 ? 0 : 1, toErrorMessage(error))
|
|
1645
|
+
return { facts: [...factsById.values()], stats, lastError }
|
|
1646
|
+
}
|
|
1647
|
+
}
|