@p-dsh-market/conversation-knowledge-map 0.1.15 → 0.1.16

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/README.md CHANGED
@@ -11,7 +11,7 @@ DSH 的“知识视图”插件,把同一工作路径下用户明确选择的
11
11
 
12
12
  配置面板会列出运行时可用的 Provider / Model,并默认带入 DSH 默认模型;本次选择会绑定到确认令牌、Agent 调用和 `manifest.json`,不会因为默认模型变化而被静默替换。提交任务后配置对话框立即关闭,失败原因会显示在知识视图页的任务条中。
13
13
 
14
- 摘要阶段按对话并行处理,并发上限固定为 3;每个对话按约 5000 字、优先在完整段落边界分段,只有单段本身超长时才按句末或硬边界拆分。同一对话的分段保持顺序处理。思维导图使用合并后的会话摘要;知识图谱直接使用保留来源的分段摘要,避免长对话在二次压缩后丢失实体。知识图谱根据已读取文本量和有效分段数动态计算上限,范围为 30–100 个实体、最多 200 条关系,并要求逐分段检查覆盖范围。结构化输出失败时会完全重置并最多重试 3 次;单个对话连续失败后只跳过该对话,不阻断其他对话和最终报告。“同时生成”模式下,一个最终视图失败也不会阻断另一个视图保存。进度区域和最终知识视图都会按时间线显示读取、摘要、具体失败原因、重试、跳过、合并、生成及保存过程;知识图谱时间线还会显示模型返回数量和来源校验后的保留数量。模型可以保留 thinking,但结果提取只读取最终文本并过滤 reasoning 内容;摘要和最终视图分别预留 12000 与 24000 个输出 Token。最终模型若返回未选择的 Session 引用,会过滤该引用;严格模式下无有效来源的内容项会被跳过,最终页面列出实际总结的对话、失败对话和过滤数量。
14
+ 摘要阶段按对话并行处理,并发上限固定为 3;每个对话按约 5000 字、优先在完整段落边界分段,只有单段本身超长时才按句末或硬边界拆分。同一对话的分段保持顺序处理。思维导图使用合并后的会话摘要;知识图谱直接使用保留来源的分段摘要,避免长对话在二次压缩后丢失实体。知识图谱按证据分段多次生成,最多 2 批并行;单批限制在 10–18 个实体、最多 24 条关系,若达到输出 Token 上限则只降低并重试当前批次。所有成功批次由 Host 按实体类型与名称、关系起点/终点/类型确定性去重并合并来源,最终结果再根据已读取文本量和有效分段数裁剪为 30–100 个实体、最多 200 条关系。单个批次连续失败只跳过该批,不会推翻其他成功批次。结构化输出失败时会完全重置并最多重试 3 次;单个对话摘要连续失败后只跳过该对话,不阻断其他对话和最终报告。“同时生成”模式下,一个最终视图失败也不会阻断另一个视图保存。进度区域和最终知识视图都会按时间线显示读取、摘要、具体失败原因、重试、跳过、合并、生成及保存过程;知识图谱时间线还会显示批次数、模型返回数量和合并去重后的保留数量。模型可以保留 thinking,但结果提取只读取最终文本并过滤 reasoning 内容;摘要和每次图谱调用分别预留 12000 与 24000 个输出 Token。最终模型若返回未选择的 Session 引用,会过滤该引用;严格模式下无有效来源的内容项会被跳过,最终页面列出实际总结的对话、失败对话和过滤数量。
15
15
 
16
16
  生成过程时间线支持折叠和展开:进行中的任务默认展开,已完成结果中的历史时间线默认折叠。思维导图使用递归树形布局并绘制父子连接线。知识图谱按关联度使用中心节点与内外双环布局,节点卡片内显示类型和最多两行名称,关系以带方向箭头的弱化曲线呈现,并通过描边区分推测或冲突内容;画布提供 50%–200% 缩放和一键恢复 100%,缩放不会影响实体筛选、点击和详情查看,也不会产生横向滚动条。
17
17
 
@@ -10,6 +10,9 @@ const SUMMARY_MAX_TOKENS = 12000
10
10
  const VIEW_MAX_TOKENS = 24000
11
11
  const SUMMARY_CONCURRENCY = 3
12
12
  const MAX_MODEL_RETRIES = 3
13
+ const GRAPH_CONCURRENCY = 2
14
+ const GRAPH_BATCH_MAX_ENTITIES = 18
15
+ const GRAPH_BATCH_MAX_RELATIONS = 24
13
16
  const MIN_GRAPH_ENTITIES = 30
14
17
  const MAX_GRAPH_ENTITIES = 100
15
18
  const MAX_GRAPH_RELATIONS = 200
@@ -205,6 +208,104 @@ function graphGenerationBudget(sources, context) {
205
208
  }
206
209
  }
207
210
 
211
+ function graphBatchBudget(context, attempt = 0) {
212
+ const contextChars = JSON.stringify(context || []).length
213
+ const reduction = Math.max(0.5, 1 - attempt * 0.2)
214
+ const entities = Math.max(8, Math.floor(Math.min(GRAPH_BATCH_MAX_ENTITIES, Math.max(10, Math.ceil(contextChars / 500))) * reduction))
215
+ return {
216
+ entities,
217
+ relations: Math.max(entities, Math.floor(Math.min(GRAPH_BATCH_MAX_RELATIONS, Math.ceil(entities * 1.35)) * reduction))
218
+ }
219
+ }
220
+
221
+ function mergeRefs(...groups) {
222
+ const bySession = new Map()
223
+ for (const ref of groups.flat()) {
224
+ const sessionId = String(ref?.sessionId || '')
225
+ if (!sessionId) continue
226
+ const seqs = bySession.get(sessionId) || new Set()
227
+ for (const seq of ref?.eventSeqs || []) if (Number.isInteger(seq) && seq >= 0) seqs.add(seq)
228
+ bySession.set(sessionId, seqs)
229
+ }
230
+ return [...bySession.entries()].slice(0, 12).map(([sessionId, seqs]) => ({ sessionId, eventSeqs: [...seqs].slice(0, 48) }))
231
+ }
232
+
233
+ function mergedConfidence(left, right) {
234
+ const values = new Set([left, right])
235
+ if (values.has('conflicted')) return 'conflicted'
236
+ if (values.has('inferred')) return 'inferred'
237
+ return 'confirmed'
238
+ }
239
+
240
+ function entityMergeKey(entity) {
241
+ const normalize = (value) => String(value || '').normalize('NFKC').trim().toLowerCase().replace(/\s+/g, ' ')
242
+ return `${normalize(entity?.type || 'concept')}\u0000${normalize(entity?.name)}`
243
+ }
244
+
245
+ function mergeKnowledgeGraphs(graphs, budget) {
246
+ const entitiesByKey = new Map()
247
+ const idMaps = []
248
+ let nextEntityId = 1
249
+ const usedEntityIds = new Set()
250
+ graphs.forEach((graph, graphIndex) => {
251
+ const idMap = new Map()
252
+ for (const entity of graph.entities || []) {
253
+ const key = entityMergeKey(entity)
254
+ let merged = entitiesByKey.get(key)
255
+ if (!merged) {
256
+ const requestedId = String(entity.id || '').trim()
257
+ let id = requestedId && !usedEntityIds.has(requestedId) ? requestedId : `entity-${nextEntityId++}`
258
+ while (usedEntityIds.has(id)) id = `entity-${nextEntityId++}`
259
+ usedEntityIds.add(id)
260
+ merged = { ...entity, id, sourceRefs: mergeRefs(entity.sourceRefs), order: entitiesByKey.size }
261
+ entitiesByKey.set(key, merged)
262
+ } else {
263
+ merged.sourceRefs = mergeRefs(merged.sourceRefs, entity.sourceRefs)
264
+ merged.confidence = mergedConfidence(merged.confidence, entity.confidence)
265
+ if (String(entity.summary || '').length > String(merged.summary || '').length) merged.summary = entity.summary
266
+ }
267
+ idMap.set(String(entity.id), merged.id)
268
+ }
269
+ idMaps[graphIndex] = idMap
270
+ })
271
+
272
+ const relationsByKey = new Map()
273
+ graphs.forEach((graph, graphIndex) => {
274
+ const idMap = idMaps[graphIndex]
275
+ for (const relation of graph.relations || []) {
276
+ const from = idMap.get(String(relation.from))
277
+ const to = idMap.get(String(relation.to))
278
+ if (!from || !to || from === to) continue
279
+ const type = String(relation.type || 'related_to').trim()
280
+ const key = `${from}\u0000${to}\u0000${type.toLowerCase()}`
281
+ const existing = relationsByKey.get(key)
282
+ if (existing) {
283
+ existing.evidence = mergeRefs(existing.evidence, relation.evidence)
284
+ existing.confidence = mergedConfidence(existing.confidence, relation.confidence)
285
+ } else {
286
+ relationsByKey.set(key, { ...relation, from, to, type, evidence: mergeRefs(relation.evidence), order: relationsByKey.size })
287
+ }
288
+ }
289
+ })
290
+
291
+ const degree = new Map()
292
+ for (const relation of relationsByKey.values()) {
293
+ degree.set(relation.from, (degree.get(relation.from) || 0) + 1)
294
+ degree.set(relation.to, (degree.get(relation.to) || 0) + 1)
295
+ }
296
+ const entities = [...entitiesByKey.values()]
297
+ .sort((left, right) => (degree.get(right.id) || 0) - (degree.get(left.id) || 0) || right.sourceRefs.length - left.sourceRefs.length || left.order - right.order)
298
+ .slice(0, budget.entities)
299
+ .map(({ order, ...entity }) => entity)
300
+ const retainedIds = new Set(entities.map((entity) => entity.id))
301
+ const relations = [...relationsByKey.values()]
302
+ .filter((relation) => retainedIds.has(relation.from) && retainedIds.has(relation.to))
303
+ .sort((left, right) => right.evidence.length - left.evidence.length || left.order - right.order)
304
+ .slice(0, budget.relations)
305
+ .map(({ order, ...relation }, index) => ({ ...relation, id: `relation-${index + 1}` }))
306
+ return { entities, relations }
307
+ }
308
+
208
309
  async function mapWithConcurrency(items, limit, mapper) {
209
310
  const results = new Array(items.length)
210
311
  let nextIndex = 0
@@ -771,40 +872,53 @@ export class KnowledgeGenerationOrchestrator {
771
872
  }
772
873
  }
773
874
  if (request.outputMode === 'knowledge-graph' || request.outputMode === 'both') {
774
- this.recordTimeline(task, 'view-start', '开始生成知识图谱。')
775
- this.update(task, 'building-knowledge-graph', { progress: { percent: 86, current: sources.length, total: sources.length, label: '生成知识图谱' } })
776
- const baseGraphPrompt = outputPrompt('knowledge-graph', graphContext, request.prompt, request.strict === true, { graphBudget })
777
- let graphError = null
778
- for (let attempt = 0; attempt <= MAX_MODEL_RETRIES; attempt += 1) {
779
- try {
780
- const prompt = attempt === 0 ? baseGraphPrompt : `${baseGraphPrompt}\n\n第 ${attempt} 次输出未通过校验:${shortText(errorMessage(graphError), 500)}。请完全重置并从头生成,修正结构或来源错误,同时保持对各分段的完整覆盖;只有确实超过本次上限时才精简。只输出完整、严格合法的 JSON。`
781
- const value = await this.runModel({
782
- kind: 'knowledge-graph', prompt, cwd: request.cwd, strict: request.strict === true,
783
- selectedSessionIds: sourceSessionIds, model: request.model, signal: task.controller.signal
784
- })
785
- const sanitized = sanitizeKnowledgeGraphSources(value, summarizedSources, request.strict === true)
786
- knowledgeGraph = validateKnowledgeGraph(sanitized.value, { selectedSessionIds: sourceSessionIds, strict: request.strict === true })
787
- this.recordTimeline(task, 'graph-coverage', `知识图谱模型返回 ${Array.isArray(value?.entities) ? value.entities.length : 0} 个实体、${Array.isArray(value?.relations) ? value.relations.length : 0} 条关系;来源校验后保留 ${knowledgeGraph.entities.length} 个实体、${knowledgeGraph.relations.length} 条关系。`, { entityLimit: graphBudget.entities, relationLimit: graphBudget.relations })
788
- sourceWarnings.skippedRefs += sanitized.skippedRefs
789
- sourceWarnings.skippedItems += sanitized.skippedItems
790
- graphError = null
791
- this.recordTimeline(task, 'view-complete', '知识图谱生成完成。')
792
- break
793
- } catch (error) {
794
- this.assertNotCancelled(task)
795
- graphError = error
796
- logMessage(this.logger, 'warn', 'knowledge graph attempt invalid id=%s attempt=%d error=%s', logId(task.id), attempt + 1, errorMessage(error))
797
- if (attempt < MAX_MODEL_RETRIES) {
798
- this.recordTimeline(task, 'retry', `知识图谱生成失败(${shortText(errorMessage(graphError), 160)}),重置重试 ${attempt + 1}/${MAX_MODEL_RETRIES}。`)
799
- this.update(task, 'building-knowledge-graph', {
800
- message: `知识图谱结构无效,正在重置重试 ${attempt + 1}/${MAX_MODEL_RETRIES}…`,
801
- progress: { percent: 88, current: sources.length, total: sources.length, label: `知识图谱重试 ${attempt + 1}/${MAX_MODEL_RETRIES}` }
875
+ const graphBatches = graphContext.map((item) => [item])
876
+ this.recordTimeline(task, 'view-start', `开始分 ${graphBatches.length} 批生成知识图谱(最多 ${GRAPH_CONCURRENCY} 批并行)。`)
877
+ this.update(task, 'building-knowledge-graph', { progress: { percent: 86, current: 0, total: graphBatches.length, label: '分批生成知识图谱' } })
878
+ let completedGraphBatches = 0
879
+ const graphBatchResults = await mapWithConcurrency(graphBatches, GRAPH_CONCURRENCY, async (batch, batchIndex) => {
880
+ let graphError = null
881
+ for (let attempt = 0; attempt <= MAX_MODEL_RETRIES; attempt += 1) {
882
+ try {
883
+ const batchBudget = graphBatchBudget(batch, attempt)
884
+ const baseGraphPrompt = outputPrompt('knowledge-graph', batch, request.prompt, request.strict === true, { graphBudget: batchBudget })
885
+ const prompt = attempt === 0 ? baseGraphPrompt : `${baseGraphPrompt}\n\n本批第 ${attempt} 次输出未通过校验:${shortText(errorMessage(graphError), 500)}。请完全重置并从头生成;本次预算已降低,优先保留有明确关系和来源的实体。只输出完整、严格合法的 JSON。`
886
+ const value = await this.runModel({
887
+ kind: 'knowledge-graph', prompt, cwd: request.cwd, strict: request.strict === true,
888
+ selectedSessionIds: sourceSessionIds, model: request.model, signal: task.controller.signal
802
889
  })
890
+ const sanitized = sanitizeKnowledgeGraphSources(value, summarizedSources, request.strict === true)
891
+ const graph = validateKnowledgeGraph(sanitized.value, { selectedSessionIds: sourceSessionIds, strict: request.strict === true })
892
+ sourceWarnings.skippedRefs += sanitized.skippedRefs
893
+ sourceWarnings.skippedItems += sanitized.skippedItems
894
+ completedGraphBatches += 1
895
+ this.recordTimeline(task, 'graph-batch-complete', `知识图谱第 ${batchIndex + 1}/${graphBatches.length} 批完成:保留 ${graph.entities.length} 个实体、${graph.relations.length} 条关系。`, { batch: batchIndex + 1, totalBatches: graphBatches.length })
896
+ this.update(task, 'building-knowledge-graph', { progress: { percent: 86 + Math.floor(4 * completedGraphBatches / graphBatches.length), current: completedGraphBatches, total: graphBatches.length, label: `知识图谱批次 ${completedGraphBatches}/${graphBatches.length}` } })
897
+ return { graph, rawEntities: Array.isArray(value?.entities) ? value.entities.length : 0, rawRelations: Array.isArray(value?.relations) ? value.relations.length : 0, error: null }
898
+ } catch (error) {
899
+ this.assertNotCancelled(task)
900
+ graphError = error
901
+ logMessage(this.logger, 'warn', 'knowledge graph batch invalid id=%s batch=%d attempt=%d error=%s', logId(task.id), batchIndex + 1, attempt + 1, errorMessage(error))
902
+ if (attempt < MAX_MODEL_RETRIES) {
903
+ this.recordTimeline(task, 'retry', `知识图谱第 ${batchIndex + 1}/${graphBatches.length} 批失败(${shortText(errorMessage(graphError), 160)}),降低本批输出预算后重试 ${attempt + 1}/${MAX_MODEL_RETRIES}。`)
904
+ }
803
905
  }
804
906
  }
805
- }
806
- if (graphError) {
807
- this.recordTimeline(task, 'view-failed', `知识图谱连续重试 ${MAX_MODEL_RETRIES} 次后仍失败,已跳过该视图。`)
907
+ completedGraphBatches += 1
908
+ this.recordTimeline(task, 'graph-batch-skipped', `知识图谱第 ${batchIndex + 1}/${graphBatches.length} 批连续失败,已跳过本批。`)
909
+ return { graph: null, rawEntities: 0, rawRelations: 0, error: graphError }
910
+ })
911
+ const successfulGraphBatches = graphBatchResults.filter((result) => result.graph)
912
+ if (successfulGraphBatches.length) {
913
+ const mergedGraph = mergeKnowledgeGraphs(successfulGraphBatches.map((result) => result.graph), graphBudget)
914
+ knowledgeGraph = validateKnowledgeGraph(mergedGraph, { selectedSessionIds: sourceSessionIds, strict: request.strict === true })
915
+ const rawEntities = successfulGraphBatches.reduce((total, result) => total + result.rawEntities, 0)
916
+ const rawRelations = successfulGraphBatches.reduce((total, result) => total + result.rawRelations, 0)
917
+ this.recordTimeline(task, 'graph-coverage', `知识图谱 ${successfulGraphBatches.length}/${graphBatches.length} 批成功,模型共返回 ${rawEntities} 个实体、${rawRelations} 条关系;合并去重后保留 ${knowledgeGraph.entities.length} 个实体、${knowledgeGraph.relations.length} 条关系。`, { entityLimit: graphBudget.entities, relationLimit: graphBudget.relations })
918
+ this.recordTimeline(task, 'view-complete', '知识图谱分批生成与合并完成。')
919
+ } else {
920
+ const graphError = graphBatchResults.find((result) => result.error)?.error || new Error('所有知识图谱批次均生成失败。')
921
+ this.recordTimeline(task, 'view-failed', `知识图谱 ${graphBatches.length} 个批次均失败,已跳过该视图。`)
808
922
  if (request.outputMode === 'knowledge-graph') throw graphError
809
923
  }
810
924
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@p-dsh-market/conversation-knowledge-map",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
4
4
  "description": "DSH 多对话思维导图与静态知识图谱",
5
5
  "keywords": [
6
6
  "dsh",