dsh-data-domain-knowledge 0.1.1-alpha.3 → 0.1.1-alpha.4

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 (116) hide show
  1. package/README.md +11 -1
  2. package/lib/client.js +736 -1546
  3. package/lib/doc-page.js +7 -7
  4. package/lib/pages.js +3042 -1396
  5. package/lib/types/agent-behavior-rules.d.ts.map +1 -1
  6. package/lib/types/agent-behavior-rules.js +2 -0
  7. package/lib/types/agent-behavior-rules.js.map +1 -1
  8. package/lib/types/convert/host.d.ts.map +1 -1
  9. package/lib/types/convert/host.js +7 -1
  10. package/lib/types/convert/host.js.map +1 -1
  11. package/lib/types/convert/ingest.d.ts +12 -20
  12. package/lib/types/convert/ingest.d.ts.map +1 -1
  13. package/lib/types/convert/ingest.js +7 -5
  14. package/lib/types/convert/ingest.js.map +1 -1
  15. package/lib/types/diagnosis/store.d.ts +2 -2
  16. package/lib/types/diagnosis/store.d.ts.map +1 -1
  17. package/lib/types/diagnosis/store.js +10 -2
  18. package/lib/types/diagnosis/store.js.map +1 -1
  19. package/lib/types/extract-model.d.ts +3 -0
  20. package/lib/types/extract-model.d.ts.map +1 -1
  21. package/lib/types/extract-model.js.map +1 -1
  22. package/lib/types/index.d.ts.map +1 -1
  23. package/lib/types/index.js +75 -56
  24. package/lib/types/index.js.map +1 -1
  25. package/lib/types/knowledge-bases.d.ts +3 -0
  26. package/lib/types/knowledge-bases.d.ts.map +1 -1
  27. package/lib/types/knowledge-bases.js +22 -2
  28. package/lib/types/knowledge-bases.js.map +1 -1
  29. package/lib/types/model-text.d.ts +7 -0
  30. package/lib/types/model-text.d.ts.map +1 -1
  31. package/lib/types/model-text.js +31 -9
  32. package/lib/types/model-text.js.map +1 -1
  33. package/lib/types/pipeline/engine.d.ts +27 -4
  34. package/lib/types/pipeline/engine.d.ts.map +1 -1
  35. package/lib/types/pipeline/engine.js +59 -12
  36. package/lib/types/pipeline/engine.js.map +1 -1
  37. package/lib/types/pipeline/progress.d.ts +12 -0
  38. package/lib/types/pipeline/progress.d.ts.map +1 -0
  39. package/lib/types/pipeline/progress.js +37 -0
  40. package/lib/types/pipeline/progress.js.map +1 -0
  41. package/lib/types/pipeline/resumable-extract.d.ts +45 -0
  42. package/lib/types/pipeline/resumable-extract.d.ts.map +1 -0
  43. package/lib/types/pipeline/resumable-extract.js +262 -0
  44. package/lib/types/pipeline/resumable-extract.js.map +1 -0
  45. package/lib/types/pipeline/store.d.ts +8 -2
  46. package/lib/types/pipeline/store.d.ts.map +1 -1
  47. package/lib/types/pipeline/store.js +27 -5
  48. package/lib/types/pipeline/store.js.map +1 -1
  49. package/lib/types/pipeline/types.d.ts +50 -0
  50. package/lib/types/pipeline/types.d.ts.map +1 -1
  51. package/lib/types/pipeline/types.js +18 -1
  52. package/lib/types/pipeline/types.js.map +1 -1
  53. package/lib/types/retrieval/scope.d.ts +17 -0
  54. package/lib/types/retrieval/scope.d.ts.map +1 -0
  55. package/lib/types/retrieval/scope.js +11 -0
  56. package/lib/types/retrieval/scope.js.map +1 -0
  57. package/lib/types/runtime.d.ts +55 -8
  58. package/lib/types/runtime.d.ts.map +1 -1
  59. package/lib/types/runtime.js +252 -121
  60. package/lib/types/runtime.js.map +1 -1
  61. package/lib/types/source-identity.d.ts +31 -0
  62. package/lib/types/source-identity.d.ts.map +1 -1
  63. package/lib/types/source-identity.js +80 -0
  64. package/lib/types/source-identity.js.map +1 -1
  65. package/lib/types/source-read.d.ts +18 -0
  66. package/lib/types/source-read.d.ts.map +1 -0
  67. package/lib/types/source-read.js +49 -0
  68. package/lib/types/source-read.js.map +1 -0
  69. package/lib/types/store/knowledge-db.d.ts +5 -29
  70. package/lib/types/store/knowledge-db.d.ts.map +1 -1
  71. package/lib/types/store/knowledge-db.js +42 -1
  72. package/lib/types/store/knowledge-db.js.map +1 -1
  73. package/lib/types/store/source-identity.d.ts +8 -0
  74. package/lib/types/store/source-identity.d.ts.map +1 -0
  75. package/lib/types/store/source-identity.js +56 -0
  76. package/lib/types/store/source-identity.js.map +1 -0
  77. package/lib/types/types.d.ts +41 -1
  78. package/lib/types/types.d.ts.map +1 -1
  79. package/lib/types/types.js.map +1 -1
  80. package/lib/types/wiki-trial-types.d.ts +3 -0
  81. package/lib/types/wiki-trial-types.d.ts.map +1 -1
  82. package/lib/types/wiki-trial.d.ts +3 -3
  83. package/lib/types/wiki-trial.d.ts.map +1 -1
  84. package/lib/types/wiki-trial.js +14 -3
  85. package/lib/types/wiki-trial.js.map +1 -1
  86. package/package.json +1 -1
  87. package/src/agent-behavior-rules.ts +2 -0
  88. package/src/client/AxisRegistrySection.tsx +1 -1
  89. package/src/client/CompileSettingsView.tsx +473 -0
  90. package/src/client/ExtractionTasksPage.tsx +557 -423
  91. package/src/client/KnowledgeBaseTab.tsx +28 -109
  92. package/src/client/PipelineRunView.tsx +173 -0
  93. package/src/client/pages.css +303 -178
  94. package/src/client/pages.tsx +3 -1
  95. package/src/convert/host.ts +7 -1
  96. package/src/convert/ingest.ts +17 -7
  97. package/src/diagnosis/store.ts +7 -2
  98. package/src/extract-model.ts +3 -0
  99. package/src/index.ts +73 -56
  100. package/src/knowledge-bases.ts +23 -3
  101. package/src/model-text.ts +33 -11
  102. package/src/pipeline/engine.ts +76 -19
  103. package/src/pipeline/progress.ts +40 -0
  104. package/src/pipeline/resumable-extract.ts +233 -0
  105. package/src/pipeline/store.ts +28 -6
  106. package/src/pipeline/types.ts +45 -2
  107. package/src/retrieval/scope.ts +10 -0
  108. package/src/runtime.ts +222 -134
  109. package/src/source-identity.ts +81 -0
  110. package/src/source-read.ts +47 -0
  111. package/src/store/knowledge-db.ts +41 -1
  112. package/src/store/source-identity.ts +42 -0
  113. package/src/types.ts +12 -1
  114. package/src/wiki-trial-types.ts +3 -2
  115. package/src/wiki-trial.ts +17 -6
  116. package/src/client/TypeDefinitionDrawer.tsx +0 -195
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AA0ClD,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAA;AACpF,OAAO,EAAiB,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAGpE,OAAO,EACL,YAAY,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,UAAU,IAAI,kBAAkB,EACnG,KAAK,WAAW,EACjB,MAAM,mBAAmB,CAAA;AAG1B,cAAc,YAAY,CAAA;AAC1B,cAAc,cAAc,CAAA;AAC5B,cAAc,sBAAsB,CAAA;AACpC,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,KAAK,WAAW,EAAE,CAAA;AAE7G,eAAO,MAAM,IAAI,8BAA8B,CAAA;AAC/C;;;GAGG;AACH,eAAO,MAAM,MAAM,iDAAkD,CAAA;AAGrE,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,CAAA;AACxD,OAAO,EAAE,uBAAuB,EAAE,CAAA;AAClC;;;;;;;;;GASG;AACH,OAAO,EAAE,MAAM,EAAE,KAAK,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAUvE,OAAO,EAAE,MAAM,EAAE,KAAK,qBAAqB,EAAE,CAAA;AAW7C,wBAAgB,qBAAqB,IAAI,cAAc,GAAG,SAAS,CAAgC;AAuRnG,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,YAAY,GAAE,qBAA0B,GAAG,IAAI,CA89DlF"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AA0ClD,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAA;AACpF,OAAO,EAAiB,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAGpE,OAAO,EACL,YAAY,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,UAAU,IAAI,kBAAkB,EACnG,KAAK,WAAW,EACjB,MAAM,mBAAmB,CAAA;AAG1B,cAAc,YAAY,CAAA;AAC1B,cAAc,cAAc,CAAA;AAC5B,cAAc,sBAAsB,CAAA;AACpC,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,KAAK,WAAW,EAAE,CAAA;AAE7G,eAAO,MAAM,IAAI,8BAA8B,CAAA;AAC/C;;;GAGG;AACH,eAAO,MAAM,MAAM,iDAAkD,CAAA;AAGrE,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,CAAA;AACxD,OAAO,EAAE,uBAAuB,EAAE,CAAA;AAClC;;;;;;;;;GASG;AACH,OAAO,EAAE,MAAM,EAAE,KAAK,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAUvE,OAAO,EAAE,MAAM,EAAE,KAAK,qBAAqB,EAAE,CAAA;AAW7C,wBAAgB,qBAAqB,IAAI,cAAc,GAAG,SAAS,CAAgC;AAuRnG,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,YAAY,GAAE,qBAA0B,GAAG,IAAI,CA8+DlF"}
@@ -1,3 +1,4 @@
1
+ import { newSourceId } from './source-identity.js';
1
2
  import { embeddingModel } from './environment/model-catalog.js';
2
3
  import { createReadStream } from 'node:fs';
3
4
  import { readFile, stat } from 'node:fs/promises';
@@ -14,6 +15,7 @@ import { KnowledgeEnvironment } from './environment/service.js';
14
15
  import { DOC_PAGE_CHARS, DOC_PAGE_CHARS_MAX, documentContentPage } from './document-page.js';
15
16
  import { runWikiTrial, trialSummary } from './wiki-trial.js';
16
17
  import { extractionRunId } from './extraction-runs.js';
18
+ import { DEFAULT_EXTRACTION_TIMEOUT_MINUTES, PIPELINE_ACTIVE_STATES, isExtractionTimeoutMinutes } from './pipeline/types.js';
17
19
  import { agentLayout, defaultAgentRoot, ensureAgentLayout, knowledgeBaseRoot, memoryRoot, resourceRegistry, resourceRoot, } from './layout.js';
18
20
  import { PickerError, createDirectory, listDirectory, pickDirectory, pickerKind, pickerOf, } from './directory-picker.js';
19
21
  import { KNOWLEDGE_SETTINGS_SCHEMA, SETTINGS_NAMESPACE } from './settings-schema.js';
@@ -355,6 +357,7 @@ export function apply(ctx, pluginConfig = {}) {
355
357
  */
356
358
  /** 注册表在默认 runtime 之后才构造;用一个可替换的读取器避开构造期 TDZ。 */
357
359
  let compileModelForBase = () => ({ ...DEFAULT_COMPILE_MODEL });
360
+ let extractionTimeoutForBase = () => DEFAULT_EXTRACTION_TIMEOUT_MINUTES;
358
361
  const modelSeamFor = (kbId = DEFAULT_KB_ID) => {
359
362
  /**
360
363
  * **只能用 `ctx.get(name)`,不能用属性访问。**
@@ -405,7 +408,9 @@ export function apply(ctx, pluginConfig = {}) {
405
408
  provider,
406
409
  model,
407
410
  ...(effectiveReasoningEffort ? { reasoningEffort: effectiveReasoningEffort } : {}),
408
- call: async ({ system, prompt, sessionId, onUsage, onDelta }) => {
411
+ ...(configured.maxTokens !== undefined ? { maxTokens: configured.maxTokens } : {}),
412
+ call: async ({ system, prompt, sessionId, onUsage, onDelta, signal, retryAttempts, maxTokens }) => {
413
+ const outputLimit = maxTokens ?? configured.maxTokens;
409
414
  /**
410
415
  * 先走 DSH 的公开解析接口,再开始发 prompt。这样固定模型过期、默认模型失效时,
411
416
  * 编译会在模型调用边界明确失败,而不是落成一次看似成功的规则抽取。
@@ -415,6 +420,7 @@ export function apply(ctx, pluginConfig = {}) {
415
420
  await llm.resolveCallConfig({
416
421
  provider, model,
417
422
  ...(effectiveReasoningEffort ? { reasoningEffort: effectiveReasoningEffort } : {}),
423
+ ...(outputLimit !== undefined ? { maxTokens: outputLimit } : {}),
418
424
  });
419
425
  }
420
426
  catch (cause) {
@@ -432,7 +438,7 @@ export function apply(ctx, pluginConfig = {}) {
432
438
  * (OpenCode 系路由回 400 `MissingSessionID`)。
433
439
  */
434
440
  const request = buildModelRequest({
435
- provider, model, reasoningEffort: effectiveReasoningEffort, system, prompt,
441
+ provider, model, reasoningEffort: effectiveReasoningEffort, maxTokens: outputLimit, system, prompt,
436
442
  // 运行时按知识库给;接缝被单独调用时(测试)退回一个稳定值,
437
443
  // 而不是留空 —— 留空会在 OpenCode 路由上 400。
438
444
  sessionId: sessionId ?? 'knowledge:default',
@@ -450,12 +456,13 @@ export function apply(ctx, pluginConfig = {}) {
450
456
  * 所以缓存亲和仍然成立。不可重试的错误(凭据、请求体、截断、用户取消)
451
457
  * 由 `isRetryableModelFailure` 放行,不在错的地方多等两分钟。
452
458
  */
453
- return callModelWithRetry(onDeltaOfAttempt => collectModelText(llm.stream(request), onUsage, onDeltaOfAttempt), { ...(onDelta ? { onDelta } : {}) });
459
+ return callModelWithRetry(onDeltaOfAttempt => collectModelText(llm.stream({ ...request, ...(signal ? { signal } : {}) }), onUsage, onDeltaOfAttempt), { ...(onDelta ? { onDelta } : {}), attempts: retryAttempts, signal });
454
460
  },
455
461
  };
456
462
  };
457
463
  let environment;
458
464
  const runtimeOptions = () => ({
465
+ extractionTimeoutMinutes: () => extractionTimeoutForBase(DEFAULT_KB_ID),
459
466
  environmentGuard: kind => environment.requireReady(kind),
460
467
  // 0029:家当目录。配置里三个路径为空时,运行时从这里解析模型与解释器。
461
468
  resourceRoot: resourceRoot(config.agentRoot),
@@ -495,6 +502,7 @@ export function apply(ctx, pluginConfig = {}) {
495
502
  runtimeOptions: () => ({ resourceRoot: resourceRoot(config.agentRoot), modelSeam: modelSeamFor, environmentGuard: kind => environment.requireReady(kind) }),
496
503
  });
497
504
  compileModelForBase = id => bases.compileModelOf(id);
505
+ extractionTimeoutForBase = id => bases.extractionTimeoutMinutesOf(id);
498
506
  runtime.baseId = bases.defaultId;
499
507
  activeKnowledgeBases = bases;
500
508
  environment = new KnowledgeEnvironment({
@@ -581,7 +589,10 @@ export function apply(ctx, pluginConfig = {}) {
581
589
  const item = models.find(model => model.provider === requestedProvider && model.id === requestedModel);
582
590
  if (item) {
583
591
  try {
584
- item.reasoning = (await llm.resolveModelInfo(requestedProvider, requestedModel)).reasoning;
592
+ const info = await llm.resolveModelInfo(requestedProvider, requestedModel);
593
+ item.reasoning = info.reasoning;
594
+ if (info.defaultMaxTokens !== undefined)
595
+ item.defaultMaxTokens = info.defaultMaxTokens;
585
596
  }
586
597
  catch (cause) {
587
598
  failures.push(`思考强度目录:${cause instanceof Error ? cause.message : String(cause)}`);
@@ -780,54 +791,39 @@ export function apply(ctx, pluginConfig = {}) {
780
791
  return Promise.resolve({ kind: 'ask', reason: '该操作会写入 Tita Knowledge Store,需要本轮用户审批。' });
781
792
  return next();
782
793
  });
783
- ctx.tools.register(tool('recall_knowledge', 'Recall Wiki Fact and Wiki Way through H2 title and body search. Use the current subquestion as query when seeking a Procedure. Return complete Wiki files with conditions and evidence. Follow Wiki links with read_knowledge_wiki; browse Object coordinates with its object_id filter. Use get_knowledge_cases for historical Case evidence; a past root cause does not establish the current root cause.', { query: { type: 'string', required: true }, limit: { type: 'integer' }, top_k: { type: 'integer' }, top_n: { type: 'integer' }, rerank: { type: 'boolean' }, context_max_chars: { type: 'integer', description: '这次召回的上下文字符上限;省略则用设置里的值(默认 20000,0 = 不限)。超出部分落在系统临时目录,响应里的 budget.overflow_path 就是它的绝对路径 —— 需要更多信息时直接读那个文件。' }, include_problems: { type: 'boolean' }, mode: { type: 'string', enum: ['fts', 'vector', 'hybrid'] }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, parent_subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' } }, async (args, exec) => withRuntime(args.kb, async (target) => agentRecallEnvelope(await target.recall(args.query, args.top_k ?? args.limit, args.include_problems ?? false, args.mode, lineageOf(args, exec), { contextTopN: args.top_n, rerank: args.rerank, ...(typeof args.context_max_chars === 'number' ? { contextMaxChars: args.context_max_chars } : {}) }))), {
784
- call: recallCallView,
785
- // 查询词从参数来,命中从结果来 —— 两者拼成一张能看懂的账本。
786
- meta: (args, value) => recallMetaOf({ ...dataOf(value), query: args?.query }),
787
- result: resultViewOf(recallResultMarkdown),
794
+ const scopeParameters = { object_id: { type: 'string', description: 'Known Object ID. Omit for all; empty matches empty only.' }, action_id: { type: 'string' }, scene_id: { type: 'string' } };
795
+ const scopeOf = (args) => ({ objectId: args.object_id, actionId: args.action_id, sceneId: args.scene_id, wikiKind: args.wiki_kind });
796
+ ctx.tools.register(tool('recall_knowledge', 'Search H2 sections, rank and deduplicate Wiki files, then deliver complete Wiki Fact / Wiki Way within the budget. Query the current subquestion for methods. top_k counts distinct Wiki candidates; top_n counts delivered hit files. Optional known coordinate IDs and wiki_kind filter every retrieval route before ranking. foundCandidates and contentDelivered distinguish matches from delivered bodies. For budget omissions call read_knowledge_wiki with budget.omitted[].read.args. Scores indicate retrieval relevance, not factual truth. Historical Case does not prove the present root cause.', {
797
+ query: { type: 'string', required: true }, ...scopeParameters, wiki_kind: { type: 'string', enum: ['fact', 'way'] },
798
+ limit: { type: 'integer', description: 'Compatibility alias for top_k.' }, top_k: { type: 'integer', description: 'Distinct Wiki candidates, 1–50.' }, top_n: { type: 'integer', description: 'Maximum complete hit Wiki files to deliver, no more than top_k.' },
799
+ rerank: { type: 'boolean' }, context_max_chars: { type: 'integer', description: 'Complete-context character budget; 0 explicitly disables the limit. Omitted files have stable read references in budget.omitted. overflowPath is a local diagnostic file, not the Agent continuation contract.' },
800
+ include_problems: { type: 'boolean' }, mode: { type: 'string', enum: ['fts', 'vector', 'hybrid'] }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, parent_subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' },
801
+ }, async (args, exec) => withRuntime(args.kb, async (target) => agentRecallEnvelope(await target.recall(args.query, args.top_k ?? args.limit, args.include_problems ?? false, args.mode, lineageOf(args, exec), { ...scopeOf(args), contextTopN: args.top_n, rerank: args.rerank, contextMaxChars: args.context_max_chars }))), {
802
+ call: recallCallView, meta: (args, value) => recallMetaOf({ ...dataOf(value), query: args?.query }), result: resultViewOf(recallResultMarkdown),
788
803
  }));
789
- ctx.tools.register(tool('read_knowledge_wiki', 'Read a complete Wiki through a [[type/entityId|label]] link or stable target. Browse an Object by object_id or unique object name; optional action_id, scene_id and wiki_kind select exact coordinates. Omitted axes mean all; empty axes match empty only. Object browsing returns a paged directory by default. Set include_content to read complete selected files. Follow outgoing links and backlinks as needed; do not fetch every neighbor automatically.', {
790
- target: { type: 'string' }, object_id: { type: 'string' }, object: { type: 'string' }, action_id: { type: 'string' }, scene_id: { type: 'string' }, wiki_kind: { type: 'string', enum: ['fact', 'way'] },
791
- include_content: { type: 'boolean' }, limit: { type: 'integer' }, offset: { type: 'integer' }, kb: { type: 'string' },
792
- }, async (args) => withRuntime(args.kb, target => target.readWiki({ target: args.target, objectId: args.object_id, object: args.object, actionId: args.action_id, sceneId: args.scene_id, wikiKind: args.wiki_kind, includeContent: args.include_content, limit: args.limit, offset: args.offset }))));
793
- ctx.tools.register(tool('get_knowledge_cases', 'Read historical Case records referenced by Wiki metadata.case_refs. Timelines are evidence from a past instance, not proof of the present diagnosis.', {
794
- case_ids: { type: 'array', required: true, description: 'Case IDs from Wiki metadata.case_refs; maximum 50 IDs.' },
795
- version: { type: 'integer', description: 'Optional historical Case version from metadata.case_refs; requires exactly one case ID.' },
796
- kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' },
797
- run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' },
798
- }, async (args) => withRuntime(args.kb, async (target) => {
799
- const ids = [...new Set((Array.isArray(args.case_ids) ? args.case_ids : [])
800
- .filter((id) => typeof id === 'string' && id.trim() !== '').map(id => id.trim()))];
801
- if (ids.length === 0)
802
- return failure({ cases: [], missing_ids: [] }, 'CASE_IDS_REQUIRED', '请传入 Wiki 的 case_refs 中的 Case ID。', false);
803
- if (ids.length > 50)
804
- return failure({ cases: [], missing_ids: [] }, 'CASE_IDS_LIMIT', '一次最多读取 50 个 Case ID。', false);
805
- if (args.version !== undefined && (ids.length !== 1 || !Number.isInteger(args.version) || args.version < 1))
806
- return failure({ cases: [], missing_ids: ids }, 'CASE_VERSION_INVALID', '读取历史版本时,请传一个 Case ID 和正整数 version。', false);
807
- const records = await Promise.all(ids.map(id => target.readCase(id, args.version)));
808
- return success({ cases: records.filter(record => record !== undefined), missing_ids: ids.filter((_, index) => records[index] === undefined) });
809
- })));
810
- ctx.tools.register(tool('get_knowledge_events', 'Read Event records referenced by recalled WikiCards. Pass event IDs from card metadata.event_refs; the result includes full timelines, evidence, outcomes, and missing fields.', {
811
- event_ids: { type: 'array', required: true, description: 'Event IDs from WikiCard metadata.event_refs; maximum 50 IDs.' },
812
- kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' },
813
- run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' },
814
- }, async (args) => withRuntime(args.kb, async (target) => {
815
- const ids = [...new Set((Array.isArray(args.event_ids) ? args.event_ids : [])
816
- .filter((id) => typeof id === 'string' && id.trim() !== '').map(id => id.trim()))];
817
- if (ids.length === 0)
818
- return failure({ events: [], missing_ids: [] }, 'EVENT_IDS_REQUIRED', '请传入 WikiCard 的 event_refs 中的 Event ID。', false);
819
- if (ids.length > 50)
820
- return failure({ events: [], missing_ids: [] }, 'EVENT_IDS_LIMIT', '一次最多读取 50 个 Event ID;请分批读取该 WikiCard 的 event_refs。', false);
821
- const byId = new Map((await target.loadEvents()).map(event => [event.id, event]));
822
- const events = ids.flatMap(id => {
823
- const event = byId.get(id);
824
- return event ? [event] : [];
825
- });
826
- return success({ events, missing_ids: ids.filter(id => !byId.has(id)) });
827
- })));
804
+ ctx.tools.register(tool('read_knowledge_wiki', 'Read a complete Wiki through a stable target or browse an Object directory. Omitted axes mean all; empty axes mean empty only. Directory mode omits content by default. include_content requests complete files within max_chars. If a file does not fit, follow nextRead for explicit body pages, concatenate them and read all conditions before applying a Procedure. expected_version prevents mixing Wiki versions. contentPage is partial unless contentComplete is true. Outgoing links and backlinks are independently bounded by link_limit; advance link_offset using links.nextOffset. Follow only relevant links.', {
805
+ target: { type: 'string' }, ...scopeParameters, object: { type: 'string' }, wiki_kind: { type: 'string', enum: ['fact', 'way'] },
806
+ include_content: { type: 'boolean' }, limit: { type: 'integer' }, offset: { type: 'integer' }, max_chars: { type: 'integer' }, content_offset: { type: 'integer' }, content_max_chars: { type: 'integer' }, expected_version: { type: 'integer' }, link_limit: { type: 'integer' }, link_offset: { type: 'integer' }, kb: { type: 'string' },
807
+ }, async (args) => withRuntime(args.kb, target => target.readWiki({ ...scopeOf(args), target: args.target, object: args.object, includeContent: args.include_content, limit: args.limit, offset: args.offset, maxChars: args.max_chars, contentOffset: args.content_offset, contentMaxChars: args.content_max_chars, expectedVersion: args.expected_version, linkLimit: args.link_limit, linkOffset: args.link_offset }))));
808
+ ctx.tools.register(tool('get_knowledge_cases', 'Find historical Case by current subquestion or exact coordinates, or read referenced case_ids. Search returns a paged directory with version-pinned nextRead references; ID reads include full records within max_chars. Pass one case_id and its version to read historical evidence. Oversized records use explicit contentPage JSON pages; concatenate and parse before using them. Historical actions, observations and outcomes do not prove the current cause.', {
809
+ case_ids: { type: 'array', description: '1–50 known Case IDs; omit for search.' }, query: { type: 'string' }, ...scopeParameters,
810
+ version: { type: 'integer' }, include_content: { type: 'boolean' }, limit: { type: 'integer' }, offset: { type: 'integer' }, max_chars: { type: 'integer' }, content_offset: { type: 'integer' },
811
+ kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' },
812
+ }, async (args) => withRuntime(args.kb, target => target.queryCases({ ...scopeOf(args), ids: args.case_ids, version: args.version, query: args.query, includeContent: args.include_content, limit: args.limit, offset: args.offset, maxChars: args.max_chars, contentOffset: args.content_offset }))));
828
813
  ctx.tools.register(tool('check_knowledge_embeddings', 'Inspect the local embedding provider and binary/int8 vector index without loading the model.', { kb: { type: 'string' }, session_key: { type: 'string' } }, async (args) => withRuntime(args.kb, target => target.embeddingHealth())));
829
814
  ctx.tools.register(tool('query_knowledge_graph', 'Query entities, neighbors, paths, lists and relation types in the compiled knowledge graph.', { action: { type: 'string', enum: ['entity', 'neighbors', 'path', 'list', 'types'], required: true }, entity_id: { type: 'string' }, id: { type: 'string' }, entity_type: { type: 'string' }, from_id: { type: 'string' }, to_id: { type: 'string' }, type: { type: 'string' }, status: { type: 'string' }, include_problem: { type: 'boolean' }, limit: { type: 'integer' }, depth: { type: 'integer' }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, parent_subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' } }, async (args, exec) => withRuntime(args.kb, target => target.graphQuery(args.action, args.entity_id ?? args.id, args.entity_type ?? args.type, args.depth ?? 1, { fromId: args.from_id, toId: args.to_id, status: args.status, includeProblem: args.include_problem ?? false, limit: args.limit ?? 50 }, lineageOf(args, exec)))));
830
- ctx.tools.register(tool('query_source_truth', 'Read SourceRaw (原始可追溯文档) with access audit. Each call returns up to `limit` matched sources and `max_chars` total characters. If `hasMoreInCurrentPage` is true, continue with `offset += returnedChars`. When it is false and `hasMoreSources` is true, continue with `source_offset = nextSourceOffset` and reset `offset` to 0. `truncated` stays true until both the current source page and all matching source pages are complete. Do not answer from partial content.', { query: { type: 'string', required: true }, limit: { type: 'integer' }, max_chars: { type: 'integer' }, offset: { type: 'integer' }, source_offset: { type: 'integer', description: '来源分页游标;当前页字符已读完后才使用 nextSourceOffset,并将 offset 重置为 0' }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' } }, async (args, exec) => withRuntime(args.kb, target => target.sourceTruth(args.query, args.limit ?? 20, args.max_chars ?? 40000, lineageOf(args, exec), args.offset ?? 0, args.source_offset ?? 0))));
815
+ ctx.tools.register(tool('query_source_truth', 'Read a precise Source Raw using source_id plus the evidence version, optional content_hash and [start,end) UTF-16 offsets. Prefer readRef returned by knowledge tools. IDs are opaque and scoped to kb; never infer one from a title, path, hash or external_id. Unknown IDs, unavailable versions and mismatched hashes or quotes fail explicitly; there is no fallback to another source. Exact-read offset is relative to the selected range; follow nextRead to continue. Without source_id, query discovers sources and returns version-pinned readRef for precise follow-up. Discovery uses source_offset for source pages and offset for text pages; advance with returnedChars and nextSourceOffset. Do not apply incomplete evidence.', {
816
+ source_id: { type: 'string' }, version: { type: 'integer' }, content_hash: { type: 'string' }, start: { type: 'integer' }, end: { type: 'integer' }, quote: { type: 'string' }, query: { type: 'string' }, limit: { type: 'integer' }, max_chars: { type: 'integer' }, offset: { type: 'integer' }, source_offset: { type: 'integer' }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' },
817
+ }, async (args, exec) => withRuntime(args.kb, async (target) => {
818
+ if (args.source_id !== undefined) {
819
+ if (args.query !== undefined || args.source_offset !== undefined)
820
+ return failure({}, 'SOURCE_SELECTION_CONFLICT', '精确读取 source_id 时不要传 query 或 source_offset。', false);
821
+ return target.readSource({ sourceId: args.source_id, version: args.version, contentHash: args.content_hash, start: args.start, end: args.end, quote: args.quote, maxChars: args.max_chars, offset: args.offset }, lineageOf(args, exec));
822
+ }
823
+ if (typeof args.query !== 'string' || !args.query.trim() || [args.version, args.content_hash, args.start, args.end, args.quote].some(value => value !== undefined))
824
+ return failure({}, 'SOURCE_QUERY_REQUIRED', '搜索请传非空 query;版本、哈希和引文范围读取必须提供 source_id。', false);
825
+ return target.sourceTruth(args.query, args.limit ?? 20, args.max_chars ?? 40000, lineageOf(args, exec), args.offset ?? 0, args.source_offset ?? 0);
826
+ })));
831
827
  /**
832
828
  * 知识库 id 的**发现入口**。
833
829
  *
@@ -878,7 +874,13 @@ export function apply(ctx, pluginConfig = {}) {
878
874
  });
879
875
  const imagePublishDescription = 'Publish one local image into a knowledge base assets bucket without user approval. Pass exactly one of `file_path` or `content_base64` (standard Base64 or a data URI); optional `filename` overrides the stored name, and optional `mime_type` must match the file bytes. Supports PNG, JPEG, GIF, WebP, AVIF, BMP and SVG up to 20 MiB. Returns the local asset URL and Markdown image reference.';
880
876
  ctx.tools.register(tool('image_publish', imagePublishDescription, imagePublishParameters, publishImage));
881
- ctx.tools.register(tool('add_source', 'Add or update a SourceRaw document (原始可追溯文档). DSH requests one user approval before execution.', { title: { type: 'string' }, content: { type: 'string', required: true }, external_id: { type: 'string' }, metadata: { type: 'json' }, source_id: { type: 'string' }, allow_duplicate_title: { type: 'boolean', description: '默认 false:标题与已有来源重复时拒收(SOURCE_TITLE_DUPLICATED),要求改标题。传 true 才允许并存。' }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' } }, async (args, exec) => withRuntime(args.kb, target => target.addSource({ title: args.title, content: args.content, externalId: args.external_id, metadata: args.metadata, sourceId: args.source_id, ...(args.allow_duplicate_title === true ? { allowDuplicateTitle: true } : {}), lineage: lineageOf(args, exec) })), {
877
+ ctx.tools.register(tool('allocate_source_ids', 'Allocate opaque Source Raw IDs before import. Keep one ID per independent input; reuse it across conversion, transport retries, renames and updates. IDs are not reserved documents until imported. Existing sources keep their current IDs. Never allocate a new ID to update an existing source.', { count: { type: 'integer', description: '1–100, default 1.' } }, async (args) => {
878
+ const count = args.count ?? 1;
879
+ if (!Number.isInteger(count) || count < 1 || count > 100)
880
+ return failure({ source_ids: [] }, 'SOURCE_COUNT_INVALID', 'count 必须为 1–100。', false);
881
+ return success({ source_ids: Array.from({ length: count }, () => newSourceId()) });
882
+ }));
883
+ ctx.tools.register(tool('add_source', 'Add or update Source Raw. For links/platform documents pass source_url or source_identity: identity lookup reuses the existing source_id, otherwise allocates one. For independent files first use allocate_source_ids and retain the ID across retries. Updates use the known source_id and preferably expected_version from an exact read (0 means create only). Titles, paths, body hashes and arbitrary external_id are not update keys. A preallocated unused ID may resolve to an existing document; always use the returned sourceId. Known IDs with contradictory origin fail. Returns a version-pinned readRef. DSH requests one user approval before execution.', { title: { type: 'string' }, content: { type: 'string', required: true }, external_id: { type: 'string' }, metadata: { type: 'json' }, source_id: { type: 'string' }, source_url: { type: 'string', description: 'Explicit acquisition URL, preserving query and fragment. Do not copy an unverified link from body text.' }, source_identity: { type: 'json', description: '{system, scope, document_id, document_type?, url?}; native identity requires system, scope and document_id. URL-only identity can use {url, scope?}.' }, expected_version: { type: 'integer' }, allow_duplicate_title: { type: 'boolean', description: '默认 false:标题与已有来源重复时拒收(SOURCE_TITLE_DUPLICATED),要求改标题。传 true 才允许并存。' }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' } }, async (args, exec) => (typeof args.source_id !== 'string' || !args.source_id.trim()) && args.source_url === undefined && args.source_identity === undefined ? failure({ sourceId: '' }, 'SOURCE_ID_REQUIRED', '请先分配 source_id;重试或更新复用已有 ID。', false) : withRuntime(args.kb, target => target.addSource({ title: args.title, content: args.content, externalId: args.external_id, metadata: args.metadata, sourceId: args.source_id, sourceUrl: args.source_url, sourceIdentity: args.source_identity, expectedVersion: args.expected_version, ...(args.allow_duplicate_title === true ? { allowDuplicateTitle: true } : {}), lineage: lineageOf(args, exec) })), {
882
884
  call: addSourceCallView,
883
885
  meta: (args, value) => addSourceMetaOf(args, dataOf(value)),
884
886
  result: resultViewOf(addSourceResultMarkdown),
@@ -897,7 +899,7 @@ export function apply(ctx, pluginConfig = {}) {
897
899
  * `compile` 默认关闭:先保存来源,再由调用方决定何时处理。显式 true 才跑全链路;
898
900
  * 未触发处理时工具返回 `compile: null`。
899
901
  */
900
- ctx.tools.register(tool('import_sources', 'Import many SourceRaw documents in one call. By default only stores sources. Explicit compile:true runs extract, normalize, materialize, and index publication for the imported documents. Per-source import failures are reported without aborting the batch. DSH requests one user approval before execution.', { sources: { type: 'array', required: true, description: `来源数组,每项 { source_id?, title?, content, external_id?, metadata?, allow_duplicate_title? };文件导入前分配唯一 source_id,重试沿用;更新旧来源必须传其 source_id;一次最多 ${MAX_IMPORT_SOURCES} 份,超了请分批。标题与已有来源重复的那一份会被拒(SOURCE_TITLE_DUPLICATED),逐条报出来而不是整批失败` }, compile: { type: 'boolean', description: '默认 false:只保存来源;显式 true 才运行完整抽取、归一与物化' }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' } }, async (args, exec) => withRuntime(args.kb, target => target.importSources({ sources: (Array.isArray(args.sources) ? args.sources : []).map(item => ({ ...(item?.source_id ? { sourceId: item.source_id } : {}), ...(item?.title ? { title: item.title } : {}), content: item?.content, ...(item?.external_id ? { externalId: item.external_id } : {}), ...(item?.metadata ? { metadata: item.metadata } : {}), ...(item?.allow_duplicate_title === true ? { allowDuplicateTitle: true } : {}) })), compile: args.compile === true, lineage: lineageOf(args, exec) })), { call: importCallView, meta: (_args, value) => importMetaOf(dataOf(value)), result: resultViewOf(importResultMarkdown) }));
902
+ ctx.tools.register(tool('import_sources', 'Import many SourceRaw documents in one call. By default only stores sources. Explicit compile:true runs extract, normalize, materialize, and index publication for the imported documents. Per-source import failures are reported without aborting the batch. DSH requests one user approval before execution.', { sources: { type: 'array', required: true, description: `来源数组,每项 { source_id?, source_url?, source_identity?, expected_version?, title?, content, external_id?, metadata?, allow_duplicate_title? };链接提供 source_url 或 source_identity,先查来源映射;独立文件先分配 source_id,重试沿用;以后续返回的 sourceId 为准;更新旧来源必须传其 source_id;一次最多 ${MAX_IMPORT_SOURCES} 份,超了请分批。标题与已有来源重复的那一份会被拒(SOURCE_TITLE_DUPLICATED),逐条报出来而不是整批失败` }, compile: { type: 'boolean', description: '默认 false:只保存来源;显式 true 才运行完整抽取、归一与物化' }, kb: { type: 'string' }, session_key: { type: 'string' }, task_id: { type: 'string' }, subtask_id: { type: 'string' }, run_id: { type: 'string' }, turn_id: { type: 'string' }, trace_id: { type: 'string' }, domain: { type: 'string' } }, async (args, exec) => Array.isArray(args.sources) && args.sources.some(item => (typeof item?.source_id !== 'string' || !item.source_id.trim()) && item?.source_url === undefined && item?.source_identity === undefined) ? failure({}, 'SOURCE_ID_REQUIRED', '请先为每个输入分配 source_id;重试或更新沿用已有 ID。', false) : withRuntime(args.kb, target => target.importSources({ sources: (Array.isArray(args.sources) ? args.sources : []).map(item => ({ ...(item?.source_id ? { sourceId: item.source_id } : {}), ...(item?.expected_version === undefined ? {} : { expectedVersion: item.expected_version }), ...(item?.source_url === undefined ? {} : { sourceUrl: item.source_url }), ...(item?.source_identity === undefined ? {} : { sourceIdentity: item.source_identity }), ...(item?.title ? { title: item.title } : {}), content: item?.content, ...(item?.external_id ? { externalId: item.external_id } : {}), ...(item?.metadata ? { metadata: item.metadata } : {}), ...(item?.allow_duplicate_title === true ? { allowDuplicateTitle: true } : {}) })), compile: args.compile === true, lineage: lineageOf(args, exec) })), { call: importCallView, meta: (_args, value) => importMetaOf(dataOf(value)), result: resultViewOf(importResultMarkdown) }));
901
903
  /**
902
904
  * `propose_wiki_cards` —— 把一批卡片**直接写进 `02_wiki`**(工具名不变,语义在 0044 改了)。
903
905
  *
@@ -1051,6 +1053,7 @@ export function apply(ctx, pluginConfig = {}) {
1051
1053
  return sendEnvelope(res, await resolved.runtime.readWiki({ target: url.searchParams.get('target') ?? undefined, objectId: url.searchParams.get('object_id') ?? undefined, object: url.searchParams.get('object') ?? undefined,
1052
1054
  actionId: url.searchParams.get('action_id') ?? undefined, sceneId: url.searchParams.get('scene_id') ?? undefined, wikiKind: (url.searchParams.get('wiki_kind') ?? undefined),
1053
1055
  includeContent: url.searchParams.has('include_content') ? url.searchParams.get('include_content') === 'true' : undefined,
1056
+ ...Object.fromEntries([['max_chars', 'maxChars'], ['content_offset', 'contentOffset'], ['content_max_chars', 'contentMaxChars'], ['expected_version', 'expectedVersion'], ['link_limit', 'linkLimit'], ['link_offset', 'linkOffset']].filter(([key]) => url.searchParams.has(key)).map(([key, field]) => [field, Number(url.searchParams.get(key))])),
1054
1057
  limit: url.searchParams.has('limit') ? Number(url.searchParams.get('limit')) : undefined, offset: url.searchParams.has('offset') ? Number(url.searchParams.get('offset')) : undefined }));
1055
1058
  } },
1056
1059
  { kind: 'exact', path: '/knowledge/cases', handler: async (req, res) => {
@@ -1079,6 +1082,7 @@ export function apply(ctx, pluginConfig = {}) {
1079
1082
  const rerankParam = url.searchParams.get('rerank');
1080
1083
  // 响应里始终带 routes + backend,前端据此显示「Coordinate / 关键词 / 向量」三路状态。
1081
1084
  return send(res, 200, await resolved.runtime.recall(url.searchParams.get('query') ?? '', topK === null ? undefined : Number(topK), url.searchParams.get('include_problems') === 'true', (url.searchParams.get('mode') ?? undefined), lineageFromUrl(url), {
1085
+ ...scopeOf(Object.fromEntries(['object_id', 'action_id', 'scene_id', 'wiki_kind'].filter(key => url.searchParams.has(key)).map(key => [key, url.searchParams.get(key)]))),
1082
1086
  ...(topN === null ? {} : { contextTopN: Number(topN) }),
1083
1087
  ...(rerankParam === null ? {} : { rerank: rerankParam !== 'false' && rerankParam !== '0' }),
1084
1088
  ...(url.searchParams.get('context_max_chars') === null ? {} : { contextMaxChars: Number(url.searchParams.get('context_max_chars')) }),
@@ -1181,7 +1185,7 @@ export function apply(ctx, pluginConfig = {}) {
1181
1185
  const pipeline = await resolved.runtime.pipeline();
1182
1186
  const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit')) || 20));
1183
1187
  const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
1184
- return send(res, 200, success({ ...pipeline.store.tasks(limit, offset), extractions: await resolved.runtime.listExtractionRuns({ limit, offset }) }));
1188
+ return send(res, 200, success({ ...pipeline.store.tasks(limit, offset), activeTasks: pipeline.store.activeTasks(), extractions: await resolved.runtime.listExtractionRuns({ limit, offset }) }));
1185
1189
  }
1186
1190
  catch (cause) {
1187
1191
  return send(res, 400, envelopeError('PIPELINE_HISTORY_FAILED', cause instanceof Error ? cause.message : String(cause)));
@@ -1203,6 +1207,8 @@ export function apply(ctx, pluginConfig = {}) {
1203
1207
  return send(res, 200, success({ task, ...pipeline.store.events(id, Math.max(0, Number(url.searchParams.get('after')) || 0)) }));
1204
1208
  if (req.method !== 'POST')
1205
1209
  return send(res, 405, envelopeError('METHOD_NOT_ALLOWED', '任务只接受 GET 或 POST'));
1210
+ if (body.action === 'retry' && PIPELINE_ACTIVE_STATES.includes(task.state))
1211
+ throw new Error('任务仍在运行,请先停止或等待完成');
1206
1212
  if (body.action === 'retry')
1207
1213
  return send(res, 202, success({ task: pipeline.start(task.stage, { ...task.selection, force: false }).task }));
1208
1214
  if (!['pause', 'resume', 'cancel'].includes(body.action))
@@ -1314,6 +1320,9 @@ export function apply(ctx, pluginConfig = {}) {
1314
1320
  ...(item?.title ? { title: String(item.title) } : {}),
1315
1321
  content: item?.content,
1316
1322
  ...(item?.source_id ? { sourceId: String(item.source_id) } : {}),
1323
+ ...(item?.source_url === undefined ? {} : { sourceUrl: item.source_url }),
1324
+ ...(item?.source_identity === undefined ? {} : { sourceIdentity: item.source_identity }),
1325
+ ...(item?.expected_version === undefined ? {} : { expectedVersion: item.expected_version }),
1317
1326
  ...(item?.external_id ? { externalId: String(item.external_id) } : {}),
1318
1327
  ...(item?.metadata && typeof item.metadata === 'object' ? { metadata: item.metadata } : {}),
1319
1328
  ...(item?.allow_duplicate_title === true ? { allowDuplicateTitle: true } : {}),
@@ -1333,7 +1342,7 @@ export function apply(ctx, pluginConfig = {}) {
1333
1342
  const resolved = resolveBase(body.kb ?? query(req).searchParams.get('kb'));
1334
1343
  if ('failure' in resolved)
1335
1344
  return sendEnvelope(res, resolved.failure);
1336
- return send(res, 200, await resolved.runtime.addSource({ title: body.title, content: body.content, externalId: body.external_id, metadata: body.metadata, sourceId: body.source_id, ...(body.allow_duplicate_title === true ? { allowDuplicateTitle: true } : {}), lineage: lineageOf(body) }));
1345
+ return send(res, 200, await resolved.runtime.addSource({ title: body.title, content: body.content, externalId: body.external_id, metadata: body.metadata, sourceId: body.source_id, sourceUrl: body.source_url, sourceIdentity: body.source_identity, expectedVersion: body.expected_version, ...(body.allow_duplicate_title === true ? { allowDuplicateTitle: true } : {}), lineage: lineageOf(body) }));
1337
1346
  }
1338
1347
  if (req.method !== 'GET')
1339
1348
  return send(res, 405, envelopeError('METHOD_NOT_ALLOWED', '该 knowledge endpoint 只接受 GET 或 POST'));
@@ -1341,6 +1350,11 @@ export function apply(ctx, pluginConfig = {}) {
1341
1350
  const resolved = resolveBase(url.searchParams.get('kb'));
1342
1351
  if ('failure' in resolved)
1343
1352
  return sendEnvelope(res, resolved.failure);
1353
+ if (url.searchParams.has('source_id'))
1354
+ return sendEnvelope(res, await resolved.runtime.readSource({ sourceId: url.searchParams.get('source_id'),
1355
+ contentHash: url.searchParams.get('content_hash') ?? undefined, quote: url.searchParams.get('quote') ?? undefined,
1356
+ ...Object.fromEntries([['version', 'version'], ['start', 'start'], ['end', 'end'], ['offset', 'offset'], ['max_chars', 'maxChars']].filter(([key]) => url.searchParams.has(key)).map(([key, field]) => [field, Number(url.searchParams.get(key))])),
1357
+ }, lineageFromUrl(url)));
1344
1358
  return send(res, 200, await resolved.runtime.sourceTruth(url.searchParams.get('query') ?? '', Number(url.searchParams.get('limit') ?? 20) || 20, Number(url.searchParams.get('max_chars') ?? 40000) || 40000, lineageFromUrl(url), Number(url.searchParams.get('offset') ?? 0) || 0, Number(url.searchParams.get('source_offset') ?? 0) || 0));
1345
1359
  }
1346
1360
  catch (cause) {
@@ -1964,7 +1978,7 @@ export function apply(ctx, pluginConfig = {}) {
1964
1978
  * ```
1965
1979
  * /knowledge/pages/trial?kb=<知识库 id> 抽取试跑
1966
1980
  * /knowledge/pages/run?kb=<库 id>&run=<轨迹 id> 一次抽取的完整报告
1967
- * /knowledge/pages/tasks?kb=<知识库 id> 抽取任务
1981
+ * /knowledge/pages/tasks?kb=<知识库 id> 知识处理与编译设置
1968
1982
  * /knowledge/pages/help/compile 编译链路
1969
1983
  * /knowledge/pages/help/overview?node=... 五个 Tab 的方案说明
1970
1984
  * ```
@@ -1993,7 +2007,7 @@ export function apply(ctx, pluginConfig = {}) {
1993
2007
  : rest[1] === 'run'
1994
2008
  ? '抽取轨迹'
1995
2009
  : rest[1] === 'tasks'
1996
- ? '抽取任务'
2010
+ ? '知识处理'
1997
2011
  : rest[1] === 'help' && rest[2] === 'compile'
1998
2012
  ? '编译链路'
1999
2013
  : rest[1] === 'help' && rest[2] === 'overview' ? 'Agent 方案说明' : '整页';
@@ -2028,6 +2042,8 @@ export function apply(ctx, pluginConfig = {}) {
2028
2042
  if (rest.length === 2) {
2029
2043
  if (method === 'PATCH') {
2030
2044
  const body = await readBody(req);
2045
+ if (body.extractionTimeoutMinutes !== undefined && !isExtractionTimeoutMinutes(body.extractionTimeoutMinutes))
2046
+ return send(res, 400, envelopeError('EXTRACTION_TIMEOUT_INVALID', '文档抽取时限只能选择 30、60 或 100 分钟,最大 100 分钟。'));
2031
2047
  if (body.compileModel && typeof body.compileModel === 'object') {
2032
2048
  const selection = body.compileModel;
2033
2049
  const catalog = await compileModelCatalog(baseId);
@@ -2035,6 +2051,8 @@ export function apply(ctx, pluginConfig = {}) {
2035
2051
  const model = selection.mode === 'fixed' ? selection.model : catalog.default.model;
2036
2052
  if (selection.mode !== 'fixed' && selection.mode !== 'default')
2037
2053
  return send(res, 400, envelopeError('MODEL_INVALID', '请选择跟随默认或固定模型'));
2054
+ if (selection.maxTokens !== undefined && (!Number.isSafeInteger(selection.maxTokens) || selection.maxTokens <= 0))
2055
+ return send(res, 400, envelopeError('MODEL_INVALID', '单次最大输出必须是正整数 token;留空表示跟随模型默认。'));
2038
2056
  if (selection.mode === 'fixed' && (!provider || !model))
2039
2057
  return send(res, 400, envelopeError('MODEL_INVALID', '固定模型需要 provider 和 model'));
2040
2058
  const llm = ctx.get('llm');
@@ -2044,7 +2062,7 @@ export function apply(ctx, pluginConfig = {}) {
2044
2062
  const effort = info?.reasoning?.efforts.find(item => item.id === selection.reasoningEffort);
2045
2063
  if (selection.reasoningEffort && !effort)
2046
2064
  throw new Error('所选模型不支持这个思考强度,请重新选择');
2047
- await llm.resolveCallConfig({ provider, model, ...(effort ? { reasoningEffort: effort.id } : {}) });
2065
+ await llm.resolveCallConfig({ provider, model, ...(effort ? { reasoningEffort: effort.id } : {}), ...(selection.maxTokens !== undefined ? { maxTokens: selection.maxTokens } : {}) });
2048
2066
  }
2049
2067
  catch (cause) {
2050
2068
  return send(res, 400, envelopeError('MODEL_INVALID', cause instanceof Error ? cause.message : String(cause)));
@@ -2056,6 +2074,7 @@ export function apply(ctx, pluginConfig = {}) {
2056
2074
  const updated = await bases.update(baseId, {
2057
2075
  name: body.name, description: body.description,
2058
2076
  extractionNote: typeof body.extractionNote === 'string' ? body.extractionNote : undefined,
2077
+ extractionTimeoutMinutes: body.extractionTimeoutMinutes,
2059
2078
  compileModel: body.compileModel && typeof body.compileModel === 'object'
2060
2079
  ? body.compileModel
2061
2080
  : undefined,