@octopi-agent/engine 0.58.0 → 0.70.7

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 (226) hide show
  1. package/dist/config-schema/context.d.ts +1 -1
  2. package/dist/config-schema/context.js +1 -1
  3. package/dist/config-schema/engine.d.ts +122 -1
  4. package/dist/config-schema/engine.js +4 -1
  5. package/dist/config-schema/substrate.d.ts +123 -0
  6. package/dist/config-schema/substrate.js +161 -0
  7. package/dist/config.d.ts +101 -1
  8. package/dist/harness/agent/builder.d.ts +15 -1
  9. package/dist/harness/agent/builder.js +41 -4
  10. package/dist/harness/agent/config-bridge.js +17 -4
  11. package/dist/harness/{context/capabilities → capabilities}/document/backends/docx.d.ts +1 -1
  12. package/dist/harness/{context/capabilities → capabilities}/document/backends/docx.js +1 -1
  13. package/dist/harness/{context/capabilities → capabilities}/document/backends/office-parser.d.ts +1 -1
  14. package/dist/harness/{context/capabilities → capabilities}/document/backends/office-parser.js +1 -1
  15. package/dist/harness/{context/capabilities → capabilities}/document/backends/pdf.d.ts +1 -1
  16. package/dist/harness/{context/capabilities → capabilities}/document/backends/pdf.js +13 -3
  17. package/dist/harness/{context/capabilities → capabilities}/document/backends/plain.d.ts +1 -1
  18. package/dist/harness/{context/capabilities → capabilities}/document/backends/plain.js +13 -4
  19. package/dist/harness/{context/capabilities → capabilities}/document/backends/sheet.d.ts +1 -1
  20. package/dist/harness/{context/capabilities → capabilities}/document/backends/sheet.js +25 -5
  21. package/dist/harness/{context/capabilities → capabilities}/document/backends/xmind.d.ts +1 -1
  22. package/dist/harness/{context/capabilities → capabilities}/document/backends/xmind.js +1 -1
  23. package/dist/harness/{context/capabilities → capabilities}/document/errors.d.ts +1 -1
  24. package/dist/harness/{context/capabilities → capabilities}/document/errors.js +1 -1
  25. package/dist/harness/capabilities/document/factory.d.ts +33 -0
  26. package/dist/harness/capabilities/document/factory.js +37 -0
  27. package/dist/harness/{context/capabilities → capabilities}/document/format.d.ts +1 -1
  28. package/dist/harness/{context/capabilities → capabilities}/document/format.js +1 -1
  29. package/dist/harness/{context/capabilities → capabilities}/document/html-to-md.d.ts +1 -1
  30. package/dist/harness/{context/capabilities → capabilities}/document/html-to-md.js +1 -1
  31. package/dist/harness/{context/capabilities → capabilities}/document/index.d.ts +3 -1
  32. package/dist/harness/{context/capabilities → capabilities}/document/index.js +2 -1
  33. package/dist/harness/{context/capabilities → capabilities}/document/legacy/factory.d.ts +3 -1
  34. package/dist/harness/{context/capabilities → capabilities}/document/legacy/factory.js +3 -1
  35. package/dist/harness/{context/capabilities → capabilities}/document/legacy/soffice.d.ts +3 -1
  36. package/dist/harness/{context/capabilities → capabilities}/document/legacy/soffice.js +44 -1
  37. package/dist/harness/{context/capabilities → capabilities}/document/port.d.ts +1 -1
  38. package/dist/harness/{context/capabilities → capabilities}/document/port.js +4 -4
  39. package/dist/harness/{context/capabilities → capabilities}/document/types.d.ts +11 -1
  40. package/dist/harness/{context/capabilities → capabilities}/document/types.js +1 -1
  41. package/dist/harness/capabilities/document/worker-port.d.ts +13 -0
  42. package/dist/harness/capabilities/document/worker-port.js +78 -0
  43. package/dist/harness/context/capabilities/index.d.ts +2 -2
  44. package/dist/harness/context/capabilities/index.js +2 -2
  45. package/dist/harness/context/capabilities/summary/gate.js +2 -2
  46. package/dist/harness/context/capabilities/summary/policies.js +5 -5
  47. package/dist/harness/context/capabilities/summary/registry.js +29 -24
  48. package/dist/harness/context/layer-health.js +3 -2
  49. package/dist/harness/context/layers.d.ts +27 -13
  50. package/dist/harness/context/layers.js +76 -66
  51. package/dist/harness/context/system-prompt-assembler.d.ts +3 -0
  52. package/dist/harness/context/system-prompt-assembler.js +11 -1
  53. package/dist/harness/extension/plugin-ecosystem/client-tools/index.d.ts +4 -0
  54. package/dist/harness/extension/plugin-ecosystem/client-tools/index.js +3 -0
  55. package/dist/harness/extension/plugin-ecosystem/client-tools/invoke.d.ts +56 -0
  56. package/dist/harness/extension/plugin-ecosystem/client-tools/invoke.js +281 -0
  57. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.d.ts +98 -0
  58. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.js +250 -0
  59. package/dist/harness/extension/plugin-ecosystem/client-tools/stream.d.ts +124 -0
  60. package/dist/harness/extension/plugin-ecosystem/client-tools/stream.js +372 -0
  61. package/dist/harness/extension/plugin-ecosystem/client-tools/types.d.ts +109 -0
  62. package/dist/harness/extension/plugin-ecosystem/client-tools/types.js +8 -0
  63. package/dist/harness/extension/plugin-ecosystem/index.d.ts +1 -0
  64. package/dist/harness/extension/plugin-ecosystem/index.js +1 -0
  65. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +1 -1
  66. package/dist/harness/extension/plugin-ecosystem/tools/knowledge.d.ts +10 -0
  67. package/dist/harness/extension/plugin-ecosystem/tools/knowledge.js +102 -5
  68. package/dist/harness/extension/plugin-ecosystem/tools/memory.d.ts +11 -1
  69. package/dist/harness/extension/plugin-ecosystem/tools/memory.js +14 -0
  70. package/dist/harness/index.d.ts +8 -5
  71. package/dist/harness/index.js +4 -2
  72. package/dist/harness/knowledge/adapters.d.ts +8 -5
  73. package/dist/harness/knowledge/adapters.js +53 -13
  74. package/dist/harness/knowledge/client.d.ts +197 -0
  75. package/dist/harness/knowledge/client.js +237 -0
  76. package/dist/harness/knowledge/connector-fetcher.d.ts +2 -2
  77. package/dist/harness/knowledge/connectors.d.ts +3 -3
  78. package/dist/harness/knowledge/connectors.js +14 -8
  79. package/dist/harness/knowledge/db.d.ts +40 -5
  80. package/dist/harness/knowledge/db.js +441 -113
  81. package/dist/harness/knowledge/document-extract-worker.js +55 -12
  82. package/dist/harness/knowledge/embed-runner.d.ts +53 -0
  83. package/dist/harness/knowledge/embed-runner.js +171 -0
  84. package/dist/harness/knowledge/engine-thread.d.ts +1 -0
  85. package/dist/harness/knowledge/engine-thread.js +302 -0
  86. package/dist/harness/knowledge/extract-document.d.ts +21 -5
  87. package/dist/harness/knowledge/extract-document.js +32 -8
  88. package/dist/harness/knowledge/fetchers.d.ts +14 -3
  89. package/dist/harness/knowledge/fetchers.js +52 -16
  90. package/dist/harness/knowledge/file-identity.d.ts +53 -0
  91. package/dist/harness/knowledge/file-identity.js +172 -0
  92. package/dist/harness/knowledge/file-index-store.d.ts +50 -0
  93. package/dist/harness/knowledge/file-index-store.js +132 -0
  94. package/dist/harness/knowledge/file-limits.d.ts +86 -0
  95. package/dist/harness/knowledge/file-limits.js +175 -0
  96. package/dist/harness/knowledge/fts.d.ts +60 -0
  97. package/dist/harness/knowledge/fts.js +218 -0
  98. package/dist/harness/knowledge/grounding.d.ts +3 -2
  99. package/dist/harness/knowledge/http-app.d.ts +50 -0
  100. package/dist/harness/knowledge/http-app.js +652 -0
  101. package/dist/harness/knowledge/http-bridge.d.ts +49 -0
  102. package/dist/harness/knowledge/http-bridge.js +17 -0
  103. package/dist/harness/knowledge/index-store.d.ts +158 -93
  104. package/dist/harness/knowledge/index-store.js +982 -441
  105. package/dist/harness/knowledge/index.d.ts +45 -5
  106. package/dist/harness/knowledge/index.js +23 -2
  107. package/dist/harness/knowledge/ingest.d.ts +262 -87
  108. package/dist/harness/knowledge/ingest.js +1072 -480
  109. package/dist/harness/knowledge/job-control-state.d.ts +29 -0
  110. package/dist/harness/knowledge/job-control-state.js +44 -0
  111. package/dist/harness/knowledge/job-control.d.ts +35 -0
  112. package/dist/harness/knowledge/job-control.js +86 -0
  113. package/dist/harness/knowledge/job-queue.d.ts +62 -0
  114. package/dist/harness/knowledge/job-queue.js +173 -0
  115. package/dist/harness/knowledge/knowledge-serve-child.d.ts +1 -0
  116. package/dist/harness/knowledge/knowledge-serve-child.js +100 -0
  117. package/dist/harness/knowledge/local-stack.d.ts +27 -0
  118. package/dist/harness/knowledge/local-stack.js +63 -0
  119. package/dist/harness/knowledge/membership-store.d.ts +65 -0
  120. package/dist/harness/knowledge/membership-store.js +198 -0
  121. package/dist/harness/knowledge/network-guard.d.ts +11 -2
  122. package/dist/harness/knowledge/network-guard.js +130 -85
  123. package/dist/harness/knowledge/parse-text-in-worker.d.ts +32 -0
  124. package/dist/harness/knowledge/parse-text-in-worker.js +158 -0
  125. package/dist/harness/knowledge/query-service.d.ts +272 -0
  126. package/dist/harness/knowledge/query-service.js +326 -0
  127. package/dist/harness/knowledge/query-worker-client.d.ts +96 -0
  128. package/dist/harness/knowledge/query-worker-client.js +207 -0
  129. package/dist/harness/knowledge/query-worker.d.ts +1 -0
  130. package/dist/harness/knowledge/query-worker.js +186 -0
  131. package/dist/harness/knowledge/read-http.d.ts +35 -0
  132. package/dist/harness/knowledge/read-http.js +373 -0
  133. package/dist/harness/knowledge/retriever.d.ts +22 -5
  134. package/dist/harness/knowledge/retriever.js +66 -35
  135. package/dist/harness/knowledge/secret-scan.d.ts +13 -2
  136. package/dist/harness/knowledge/secret-scan.js +25 -2
  137. package/dist/harness/knowledge/serve.d.ts +48 -0
  138. package/dist/harness/knowledge/serve.js +336 -0
  139. package/dist/harness/knowledge/source-store.d.ts +97 -19
  140. package/dist/harness/knowledge/source-store.js +166 -94
  141. package/dist/harness/knowledge/start-service-process.d.ts +49 -0
  142. package/dist/harness/knowledge/start-service-process.js +158 -0
  143. package/dist/harness/knowledge/text-parse-worker.d.ts +1 -0
  144. package/dist/harness/knowledge/text-parse-worker.js +54 -0
  145. package/dist/harness/knowledge/types.d.ts +1 -1
  146. package/dist/harness/knowledge/types.js +1 -1
  147. package/dist/harness/knowledge/vector-ann.d.ts +42 -0
  148. package/dist/harness/knowledge/vector-ann.js +68 -0
  149. package/dist/harness/knowledge/writer-lock.d.ts +13 -0
  150. package/dist/harness/knowledge/writer-lock.js +71 -0
  151. package/dist/harness/knowledge/writer-service.d.ts +194 -0
  152. package/dist/harness/knowledge/writer-service.js +355 -0
  153. package/dist/harness/knowledge/writer-worker-client.d.ts +102 -0
  154. package/dist/harness/knowledge/writer-worker-client.js +381 -0
  155. package/dist/harness/knowledge/writer-worker.d.ts +1 -0
  156. package/dist/harness/knowledge/writer-worker.js +189 -0
  157. package/dist/harness/memory/cognition-decay.d.ts +36 -0
  158. package/dist/harness/memory/cognition-decay.js +55 -0
  159. package/dist/harness/memory/cognition-gates.d.ts +60 -0
  160. package/dist/harness/memory/cognition-gates.js +191 -0
  161. package/dist/harness/memory/cognition-trigger.d.ts +30 -0
  162. package/dist/harness/memory/cognition-trigger.js +41 -0
  163. package/dist/harness/memory/cognition-types.d.ts +1 -1
  164. package/dist/harness/memory/cognition.d.ts +40 -8
  165. package/dist/harness/memory/cognition.js +432 -79
  166. package/dist/harness/memory/conceptualizer.d.ts +66 -0
  167. package/dist/harness/memory/conceptualizer.js +246 -0
  168. package/dist/harness/memory/index.d.ts +16 -2
  169. package/dist/harness/memory/index.js +11 -1
  170. package/dist/harness/memory/sqlite/agent-db.d.ts +9 -0
  171. package/dist/harness/memory/sqlite/agent-db.js +118 -15
  172. package/dist/harness/memory/sqlite/cognition-store.d.ts +55 -16
  173. package/dist/harness/memory/sqlite/cognition-store.js +591 -144
  174. package/dist/harness/memory/sqlite/embedding.d.ts +5 -2
  175. package/dist/harness/memory/sqlite/embedding.js +109 -16
  176. package/dist/harness/memory/sqlite/keyword-search.d.ts +21 -0
  177. package/dist/harness/memory/sqlite/keyword-search.js +64 -0
  178. package/dist/harness/memory/sqlite/wisdom-store.d.ts +33 -14
  179. package/dist/harness/memory/sqlite/wisdom-store.js +257 -44
  180. package/dist/harness/memory/types.d.ts +331 -16
  181. package/dist/harness/memory/types.js +49 -0
  182. package/dist/harness/memory/wisdom-formation.d.ts +101 -0
  183. package/dist/harness/memory/wisdom-formation.js +304 -0
  184. package/dist/harness/memory/wisdom-gates.d.ts +50 -0
  185. package/dist/harness/memory/wisdom-gates.js +204 -0
  186. package/dist/harness/memory/wisdom-policy.d.ts +107 -0
  187. package/dist/harness/memory/wisdom-policy.js +220 -0
  188. package/dist/harness/memory/wisdom-types.d.ts +3 -2
  189. package/dist/harness/memory/wisdom-types.js +2 -2
  190. package/dist/harness/memory/wisdom.d.ts +27 -0
  191. package/dist/harness/memory/wisdom.js +181 -0
  192. package/dist/harness/run/agent/agent.d.ts +9 -0
  193. package/dist/harness/run/agent/agent.js +19 -0
  194. package/dist/harness/run/reliability/run-agent.js +6 -2
  195. package/dist/harness/run/runner.js +2 -1
  196. package/dist/harness/session/attachments/service.d.ts +1 -1
  197. package/dist/harness/session/attachments/service.js +1 -1
  198. package/dist/harness/session/index.d.ts +1 -0
  199. package/dist/harness/session/index.js +1 -0
  200. package/dist/harness/session/title.d.ts +86 -0
  201. package/dist/harness/session/title.js +268 -0
  202. package/dist/harness/shared/events/agent-event-map.d.ts +8 -0
  203. package/dist/harness/shared/events/agent-event-map.js +1 -0
  204. package/dist/index.d.ts +7 -3
  205. package/dist/index.js +3 -1
  206. package/dist/subsystems/cognition-steward/conceptualize/SUBSYSTEM.md +43 -0
  207. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +50 -0
  208. package/dist/subsystems/cognition-steward/conceptualize/handler.d.ts +9 -0
  209. package/dist/subsystems/cognition-steward/conceptualize/handler.js +125 -0
  210. package/dist/subsystems/cognition-steward/consolidate/SUBSYSTEM.md +6 -0
  211. package/dist/subsystems/cognition-steward/consolidate/config.yaml +54 -0
  212. package/dist/subsystems/cognition-steward/consolidate/handler.d.ts +12 -0
  213. package/dist/subsystems/cognition-steward/consolidate/handler.js +93 -0
  214. package/dist/subsystems/wisdom-steward/evaluate/config.yaml +50 -0
  215. package/dist/subsystems/wisdom-steward/evaluate/handler.d.ts +18 -0
  216. package/dist/subsystems/wisdom-steward/evaluate/handler.js +91 -0
  217. package/dist/subsystems/wisdom-steward/formation/SUBSYSTEM.md +42 -0
  218. package/dist/subsystems/wisdom-steward/formation/config.yaml +54 -0
  219. package/dist/subsystems/wisdom-steward/formation/handler.d.ts +18 -0
  220. package/dist/subsystems/wisdom-steward/formation/handler.js +212 -0
  221. package/dist/subsystems/wisdom-steward/govern/config.yaml +55 -0
  222. package/dist/subsystems/wisdom-steward/govern/handler.d.ts +17 -0
  223. package/dist/subsystems/wisdom-steward/govern/handler.js +68 -0
  224. package/dist/worker-path.d.ts +8 -0
  225. package/dist/worker-path.js +15 -0
  226. package/package.json +2 -2
@@ -17,9 +17,12 @@ export interface EmbeddingProvider {
17
17
  readonly name: string;
18
18
  /** 向量维度 */
19
19
  readonly dimensions: number;
20
- /** 生成 embedding */
20
+ /** 生成 embedding;输入超模型上下文时由实现做截断回退 */
21
21
  embed(text: string): Promise<number[]>;
22
- /** 批量生成 embedding */
22
+ /**
23
+ * 批量生成 embedding。
24
+ * 与入参等长;失败条目为空数组,由调用方按条续试(禁止静默丢条)。
25
+ */
23
26
  embedBatch(texts: string[]): Promise<number[][]>;
24
27
  }
25
28
  /** HTTP 请求/响应字段映射(type=http 或覆盖 openai/ollama 默认) */
@@ -37,6 +37,25 @@ function asEmbedding(value) {
37
37
  // float32 buffer 等情况暂不支持
38
38
  return null;
39
39
  }
40
+ /** 服务端提示输入超过模型上下文(Ollama/TEI/OpenAI 措辞不一) */
41
+ function isContextLengthError(err) {
42
+ const msg = err instanceof Error ? err.message : String(err);
43
+ return /context length|input length|prompt is too long|maximum context|too many tokens|exceeds the (max|context)|max_?tokens|token limit/i.test(msg);
44
+ }
45
+ /**
46
+ * 为 embedding 缩短输入:保头 72% + 尾 28%(表头/结论都在),中间用省略号衔接。
47
+ * 全文仍留在检索侧;这里只影响向量语义覆盖面。
48
+ */
49
+ function shrinkEmbedText(text, maxChars) {
50
+ const t = text.trim();
51
+ if (t.length <= maxChars)
52
+ return t;
53
+ const marker = '\n…\n';
54
+ const budget = Math.max(48, maxChars - marker.length);
55
+ const head = Math.ceil(budget * 0.72);
56
+ const tail = Math.floor(budget * 0.28);
57
+ return `${t.slice(0, head)}${marker}${t.slice(t.length - tail)}`;
58
+ }
40
59
  function defaultPath(type, custom) {
41
60
  if (custom)
42
61
  return custom;
@@ -181,8 +200,8 @@ class HttpEmbeddingProvider {
181
200
  continue;
182
201
  }
183
202
  const vec = asEmbedding(getByPath(item, mapping.itemEmbeddingPath));
184
- if (vec)
185
- out.push(vec);
203
+ // 保留空槽对齐下标;调用方按条重试,禁止静默丢条
204
+ out.push(vec ?? []);
186
205
  }
187
206
  }
188
207
  if (out.length === 0) {
@@ -193,33 +212,87 @@ class HttpEmbeddingProvider {
193
212
  // 协议异常时以实际返回条数为准,由调用方决定是否串行重试
194
213
  return out;
195
214
  }
196
- async embed(text) {
215
+ /** 单次请求;不做截断回退 */
216
+ async embedRaw(text) {
197
217
  const res = await fetch(this.opts.url, {
198
218
  method: 'POST',
199
219
  headers: this.buildHeaders(),
200
220
  body: JSON.stringify(this.buildBody(text)),
201
221
  signal: AbortSignal.timeout(this.opts.timeoutMs),
202
222
  });
223
+ const rawText = await res.text().catch(() => '');
224
+ let data = {};
225
+ if (rawText) {
226
+ try {
227
+ data = JSON.parse(rawText);
228
+ }
229
+ catch {
230
+ data = {};
231
+ }
232
+ }
233
+ else if (typeof res.json === 'function') {
234
+ // 测试桩可能只实现 json();真响应 body 空则维持 {}
235
+ data = await res.json().catch(() => ({}));
236
+ }
203
237
  if (!res.ok) {
204
- const detail = await res.text().catch(() => '');
205
- throw new Error(`Embedding request failed: ${res.status} ${res.statusText} ${detail.slice(0, 200)}`);
238
+ const errText = typeof data?.error === 'string'
239
+ ? data.error
240
+ : rawText.slice(0, 200);
241
+ throw new Error(`Embedding request failed: ${res.status} ${res.statusText} ${errText}`.slice(0, 400));
242
+ }
243
+ const apiErr = data?.error;
244
+ if (typeof apiErr === 'string' && apiErr) {
245
+ throw new Error(`Embedding request failed: ${apiErr}`);
206
246
  }
207
- const data = (await res.json());
208
247
  const vec = this.extractOne(data);
209
248
  if (!vec || vec.length === 0) {
210
249
  throw new Error(`Embedding response missing vector at path "${this.opts.mapping.embeddingsPath}"`);
211
250
  }
212
251
  return vec;
213
252
  }
253
+ async embed(text) {
254
+ try {
255
+ return await this.embedRaw(text);
256
+ }
257
+ catch (err) {
258
+ // 模型上下文按 token 计:同字数中文密度不同,有的 2400 字能进有的不能
259
+ if (!isContextLengthError(err))
260
+ throw err;
261
+ let size = Math.min(text.trim().length, 1600);
262
+ while (size >= 200) {
263
+ try {
264
+ return await this.embedRaw(shrinkEmbedText(text, size));
265
+ }
266
+ catch (e2) {
267
+ if (!isContextLengthError(e2))
268
+ throw e2;
269
+ size = Math.floor(size * 0.7);
270
+ }
271
+ }
272
+ throw err;
273
+ }
274
+ }
214
275
  async embedBatch(texts) {
215
276
  if (texts.length === 0)
216
277
  return [];
217
278
  if (!this.opts.supportsBatch) {
218
- // 串行调用 embed,避免并发压垮单条接口
279
+ // 串行调用 embed(含截断回退);单条失败不拖垮同批其它条
219
280
  const out = [];
281
+ let lastErr;
282
+ let ok = 0;
220
283
  for (const t of texts) {
221
- out.push(await this.embed(t));
284
+ try {
285
+ const vec = await this.embed(t);
286
+ out.push(vec);
287
+ ok += 1;
288
+ }
289
+ catch (e) {
290
+ lastErr = e;
291
+ out.push([]);
292
+ }
222
293
  }
294
+ if (ok === 0 && lastErr)
295
+ throw lastErr;
223
296
  return out;
224
297
  }
225
298
  // 服务端批次上限(如百炼 qwen3.7-text-embedding = 20);超出切片
@@ -248,21 +321,41 @@ class HttpEmbeddingProvider {
248
321
  }
249
322
  const data = (await res.json());
250
323
  const many = this.extractMany(data);
251
- if (many.length >= 1) {
252
- if (many.length === texts.length)
253
- return many;
254
- if (texts.length > 1)
255
- return this.embedSerial(texts);
256
- return many.slice(0, 1);
324
+ if (many.length === texts.length) {
325
+ // 对齐后仍有空槽:按条补齐(embed 内含上下文截断回退);单条失败留空槽给上层续试
326
+ for (let i = 0; i < many.length; i++) {
327
+ if (many[i]?.length)
328
+ continue;
329
+ try {
330
+ many[i] = await this.embed(texts[i]);
331
+ }
332
+ catch {
333
+ many[i] = [];
334
+ }
335
+ }
336
+ return many;
257
337
  }
258
- return this.embedSerial(texts);
338
+ if (texts.length > 1)
339
+ return this.embedSerial(texts);
340
+ return many.slice(0, 1);
259
341
  }
260
342
  /** 串行单条(批量失败回退;避免并发风暴触发限流) */
261
343
  async embedSerial(texts) {
262
344
  const out = [];
345
+ let lastErr;
346
+ let ok = 0;
263
347
  for (const t of texts) {
264
- out.push(await this.embed(t));
348
+ try {
349
+ out.push(await this.embed(t));
350
+ ok += 1;
351
+ }
352
+ catch (e) {
353
+ lastErr = e;
354
+ out.push([]);
355
+ }
265
356
  }
357
+ if (ok === 0 && lastErr)
358
+ throw lastErr;
266
359
  return out;
267
360
  }
268
361
  }
@@ -34,6 +34,27 @@ export interface KeywordTokens {
34
34
  * @param text - 原始查询
35
35
  */
36
36
  export declare function tokenizeKeywordDetail(text: string): KeywordTokens;
37
+ /**
38
+ * 查询是否有足够语义信号做自动召回(grounding)。
39
+ *
40
+ * - ≥2 个 strong 词 → 有
41
+ * - 单个 CJK 整段长度 ≥3(如「技术栈选择」)→ 视为多概念
42
+ * - 否则(「继续」「好的」「ok」)→ 无
43
+ *
44
+ * @param tokens - {@link tokenizeKeywordDetail} 结果
45
+ */
46
+ export declare function hasEnoughQuerySignal(tokens: KeywordTokens | string[]): boolean;
47
+ /**
48
+ * 绝对关键词相关度(0–1):查询 token 被正文/路径覆盖的加权比例。
49
+ *
50
+ * 与结果集无关,供 inject/hint 地板使用;**不要**再做组内 min-max。
51
+ * strong 权重 1,weak(CJK 滑窗二元组)0.5;命中字段:content 1.0 / tags 0.6 / 其它 0.3。
52
+ *
53
+ * @param fields - 可检索字段
54
+ * @param tokens - 查询分词
55
+ * @returns 0–1;无 token 时 0
56
+ */
57
+ export declare function scoreKeywordCoverage(fields: KeywordFields, tokens: string[] | KeywordTokens): number;
37
58
  /**
38
59
  * 单条记忆的关键词命中得分。
39
60
  *
@@ -64,6 +64,70 @@ export function tokenizeKeywordDetail(text) {
64
64
  const all = [...new Set([...strong, ...weak])].filter((t) => t.length >= 2);
65
65
  return { all, strong: [...strong].filter((t) => t.length >= 2), weak: [...weak] };
66
66
  }
67
+ /**
68
+ * 查询是否有足够语义信号做自动召回(grounding)。
69
+ *
70
+ * - ≥2 个 strong 词 → 有
71
+ * - 单个 CJK 整段长度 ≥3(如「技术栈选择」)→ 视为多概念
72
+ * - 否则(「继续」「好的」「ok」)→ 无
73
+ *
74
+ * @param tokens - {@link tokenizeKeywordDetail} 结果
75
+ */
76
+ export function hasEnoughQuerySignal(tokens) {
77
+ const strong = Array.isArray(tokens) ? tokens : tokens.strong;
78
+ const usable = strong.filter((t) => t.length >= 2);
79
+ if (usable.length >= 2)
80
+ return true;
81
+ return usable.some((t) => t.length >= 3 && isCjk(t[0] ?? ''));
82
+ }
83
+ /**
84
+ * 绝对关键词相关度(0–1):查询 token 被正文/路径覆盖的加权比例。
85
+ *
86
+ * 与结果集无关,供 inject/hint 地板使用;**不要**再做组内 min-max。
87
+ * strong 权重 1,weak(CJK 滑窗二元组)0.5;命中字段:content 1.0 / tags 0.6 / 其它 0.3。
88
+ *
89
+ * @param fields - 可检索字段
90
+ * @param tokens - 查询分词
91
+ * @returns 0–1;无 token 时 0
92
+ */
93
+ export function scoreKeywordCoverage(fields, tokens) {
94
+ const detail = Array.isArray(tokens)
95
+ ? {
96
+ all: tokens,
97
+ strong: tokens,
98
+ weak: [],
99
+ }
100
+ : tokens;
101
+ const list = detail.all;
102
+ if (list.length === 0)
103
+ return 0;
104
+ const weakSet = new Set(detail.weak);
105
+ const content = (fields.content ?? '').toLowerCase();
106
+ const futureUse = (fields.futureUse ?? '').toLowerCase();
107
+ const tags = asText(fields.tags).toLowerCase();
108
+ const anchors = asText(fields.anchors).toLowerCase();
109
+ const evidence = (fields.evidence ?? '').toLowerCase();
110
+ let totalW = 0;
111
+ let hitW = 0;
112
+ for (const token of list) {
113
+ if (!token)
114
+ continue;
115
+ const tw = weakSet.has(token) ? 0.5 : 1;
116
+ totalW += tw;
117
+ if (content.includes(token)) {
118
+ hitW += tw * 1.0;
119
+ }
120
+ else if (tags.includes(token)) {
121
+ hitW += tw * 0.6;
122
+ }
123
+ else if (futureUse.includes(token) || anchors.includes(token) || evidence.includes(token)) {
124
+ hitW += tw * 0.3;
125
+ }
126
+ }
127
+ if (totalW === 0)
128
+ return 0;
129
+ return Math.min(1, hitW / totalW);
130
+ }
67
131
  function asText(v) {
68
132
  if (v == null)
69
133
  return '';
@@ -1,23 +1,42 @@
1
1
  /**
2
- * SqliteWisdomStore — SQLite 智慧存储
2
+ * SqliteWisdomStore — 判断范式(maxim)SQLite 存储
3
+ *
4
+ * 写入只经 admit(门控在 wisdom-gates)。无旧 content 形态兼容。
3
5
  *
4
6
  * @module
5
7
  */
6
- import type { WisdomStore, WisdomEntry } from '../wisdom-types.js';
8
+ import type { AdmitWisdomInput, AdmitWisdomResult, WisdomEntry, WisdomInjectPick, WisdomInjectQuery, WisdomOutcomeEvent, WisdomRetireReason, WisdomStats, WisdomStore } from '../types.js';
7
9
  import { AgentDatabase } from './agent-db.js';
10
+ export interface SqliteWisdomStoreOptions {
11
+ /** admit 硬顶(存活面);默认 80 */
12
+ hardCap?: number;
13
+ }
8
14
  export declare class SqliteWisdomStore implements WisdomStore {
15
+ readonly name = "sqlite-wisdom";
9
16
  private db;
10
- constructor(db: AgentDatabase);
11
- store(entry: Omit<WisdomEntry, 'id' | 'createdAt'>): Promise<string>;
12
- getAll(): Promise<WisdomEntry[]>;
13
- delete(id: string): Promise<void>;
14
- /**
15
- * 获取数量
16
- */
17
- count(): number;
18
- /**
19
- * 淘汰最低优先级的 wisdom(超过上限时调用)
20
- */
21
- evict(maxCount: number): Promise<number>;
17
+ private readonly hardCapLimit;
18
+ constructor(db: AgentDatabase, options?: SqliteWisdomStoreOptions);
19
+ admit(input: AdmitWisdomInput, options?: {
20
+ allowedMemoryIds?: ReadonlySet<string>;
21
+ }): Promise<AdmitWisdomResult>;
22
+ get(id: string): Promise<WisdomEntry | null>;
23
+ selectForInjection(query: WisdomInjectQuery): Promise<WisdomInjectPick[]>;
24
+ listForGovern(filter?: {
25
+ includeRetired?: boolean;
26
+ }): Promise<WisdomEntry[]>;
27
+ update(id: string, patch: Partial<WisdomEntry>): Promise<void>;
28
+ softRetire(id: string, meta: {
29
+ by: string;
30
+ reason: WisdomRetireReason | string;
31
+ }): Promise<void>;
32
+ recordOutcomes(events: WisdomOutcomeEvent[]): Promise<void>;
33
+ touchApplied(ids: string[]): Promise<void>;
34
+ stats(): Promise<WisdomStats>;
35
+ /** 存活面计数(candidate/trial/active/strengthened/contested) */
36
+ countLive(): number;
37
+ private hardCap;
38
+ private livingCount;
39
+ private listMinimal;
40
+ private getSync;
22
41
  private rowToEntry;
23
42
  }
@@ -1,64 +1,277 @@
1
1
  /**
2
- * SqliteWisdomStore — SQLite 智慧存储
2
+ * SqliteWisdomStore — 判断范式(maxim)SQLite 存储
3
+ *
4
+ * 写入只经 admit(门控在 wisdom-gates)。无旧 content 形态兼容。
3
5
  *
4
6
  * @module
5
7
  */
8
+ import { WISDOM_STATUSES } from '../types.js';
9
+ import { evaluateWisdomGate, resolveInitialWisdomStatus, } from '../wisdom-gates.js';
10
+ import { foldOutcomeEvents, planConfidenceUpdate } from '../wisdom-policy.js';
11
+ import { pickForInjection } from '../wisdom-formation.js';
6
12
  import { AgentDatabase } from './agent-db.js';
7
13
  export class SqliteWisdomStore {
14
+ name = 'sqlite-wisdom';
8
15
  db;
9
- constructor(db) {
16
+ hardCapLimit;
17
+ constructor(db, options) {
10
18
  this.db = db;
19
+ this.hardCapLimit = options?.hardCap ?? 80;
11
20
  }
12
- async store(entry) {
21
+ async admit(input, options) {
22
+ const existing = this.listMinimal();
23
+ const gate = evaluateWisdomGate(input, {
24
+ existing,
25
+ allowedMemoryIds: options?.allowedMemoryIds,
26
+ capacityAdmitStop: this.livingCount() >= this.hardCap(),
27
+ });
28
+ if (!gate.ok) {
29
+ return { action: 'rejected', reason: gate.reason, message: gate.message };
30
+ }
31
+ const now = Date.now();
32
+ const status = resolveInitialWisdomStatus(input);
13
33
  const id = AgentDatabase.generateId('wis');
34
+ if (input.supersedesId) {
35
+ const prev = this.getSync(input.supersedesId);
36
+ if (!prev) {
37
+ return {
38
+ action: 'rejected',
39
+ reason: 'supersedes_target_missing',
40
+ message: `supersedesId=${input.supersedesId}`,
41
+ };
42
+ }
43
+ this.db.raw
44
+ .prepare(`UPDATE wisdom SET status = 'superseded', superseded_by = ?, updated_at = ? WHERE id = ?`)
45
+ .run(id, now, prev.id);
46
+ }
47
+ this.db.raw
48
+ .prepare(`INSERT INTO wisdom (
49
+ id, statement, rationale, scenario_json, effect_json, status, confidence, priority,
50
+ derived_from_json, exceptions_json, counterevidence_json, outcomes_json,
51
+ origin, kind, superseded_by, created_at, updated_at
52
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
53
+ .run(id, input.statement.trim(), input.rationale?.trim() || null, JSON.stringify(input.scenario), JSON.stringify(input.effect), status, clamp01(input.confidence ?? defaultConfidence(status, input.origin ?? 'distilled')), input.priority ?? defaultPriority(status, input.origin ?? 'distilled'), JSON.stringify(input.derivedFrom), JSON.stringify(input.exceptions ?? []), JSON.stringify([]), JSON.stringify(emptyOutcomes()), input.origin ?? 'distilled', input.kind, null, now, now);
54
+ return {
55
+ action: input.supersedesId ? 'superseded' : 'created',
56
+ id,
57
+ };
58
+ }
59
+ async get(id) {
60
+ const row = this.db.raw.prepare(`SELECT * FROM wisdom WHERE id = ?`).get(id);
61
+ return row ? this.rowToEntry(row) : null;
62
+ }
63
+ async selectForInjection(query) {
64
+ const rows = this.db.raw
65
+ .prepare(`SELECT * FROM wisdom WHERE status IN ('trial','active','strengthened') ORDER BY priority DESC, confidence DESC`)
66
+ .all();
67
+ const entries = rows.map((r) => this.rowToEntry(r));
68
+ return pickForInjection(entries, query.text ?? '', {
69
+ coreMaxItems: query.coreMaxItems,
70
+ scenarioMaxItems: query.scenarioMaxItems,
71
+ includeTrial: query.includeTrial,
72
+ });
73
+ }
74
+ async listForGovern(filter) {
75
+ const includeRetired = filter?.includeRetired ?? false;
76
+ const rows = (includeRetired
77
+ ? this.db.raw.prepare(`SELECT * FROM wisdom ORDER BY updated_at DESC`).all()
78
+ : this.db.raw
79
+ .prepare(`SELECT * FROM wisdom WHERE status NOT IN ('retired') ORDER BY updated_at DESC`)
80
+ .all());
81
+ return rows.map((r) => this.rowToEntry(r));
82
+ }
83
+ async update(id, patch) {
84
+ const current = this.getSync(id);
85
+ if (!current)
86
+ throw new Error(`wisdom_update_not_found: ${id}`);
87
+ const merged = {
88
+ ...current,
89
+ ...patch,
90
+ id: current.id,
91
+ createdAt: current.createdAt,
92
+ updatedAt: Date.now(),
93
+ outcomes: { ...current.outcomes, ...(patch.outcomes ?? {}) },
94
+ };
95
+ this.db.raw
96
+ .prepare(`UPDATE wisdom SET
97
+ statement = ?, rationale = ?, scenario_json = ?, effect_json = ?,
98
+ status = ?, confidence = ?, priority = ?, derived_from_json = ?,
99
+ exceptions_json = ?, counterevidence_json = ?, outcomes_json = ?,
100
+ origin = ?, kind = ?, superseded_by = ?, updated_at = ?
101
+ WHERE id = ?`)
102
+ .run(merged.statement, merged.rationale ?? null, JSON.stringify(merged.scenario), JSON.stringify(merged.effect), merged.status, clamp01(merged.confidence), merged.priority, JSON.stringify(merged.derivedFrom), JSON.stringify(merged.exceptions ?? []), JSON.stringify(merged.counterevidence ?? []), JSON.stringify(merged.outcomes), merged.origin, merged.kind, merged.supersededBy ?? null, merged.updatedAt, id);
103
+ }
104
+ async softRetire(id, meta) {
105
+ const current = this.getSync(id);
106
+ if (!current)
107
+ return;
108
+ if (current.status === 'superseded')
109
+ return;
110
+ await this.update(id, {
111
+ status: 'retired',
112
+ exceptions: [...(current.exceptions ?? []), `retired:${meta.reason}:${meta.by}`],
113
+ });
114
+ }
115
+ async recordOutcomes(events) {
116
+ if (events.length === 0)
117
+ return;
118
+ const byId = new Map();
119
+ for (const e of events) {
120
+ const list = byId.get(e.wisdomId) ?? [];
121
+ list.push(e);
122
+ byId.set(e.wisdomId, list);
123
+ }
124
+ for (const [id, evs] of byId) {
125
+ const current = this.getSync(id);
126
+ if (!current)
127
+ continue;
128
+ const folded = foldOutcomeEvents(current, evs);
129
+ let next = { ...current, ...folded, updatedAt: Date.now() };
130
+ const plan = planConfidenceUpdate(next);
131
+ if (plan) {
132
+ next = {
133
+ ...next,
134
+ confidence: plan.confidence,
135
+ status: plan.status,
136
+ outcomes: {
137
+ ...next.outcomes,
138
+ evalAssisted: plan.evalAssisted,
139
+ evalContested: plan.evalContested,
140
+ },
141
+ };
142
+ }
143
+ const counter = evs.filter((e) => e.signal === 'contested' && (e.ref || e.note));
144
+ if (counter.length) {
145
+ const ce = [...(next.counterevidence ?? [])];
146
+ for (const c of counter) {
147
+ ce.push({
148
+ ref: c.ref ?? c.wisdomId,
149
+ note: c.note ?? 'contested',
150
+ at: c.at ?? Date.now(),
151
+ weight: 1,
152
+ });
153
+ }
154
+ next = { ...next, counterevidence: ce };
155
+ }
156
+ await this.update(id, next);
157
+ }
158
+ }
159
+ async touchApplied(ids) {
160
+ if (ids.length === 0)
161
+ return;
14
162
  const now = Date.now();
15
- this.db.raw.prepare(`
16
- INSERT INTO wisdom (id, content, derived_from, priority, confidence, applicable_scenarios, status, created_at, updated_at)
17
- VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?)
18
- `).run(id, entry.content, JSON.stringify(entry.derivedFrom), entry.priority, entry.confidence ?? 0.5, JSON.stringify(entry.applicableScenarios ?? []), now, now);
19
- return id;
20
- }
21
- async getAll() {
22
- const rows = this.db.raw.prepare("SELECT * FROM wisdom WHERE status = 'active' ORDER BY priority DESC").all();
23
- return rows.map(r => this.rowToEntry(r));
24
- }
25
- async delete(id) {
26
- this.db.raw.prepare("UPDATE wisdom SET status = 'retired' WHERE id = ?").run(id);
27
- }
28
- /**
29
- * 获取数量
30
- */
31
- count() {
32
- const row = this.db.raw.prepare("SELECT COUNT(*) as count FROM wisdom WHERE status = 'active'").get();
33
- return row.count;
34
- }
35
- /**
36
- * 淘汰最低优先级的 wisdom(超过上限时调用)
37
- */
38
- async evict(maxCount) {
39
- const current = this.count();
40
- if (current <= maxCount)
41
- return 0;
42
- const toEvict = current - maxCount;
43
- this.db.raw.prepare(`
44
- UPDATE wisdom SET status = 'retired'
45
- WHERE id IN (
46
- SELECT id FROM wisdom
47
- WHERE status = 'active'
48
- ORDER BY priority ASC, confidence ASC
49
- LIMIT ?
50
- )
51
- `).run(toEvict);
52
- return toEvict;
163
+ for (const id of ids) {
164
+ const cur = this.getSync(id);
165
+ if (!cur)
166
+ continue;
167
+ const outcomes = {
168
+ ...cur.outcomes,
169
+ applied: cur.outcomes.applied + 1,
170
+ lastAppliedAt: now,
171
+ };
172
+ this.db.raw
173
+ .prepare(`UPDATE wisdom SET outcomes_json = ?, updated_at = ? WHERE id = ?`)
174
+ .run(JSON.stringify(outcomes), now, id);
175
+ }
176
+ }
177
+ async stats() {
178
+ const rows = this.db.raw.prepare(`SELECT * FROM wisdom`).all();
179
+ const byStatus = Object.fromEntries(WISDOM_STATUSES.map((s) => [s, 0]));
180
+ let confSum = 0;
181
+ let prioSum = 0;
182
+ let applied = 0;
183
+ let contested = 0;
184
+ for (const r of rows) {
185
+ const st = r.status ?? 'active';
186
+ byStatus[st] = (byStatus[st] ?? 0) + 1;
187
+ confSum += r.confidence;
188
+ prioSum += r.priority;
189
+ const o = safeParse(r.outcomes_json, emptyOutcomes());
190
+ applied += o.applied;
191
+ contested += o.contested;
192
+ }
193
+ const n = rows.length || 1;
194
+ return {
195
+ total: rows.length,
196
+ byStatus,
197
+ avgConfidence: confSum / n,
198
+ avgPriority: prioSum / n,
199
+ totalApplied: applied,
200
+ totalContested: contested,
201
+ };
202
+ }
203
+ /** 存活面计数(candidate/trial/active/strengthened/contested) */
204
+ countLive() {
205
+ return this.livingCount();
206
+ }
207
+ hardCap() {
208
+ return this.hardCapLimit;
209
+ }
210
+ livingCount() {
211
+ const row = this.db.raw
212
+ .prepare(`SELECT COUNT(*) as c FROM wisdom WHERE status IN ('candidate','trial','active','strengthened','contested')`)
213
+ .get();
214
+ return row.c;
215
+ }
216
+ listMinimal() {
217
+ const rows = this.db.raw
218
+ .prepare(`SELECT id, statement, status, kind FROM wisdom WHERE status NOT IN ('retired')`)
219
+ .all();
220
+ return rows;
221
+ }
222
+ getSync(id) {
223
+ const row = this.db.raw.prepare(`SELECT * FROM wisdom WHERE id = ?`).get(id);
224
+ return row ? this.rowToEntry(row) : null;
53
225
  }
54
226
  rowToEntry(row) {
55
227
  return {
56
228
  id: row.id,
57
- content: row.content,
58
- derivedFrom: JSON.parse(row.derived_from),
229
+ statement: row.statement,
230
+ rationale: row.rationale ?? undefined,
231
+ scenario: safeParse(row.scenario_json, { problemTypes: [] }),
232
+ effect: safeParse(row.effect_json, {}),
233
+ status: (WISDOM_STATUSES.includes(row.status)
234
+ ? row.status
235
+ : 'active'),
236
+ confidence: row.confidence,
59
237
  priority: row.priority,
238
+ derivedFrom: safeParse(row.derived_from_json, { memoryIds: [] }),
239
+ exceptions: safeParse(row.exceptions_json, []),
240
+ counterevidence: safeParse(row.counterevidence_json, []),
241
+ outcomes: safeParse(row.outcomes_json, emptyOutcomes()),
242
+ origin: row.origin,
243
+ kind: row.kind,
244
+ supersededBy: row.superseded_by ?? undefined,
60
245
  createdAt: row.created_at,
61
- applicableScenarios: JSON.parse(row.applicable_scenarios),
246
+ updatedAt: row.updated_at,
62
247
  };
63
248
  }
64
249
  }
250
+ function emptyOutcomes() {
251
+ return { applied: 0, cited: 0, assisted: 0, contested: 0, evalAssisted: 0, evalContested: 0 };
252
+ }
253
+ function clamp01(n) {
254
+ return Math.min(1, Math.max(0, n));
255
+ }
256
+ function defaultConfidence(status, origin) {
257
+ if (origin === 'factory' || status === 'active')
258
+ return 0.7;
259
+ return 0.5;
260
+ }
261
+ function defaultPriority(status, origin) {
262
+ if (origin === 'factory')
263
+ return 80;
264
+ if (status === 'active')
265
+ return 50;
266
+ return 30;
267
+ }
268
+ function safeParse(raw, fallback) {
269
+ if (!raw)
270
+ return fallback;
271
+ try {
272
+ return JSON.parse(raw);
273
+ }
274
+ catch {
275
+ return fallback;
276
+ }
277
+ }