@botbotgo/agent-harness 0.0.475 → 0.0.476

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 (227) hide show
  1. package/README.md +3 -1234
  2. package/README.zh.md +3 -1191
  3. package/dist/acp.js +1 -1
  4. package/dist/api.js +1 -404
  5. package/dist/benchmark/checkpoint-resume-cost-benchmark.js +1 -55
  6. package/dist/benchmark/deepagent-local-model-benchmark.js +2 -35
  7. package/dist/benchmark/upstream-runtime-ab-benchmark.js +1 -179
  8. package/dist/cli/chat-interactive.js +25 -244
  9. package/dist/cli/chat-rendering.js +6 -100
  10. package/dist/cli/chat-stream.js +23 -512
  11. package/dist/cli/chat-ui.js +21 -199
  12. package/dist/cli/chat-workspace.js +2 -210
  13. package/dist/cli/main.js +21 -428
  14. package/dist/cli/managed-service-commands.js +9 -63
  15. package/dist/cli/managed-service.js +2 -137
  16. package/dist/cli/options-init-chat.js +1 -108
  17. package/dist/cli/options-runtime.js +1 -158
  18. package/dist/cli/options-serve.js +1 -282
  19. package/dist/cli/options.js +2 -19
  20. package/dist/cli/process-guards.js +1 -139
  21. package/dist/cli/request-tree.js +7 -296
  22. package/dist/cli/runtime-commands.js +12 -258
  23. package/dist/cli/runtime-output.js +16 -155
  24. package/dist/cli/server-commands.js +16 -270
  25. package/dist/cli/workspace.js +1 -67
  26. package/dist/cli.js +1 -7
  27. package/dist/client/acp.js +1 -1
  28. package/dist/client/in-process.js +1 -67
  29. package/dist/client/index.js +1 -2
  30. package/dist/client/types.js +0 -1
  31. package/dist/client.js +1 -1
  32. package/dist/contracts/core.js +1 -1
  33. package/dist/contracts/runtime-evaluation.js +0 -1
  34. package/dist/contracts/runtime-memory.js +0 -1
  35. package/dist/contracts/runtime-observability.js +0 -1
  36. package/dist/contracts/runtime-requests.js +0 -1
  37. package/dist/contracts/runtime-scheduling.js +0 -1
  38. package/dist/contracts/runtime.js +1 -27
  39. package/dist/contracts/types.js +1 -3
  40. package/dist/contracts/workspace.js +0 -1
  41. package/dist/flow/build-flow-graph.js +1 -50
  42. package/dist/flow/export-mermaid.js +2 -464
  43. package/dist/flow/export-sequence-mermaid.js +2 -325
  44. package/dist/flow/flow-graph-normalization.js +1 -214
  45. package/dist/flow/flow-graph-runtime.js +1 -107
  46. package/dist/flow/flow-graph-upstream.js +1 -494
  47. package/dist/flow/index.js +1 -3
  48. package/dist/flow/types.js +0 -1
  49. package/dist/index.js +1 -5
  50. package/dist/init-project.js +1 -1
  51. package/dist/knowledge/config.js +1 -32
  52. package/dist/knowledge/contracts.js +0 -1
  53. package/dist/knowledge/index.js +1 -2
  54. package/dist/knowledge/module.js +12 -909
  55. package/dist/knowledge/procedural/config.js +1 -125
  56. package/dist/knowledge/procedural/index.js +1 -2
  57. package/dist/knowledge/procedural/manager.js +9 -345
  58. package/dist/mcp.js +1 -2
  59. package/dist/package-version.d.ts +1 -1
  60. package/dist/package-version.js +1 -2
  61. package/dist/persistence/file-store.js +3 -758
  62. package/dist/persistence/sqlite-request-context-store.js +5 -54
  63. package/dist/persistence/sqlite-request-queue-store.js +10 -108
  64. package/dist/persistence/sqlite-runtime.js +1 -86
  65. package/dist/persistence/sqlite-store.js +62 -810
  66. package/dist/persistence/types.js +0 -1
  67. package/dist/projections/presentation.js +37 -206
  68. package/dist/projections/request-events.js +2 -502
  69. package/dist/projections/upstream-events.js +1 -201
  70. package/dist/protocol/a2a/http-discovery.js +1 -178
  71. package/dist/protocol/a2a/http-rpc.js +6 -622
  72. package/dist/protocol/a2a/http.js +1 -138
  73. package/dist/protocol/a2a/task-state.js +3 -317
  74. package/dist/protocol/acp/client.js +8 -294
  75. package/dist/protocol/acp/harness-client.js +1 -218
  76. package/dist/protocol/acp/http.js +5 -130
  77. package/dist/protocol/acp/server.js +1 -310
  78. package/dist/protocol/acp/stdio.js +2 -69
  79. package/dist/protocol/ag-ui/http.js +3 -378
  80. package/dist/protocol/mcp/server.js +1 -428
  81. package/dist/resource/backend/workspace-scoped-backend.js +1 -319
  82. package/dist/resource/isolation.js +1 -237
  83. package/dist/resource/mcp/tool-support.js +3 -296
  84. package/dist/resource/mcp-tool-support.js +1 -2
  85. package/dist/resource/providers/resource-provider.js +1 -215
  86. package/dist/resource/resource-impl.js +1 -3
  87. package/dist/resource/resource-types.js +0 -1
  88. package/dist/resource/resource.js +1 -1
  89. package/dist/resource/sources.js +1 -247
  90. package/dist/resource/tools/function-tool-resolver.js +2 -272
  91. package/dist/runtime/adapter/compat/deepagent-compat.js +1 -29
  92. package/dist/runtime/adapter/compat/openai-compatible.js +1 -55
  93. package/dist/runtime/adapter/direct-builtin-utility.js +2 -90
  94. package/dist/runtime/adapter/flow/execution-context.js +1 -71
  95. package/dist/runtime/adapter/flow/invocation-flow.js +8 -425
  96. package/dist/runtime/adapter/flow/invoke-runtime.js +1 -20
  97. package/dist/runtime/adapter/flow/stream-runtime.js +11 -1395
  98. package/dist/runtime/adapter/invocation-result.js +2 -473
  99. package/dist/runtime/adapter/local-tool-invocation.js +6 -638
  100. package/dist/runtime/adapter/middleware/context-hygiene.js +1 -83
  101. package/dist/runtime/adapter/middleware-assembly.js +5 -477
  102. package/dist/runtime/adapter/model/invocation-request.js +3 -183
  103. package/dist/runtime/adapter/model/message-assembly.js +1 -28
  104. package/dist/runtime/adapter/model/model-providers.js +23 -1115
  105. package/dist/runtime/adapter/model/prompted-json-tool-call-capture.js +1 -40
  106. package/dist/runtime/adapter/model/prompted-json-tool-policy.js +1 -22
  107. package/dist/runtime/adapter/resilience.js +1 -104
  108. package/dist/runtime/adapter/runtime-adapter-support.js +3 -141
  109. package/dist/runtime/adapter/runtime-shell.js +5 -166
  110. package/dist/runtime/adapter/stream-event-projection.js +2 -622
  111. package/dist/runtime/adapter/stream-text-consumption.js +1 -18
  112. package/dist/runtime/adapter/terminal-status.js +2 -67
  113. package/dist/runtime/adapter/tool/builtin-middleware-tools.js +6 -627
  114. package/dist/runtime/adapter/tool/declared-middleware.js +1 -154
  115. package/dist/runtime/adapter/tool/interrupt-policy.js +1 -34
  116. package/dist/runtime/adapter/tool/provider-tool.js +1 -25
  117. package/dist/runtime/adapter/tool/resolved-tool.js +1 -225
  118. package/dist/runtime/adapter/tool/tool-arguments.js +3 -486
  119. package/dist/runtime/adapter/tool/tool-hitl.js +1 -346
  120. package/dist/runtime/adapter/tool/tool-name-mapping.js +1 -128
  121. package/dist/runtime/adapter/tool/tool-output-artifacts.js +2 -88
  122. package/dist/runtime/adapter/tool/tool-replay.js +1 -37
  123. package/dist/runtime/adapter/tool-resolution.js +1 -86
  124. package/dist/runtime/adapter/upstream-configurable-keys.js +1 -2
  125. package/dist/runtime/agent-runtime-adapter.js +60 -2338
  126. package/dist/runtime/agent-runtime-assembly.js +7 -249
  127. package/dist/runtime/env/runtime-env.js +1 -62
  128. package/dist/runtime/harness/background-runtime.js +1 -8
  129. package/dist/runtime/harness/bindings.js +1 -58
  130. package/dist/runtime/harness/events/event-bus.js +1 -16
  131. package/dist/runtime/harness/events/event-sink.js +1 -61
  132. package/dist/runtime/harness/events/events.js +1 -80
  133. package/dist/runtime/harness/events/listener-runtime.js +1 -13
  134. package/dist/runtime/harness/events/runtime-event-operations.js +1 -9
  135. package/dist/runtime/harness/events/streaming.js +1 -100
  136. package/dist/runtime/harness/events/timeline.js +1 -52
  137. package/dist/runtime/harness/public-shapes.js +1 -186
  138. package/dist/runtime/harness/run/artifact-paths.js +1 -15
  139. package/dist/runtime/harness/run/governance.js +1 -295
  140. package/dist/runtime/harness/run/helpers.js +1 -71
  141. package/dist/runtime/harness/run/inspection.js +1 -409
  142. package/dist/runtime/harness/run/operator-overview.js +1 -80
  143. package/dist/runtime/harness/run/queue-diagnostics.js +1 -15
  144. package/dist/runtime/harness/run/recovery.js +1 -162
  145. package/dist/runtime/harness/run/resources.js +1 -60
  146. package/dist/runtime/harness/run/resume.js +1 -56
  147. package/dist/runtime/harness/run/routing.js +1 -48
  148. package/dist/runtime/harness/run/run-lifecycle.js +1 -66
  149. package/dist/runtime/harness/run/run-operations.js +1 -217
  150. package/dist/runtime/harness/run/run-queue.js +1 -43
  151. package/dist/runtime/harness/run/run-slot-acquisition.js +1 -157
  152. package/dist/runtime/harness/run/session-records.js +1 -97
  153. package/dist/runtime/harness/run/start-run.js +1 -120
  154. package/dist/runtime/harness/run/startup-runtime.js +1 -69
  155. package/dist/runtime/harness/run/stream-run.js +8 -1418
  156. package/dist/runtime/harness/run/surface-semantics.js +1 -79
  157. package/dist/runtime/harness/runtime-defaults.js +1 -39
  158. package/dist/runtime/harness/system/boundary-analysis.js +1 -234
  159. package/dist/runtime/harness/system/health-monitor.js +1 -258
  160. package/dist/runtime/harness/system/inventory.js +1 -129
  161. package/dist/runtime/harness/system/mem0-ingestion-sync.js +5 -345
  162. package/dist/runtime/harness/system/policy-engine.js +1 -175
  163. package/dist/runtime/harness/system/runtime-memory-candidates.js +4 -110
  164. package/dist/runtime/harness/system/runtime-memory-consolidation.js +1 -51
  165. package/dist/runtime/harness/system/runtime-memory-manager.js +10 -693
  166. package/dist/runtime/harness/system/runtime-memory-policy.js +1 -155
  167. package/dist/runtime/harness/system/runtime-memory-records.js +11 -577
  168. package/dist/runtime/harness/system/runtime-memory-sync.js +5 -206
  169. package/dist/runtime/harness/system/session-memory-sync.js +3 -113
  170. package/dist/runtime/harness/system/skill-requirements.js +1 -112
  171. package/dist/runtime/harness/system/store.js +9 -365
  172. package/dist/runtime/harness/tool-gateway/index.js +1 -2
  173. package/dist/runtime/harness/tool-gateway/policy.js +1 -45
  174. package/dist/runtime/harness/tool-gateway/validation.js +1 -176
  175. package/dist/runtime/harness/tool-schema.js +1 -3
  176. package/dist/runtime/harness.js +3 -1490
  177. package/dist/runtime/index.js +1 -3
  178. package/dist/runtime/layout/runtime-layout.js +1 -31
  179. package/dist/runtime/maintenance/checkpoint-maintenance.js +2 -178
  180. package/dist/runtime/maintenance/file-checkpoint-saver.js +1 -106
  181. package/dist/runtime/maintenance/runtime-record-maintenance.js +2 -169
  182. package/dist/runtime/maintenance/sqlite-checkpoint-saver.js +4 -289
  183. package/dist/runtime/parsing/output-content.js +10 -550
  184. package/dist/runtime/parsing/output-parsing.js +1 -4
  185. package/dist/runtime/parsing/output-recovery.js +3 -213
  186. package/dist/runtime/parsing/output-tool-args.js +7 -663
  187. package/dist/runtime/parsing/stream-event-parsing.js +3 -362
  188. package/dist/runtime/prompts/runtime-prompts.js +4 -73
  189. package/dist/runtime/scheduling/system-schedule-manager.js +11 -532
  190. package/dist/runtime/skills/skill-metadata.js +1 -197
  191. package/dist/runtime/startup-tracing.js +2 -37
  192. package/dist/runtime/support/compiled-binding.js +1 -290
  193. package/dist/runtime/support/embedding-models.js +1 -118
  194. package/dist/runtime/support/harness-support.js +5 -137
  195. package/dist/runtime/support/llamaindex.js +1 -108
  196. package/dist/runtime/support/runtime-adapter-options.js +1 -29
  197. package/dist/runtime/support/runtime-factories.js +1 -51
  198. package/dist/runtime/support/vector-stores.js +9 -270
  199. package/dist/scaffold/init-project.js +54 -233
  200. package/dist/tooling/extensions.js +1 -311
  201. package/dist/tooling/module-loader.js +1 -55
  202. package/dist/tools.js +1 -176
  203. package/dist/utils/agent-display.js +1 -18
  204. package/dist/utils/bundled-text.js +4 -39
  205. package/dist/utils/compiled-binding.js +1 -33
  206. package/dist/utils/fs.js +2 -45
  207. package/dist/utils/id.js +1 -9
  208. package/dist/utils/message-content.js +1 -30
  209. package/dist/utils/object.js +1 -6
  210. package/dist/workspace/agent-binding-compiler.js +3 -613
  211. package/dist/workspace/compile.js +1 -472
  212. package/dist/workspace/framework-contract-validation.js +2 -322
  213. package/dist/workspace/index.js +1 -1
  214. package/dist/workspace/object-loader-paths.js +1 -71
  215. package/dist/workspace/object-loader-readers.js +1 -187
  216. package/dist/workspace/object-loader.js +1 -754
  217. package/dist/workspace/resource-compilers.js +1 -374
  218. package/dist/workspace/support/agent-capabilities.js +1 -37
  219. package/dist/workspace/support/agent-execution-config.js +1 -44
  220. package/dist/workspace/support/discovery.js +1 -147
  221. package/dist/workspace/support/source-collectors.js +1 -30
  222. package/dist/workspace/support/source-protocols.js +2 -192
  223. package/dist/workspace/support/workspace-ref-utils.js +1 -362
  224. package/dist/workspace/tool-hydration.js +1 -280
  225. package/dist/workspace/validate.js +1 -99
  226. package/dist/workspace/yaml-object-reader.js +1 -285
  227. package/package.json +7 -3
@@ -1,125 +1 @@
1
- function asObject(value) {
2
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
3
- }
4
- function asString(value) {
5
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
6
- }
7
- function asStringArray(value) {
8
- if (!Array.isArray(value)) {
9
- return undefined;
10
- }
11
- const items = value
12
- .filter((item) => typeof item === "string")
13
- .map((item) => item.trim())
14
- .filter((item) => item.length > 0);
15
- return items.length > 0 ? Array.from(new Set(items)) : undefined;
16
- }
17
- function asBoolean(value) {
18
- return typeof value === "boolean" ? value : undefined;
19
- }
20
- function asPositiveInteger(value) {
21
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
22
- }
23
- function asNumber(value) {
24
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
25
- }
26
- function readProceduralMemoryRuntimeSpec(source) {
27
- const typed = asObject(source);
28
- if (!typed) {
29
- return undefined;
30
- }
31
- const kind = typeof typed.kind === "string" ? typed.kind : undefined;
32
- const hasTypedEnvelope = typeof typed.apiVersion === "string" || !!asObject(typed.metadata);
33
- if (kind === "ProceduralMemoryRuntime") {
34
- return asObject(typed.spec);
35
- }
36
- if (hasTypedEnvelope && asObject(typed.spec)) {
37
- return asObject(typed.spec);
38
- }
39
- return typed;
40
- }
41
- export function readProceduralMemoryRuntimeConfig(proceduralMemory) {
42
- const spec = readProceduralMemoryRuntimeSpec(proceduralMemory);
43
- const enabled = spec?.enabled === true;
44
- const provider = asObject(spec?.provider);
45
- const mode = asObject(spec?.mode);
46
- const trigger = asObject(spec?.trigger);
47
- const extraction = asObject(spec?.extraction);
48
- const retrieval = asObject(spec?.retrieval);
49
- const maintenance = asObject(spec?.maintenance);
50
- const onWrite = asObject(maintenance?.onWrite);
51
- const schedule = asObject(maintenance?.schedule);
52
- const idle = asObject(maintenance?.idle);
53
- const limits = asObject(maintenance?.limits);
54
- const decay = asObject(maintenance?.decay);
55
- const pruning = asObject(maintenance?.pruning);
56
- return {
57
- enabled,
58
- provider: provider
59
- ? {
60
- kind: asString(provider.kind) ?? "reme",
61
- options: Object.keys(provider).filter((key) => key !== "kind").length > 0
62
- ? Object.fromEntries(Object.entries(provider).filter(([key]) => key !== "kind"))
63
- : null,
64
- }
65
- : null,
66
- store: asObject(spec?.store) ?? null,
67
- vectorStore: asObject(spec?.vectorStore) ?? null,
68
- embeddingModel: asObject(spec?.embeddingModel) ?? null,
69
- formation: enabled
70
- ? {
71
- backgroundOnly: mode?.backgroundOnly !== false,
72
- background: {
73
- enabled: true,
74
- scopeHints: asStringArray(extraction?.focus) ?? ["coding_patterns", "workflow_patterns", "debugging_lessons"],
75
- maxMessagesPerRequest: asPositiveInteger(extraction?.maxMessagesPerRequest) ?? 60,
76
- writeOnApprovalResolution: trigger?.onApprovalResolved === true,
77
- writeOnRequestCompletion: trigger?.onRequestCompleted !== false,
78
- stateStorePath: asString(asObject(spec?.state)?.cursorPath) ?? "knowledge/procedural-memory-state.json",
79
- },
80
- }
81
- : null,
82
- retrieval: enabled
83
- ? {
84
- enabled: retrieval?.enabled !== false,
85
- defaultTopK: asPositiveInteger(retrieval?.defaultTopK) ?? 5,
86
- maxPromptItems: asPositiveInteger(retrieval?.maxPromptItems) ?? 4,
87
- }
88
- : null,
89
- maintenance: enabled
90
- ? {
91
- enabled: maintenance?.enabled !== false,
92
- onWrite: {
93
- dedupeNearby: onWrite?.dedupeNearby !== false,
94
- updateFrequency: onWrite?.updateFrequency !== false,
95
- },
96
- schedule: schedule
97
- ? {
98
- enabled: schedule.enabled !== false,
99
- everyMinutes: asPositiveInteger(schedule.everyMinutes) ?? 60,
100
- }
101
- : null,
102
- idle: idle
103
- ? {
104
- enabled: idle.enabled !== false,
105
- minIdleMinutes: asPositiveInteger(idle.minIdleMinutes) ?? 20,
106
- maxRunsPerIdleWindow: asPositiveInteger(idle.maxRunsPerIdleWindow) ?? 1,
107
- }
108
- : null,
109
- tasks: asStringArray(maintenance?.tasks) ?? ["dedupe", "merge_similar", "decay_stale", "prune_low_value"],
110
- limits: {
111
- maxRecordsPerRun: asPositiveInteger(limits?.maxRecordsPerRun) ?? 200,
112
- maxClustersPerRun: asPositiveInteger(limits?.maxClustersPerRun) ?? 50,
113
- },
114
- decay: {
115
- enabled: decay?.enabled !== false,
116
- ...(asPositiveInteger(decay?.maxAgeDays) ? { maxAgeDays: asPositiveInteger(decay?.maxAgeDays) } : {}),
117
- },
118
- pruning: {
119
- ...(asNumber(pruning?.minScore) !== undefined ? { minScore: asNumber(pruning?.minScore) } : {}),
120
- ...(asPositiveInteger(pruning?.minFrequency) ? { minFrequency: asPositiveInteger(pruning?.minFrequency) } : {}),
121
- },
122
- }
123
- : null,
124
- };
125
- }
1
+ function r(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function b(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function R(e){if(!Array.isArray(e))return;const n=e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0);return n.length>0?Array.from(new Set(n)):void 0}function A(e){return typeof e=="boolean"?e:void 0}function i(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0}function x(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function k(e){const n=r(e);if(!n)return;const t=typeof n.kind=="string"?n.kind:void 0,s=typeof n.apiVersion=="string"||!!r(n.metadata);return t==="ProceduralMemoryRuntime"||s&&r(n.spec)?r(n.spec):n}function M(e){const n=k(e),t=n?.enabled===!0,s=r(n?.provider),P=r(n?.mode),f=r(n?.trigger),p=r(n?.extraction),u=r(n?.retrieval),o=r(n?.maintenance),y=r(o?.onWrite),l=r(o?.schedule),d=r(o?.idle),g=r(o?.limits),c=r(o?.decay),a=r(o?.pruning);return{enabled:t,provider:s?{kind:b(s.kind)??"reme",options:Object.keys(s).filter(m=>m!=="kind").length>0?Object.fromEntries(Object.entries(s).filter(([m])=>m!=="kind")):null}:null,store:r(n?.store)??null,vectorStore:r(n?.vectorStore)??null,embeddingModel:r(n?.embeddingModel)??null,formation:t?{backgroundOnly:P?.backgroundOnly!==!1,background:{enabled:!0,scopeHints:R(p?.focus)??["coding_patterns","workflow_patterns","debugging_lessons"],maxMessagesPerRequest:i(p?.maxMessagesPerRequest)??60,writeOnApprovalResolution:f?.onApprovalResolved===!0,writeOnRequestCompletion:f?.onRequestCompleted!==!1,stateStorePath:b(r(n?.state)?.cursorPath)??"knowledge/procedural-memory-state.json"}}:null,retrieval:t?{enabled:u?.enabled!==!1,defaultTopK:i(u?.defaultTopK)??5,maxPromptItems:i(u?.maxPromptItems)??4}:null,maintenance:t?{enabled:o?.enabled!==!1,onWrite:{dedupeNearby:y?.dedupeNearby!==!1,updateFrequency:y?.updateFrequency!==!1},schedule:l?{enabled:l.enabled!==!1,everyMinutes:i(l.everyMinutes)??60}:null,idle:d?{enabled:d.enabled!==!1,minIdleMinutes:i(d.minIdleMinutes)??20,maxRunsPerIdleWindow:i(d.maxRunsPerIdleWindow)??1}:null,tasks:R(o?.tasks)??["dedupe","merge_similar","decay_stale","prune_low_value"],limits:{maxRecordsPerRun:i(g?.maxRecordsPerRun)??200,maxClustersPerRun:i(g?.maxClustersPerRun)??50},decay:{enabled:c?.enabled!==!1,...i(c?.maxAgeDays)?{maxAgeDays:i(c?.maxAgeDays)}:{}},pruning:{...x(a?.minScore)!==void 0?{minScore:x(a?.minScore)}:{},...i(a?.minFrequency)?{minFrequency:i(a?.minFrequency)}:{}}}:null}}export{M as readProceduralMemoryRuntimeConfig};
@@ -1,2 +1 @@
1
- export { readProceduralMemoryRuntimeConfig } from "./config.js";
2
- export { createBackgroundProceduralCandidates, createProceduralMemoryManager, ProceduralMemoryFormationSync, } from "./manager.js";
1
+ import{readProceduralMemoryRuntimeConfig as o}from"./config.js";import{createBackgroundProceduralCandidates as c,createProceduralMemoryManager as d,ProceduralMemoryFormationSync as m}from"./manager.js";export{m as ProceduralMemoryFormationSync,c as createBackgroundProceduralCandidates,d as createProceduralMemoryManager,o as readProceduralMemoryRuntimeConfig};
@@ -1,345 +1,9 @@
1
- import path from "node:path";
2
- import { extractMessageText } from "../../utils/message-content.js";
3
- import { createResolvedModel } from "../../runtime/adapter/model/model-providers.js";
4
- import { FileBackedStore } from "../../runtime/harness/system/store.js";
5
- import { compileModel } from "../../workspace/resource-compilers.js";
6
- import { resolveRefId } from "../../workspace/support/workspace-ref-utils.js";
7
- import { renderProceduralMemoryManagerPrompt } from "../../runtime/prompts/runtime-prompts.js";
8
- const FORMATION_EVENT_TYPES = new Set([
9
- "request.state.changed",
10
- "approval.resolved",
11
- ]);
12
- function excerpt(message) {
13
- if (!message?.content) {
14
- return undefined;
15
- }
16
- const normalized = extractMessageText(message.content).replace(/\s+/g, " ").trim();
17
- if (!normalized) {
18
- return undefined;
19
- }
20
- return normalized.length > 240 ? `${normalized.slice(0, 237)}...` : normalized;
21
- }
22
- function summarizeApprovals(approvals) {
23
- if (approvals.length === 0) {
24
- return "No approvals were recorded in this run.";
25
- }
26
- return approvals
27
- .map((approval) => `${approval.toolName} (${approval.status})`)
28
- .join(", ");
29
- }
30
- function fingerprintMessages(messages, focus) {
31
- const serialized = messages
32
- .map((message) => `${message.role}\n${message.createdAt}\n${extractMessageText(message.content)}`)
33
- .join("\n---\n");
34
- return `${focus.join(",")}::${serialized}`;
35
- }
36
- function selectRelatedContextRecords(candidate, existingRecords, maxRecords) {
37
- const candidateText = `${candidate.summary ?? ""}\n${candidate.content}`.toLowerCase().trim();
38
- if (!candidateText) {
39
- return existingRecords.slice(0, maxRecords);
40
- }
41
- return existingRecords
42
- .filter((record) => record.status === "active")
43
- .map((record) => {
44
- let score = 0;
45
- const recordText = `${record.summary}\n${record.content}`.toLowerCase();
46
- if (candidate.scope && record.scope === candidate.scope) {
47
- score += 2;
48
- }
49
- if (recordText.includes(candidateText) || candidateText.includes(recordText)) {
50
- score += 4;
51
- }
52
- const candidateTokens = new Set(candidateText.split(/[^a-z0-9_\u4e00-\u9fff]+/iu).filter((token) => token.length > 1));
53
- const recordTokens = new Set(recordText.split(/[^a-z0-9_\u4e00-\u9fff]+/iu).filter((token) => token.length > 1));
54
- let shared = 0;
55
- for (const token of candidateTokens) {
56
- if (recordTokens.has(token)) {
57
- shared += 1;
58
- }
59
- }
60
- score += shared;
61
- return { record, score };
62
- })
63
- .filter((item) => item.score > 0)
64
- .sort((left, right) => right.score - left.score || right.record.lastConfirmedAt.localeCompare(left.record.lastConfirmedAt))
65
- .slice(0, maxRecords)
66
- .map((item) => item.record);
67
- }
68
- function extractText(value) {
69
- if (typeof value === "string") {
70
- return value;
71
- }
72
- if (typeof value !== "object" || value === null) {
73
- return undefined;
74
- }
75
- if ("content" in value && typeof value.content === "string") {
76
- return String(value.content);
77
- }
78
- const kwargs = "kwargs" in value && typeof value.kwargs === "object" && value.kwargs !== null
79
- ? value.kwargs
80
- : undefined;
81
- if (typeof kwargs?.content === "string") {
82
- return kwargs.content;
83
- }
84
- return undefined;
85
- }
86
- function tryParseJsonObject(text) {
87
- try {
88
- const parsed = JSON.parse(text);
89
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
90
- }
91
- catch {
92
- const match = text.match(/\{[\s\S]*\}/);
93
- if (!match) {
94
- return null;
95
- }
96
- try {
97
- const parsed = JSON.parse(match[0]);
98
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
99
- }
100
- catch {
101
- return null;
102
- }
103
- }
104
- }
105
- function asString(value) {
106
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
107
- }
108
- function asNumber(value) {
109
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
110
- }
111
- function asStringArray(value) {
112
- if (!Array.isArray(value)) {
113
- return undefined;
114
- }
115
- const items = value
116
- .filter((item) => typeof item === "string")
117
- .map((item) => item.trim())
118
- .filter((item) => item.length > 0);
119
- return items.length > 0 ? Array.from(new Set(items)) : undefined;
120
- }
121
- function normalizeScope(value) {
122
- return value === "session" || value === "agent" || value === "workspace" || value === "user" || value === "project"
123
- ? value
124
- : undefined;
125
- }
126
- function normalizeCandidateOutputs(parsed, candidate) {
127
- const rawOutputs = Array.isArray(parsed.mutations)
128
- ? parsed.mutations.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item))
129
- : [parsed];
130
- return rawOutputs.map((output) => ({
131
- ...candidate,
132
- kind: "procedural",
133
- scope: normalizeScope(output.scope) ?? candidate.scope ?? "workspace",
134
- summary: asString(output.summary) ?? candidate.summary,
135
- content: asString(output.content) ?? candidate.content,
136
- confidence: asNumber(output.confidence) ?? candidate.confidence ?? 0.72,
137
- tags: asStringArray(output.tags) ?? candidate.tags,
138
- })).filter((item) => typeof item.content === "string" && item.content.trim().length > 0);
139
- }
140
- export function createBackgroundProceduralCandidates(input) {
141
- const latestUser = excerpt(input.messages.filter((message) => message.role === "user").at(-1));
142
- const latestAssistant = excerpt(input.messages.filter((message) => message.role === "assistant").at(-1));
143
- const transcriptPreview = input.messages
144
- .slice(-6)
145
- .map((message) => `${message.role}: ${excerpt(message) ?? "(empty)"}`)
146
- .join("\n");
147
- const approvals = summarizeApprovals(input.approvals);
148
- const sourceRef = `runtime://sessions/${input.session.sessionId}/requests/${input.requestId}/procedural-reflection`;
149
- return [{
150
- kind: "procedural",
151
- scope: "workspace",
152
- sourceType: "runtime-transcript",
153
- sourceRef,
154
- summary: latestUser ?? latestAssistant ?? `Procedural reflection for ${input.requestId}`,
155
- content: [
156
- "Completed run transcript evidence for procedural memory extraction.",
157
- `Trigger: ${input.trigger}`,
158
- `Focus: ${input.focus.join(", ")}`,
159
- "",
160
- "Latest user message:",
161
- latestUser ?? "(none)",
162
- "",
163
- "Latest assistant response:",
164
- latestAssistant ?? "(none)",
165
- "",
166
- "Recent transcript excerpt:",
167
- transcriptPreview || "(none)",
168
- "",
169
- "Approval snapshot:",
170
- approvals,
171
- ].join("\n"),
172
- confidence: 0.64,
173
- observedAt: input.recordedAt,
174
- tags: ["procedural-background-extraction", input.trigger, ...input.focus],
175
- }];
176
- }
177
- async function runProceduralMemoryManager(input) {
178
- let resolvedModel;
179
- try {
180
- resolvedModel = await createResolvedModel(input.model, input.modelResolver);
181
- }
182
- catch {
183
- return input.candidates;
184
- }
185
- const invoker = resolvedModel;
186
- if (typeof invoker.invoke !== "function") {
187
- return input.candidates;
188
- }
189
- const transformed = [];
190
- for (const candidate of input.candidates) {
191
- const prompt = renderProceduralMemoryManagerPrompt({
192
- candidate,
193
- sessionId: input.sessionId,
194
- requestId: input.requestId,
195
- focus: input.focus,
196
- existingRecords: selectRelatedContextRecords(candidate, input.existingRecords, input.maxContextRecords ?? input.existingRecords.length),
197
- });
198
- let response;
199
- try {
200
- response = await invoker.invoke(prompt, {});
201
- }
202
- catch {
203
- continue;
204
- }
205
- const parsed = tryParseJsonObject(extractText(response) ?? "");
206
- if (!parsed || parsed.store === false) {
207
- continue;
208
- }
209
- transformed.push(...normalizeCandidateOutputs(parsed, candidate));
210
- }
211
- return transformed;
212
- }
213
- export function createProceduralMemoryManager(input) {
214
- return {
215
- async transform({ candidates, binding, sessionId, requestId, recordedAt, existingRecords }) {
216
- if (input.config.enabled !== true || candidates.length === 0) {
217
- return candidates;
218
- }
219
- if (!binding.langchainAgentParams?.model) {
220
- return candidates;
221
- }
222
- const providerModelRef = asString(input.config.provider?.options?.modelRef);
223
- const primaryModel = (() => {
224
- if (!providerModelRef) {
225
- return binding.langchainAgentParams.model;
226
- }
227
- const configured = input.workspace.models.get(resolveRefId(providerModelRef));
228
- return configured ? compileModel(configured) : binding.langchainAgentParams.model;
229
- })();
230
- return runProceduralMemoryManager({
231
- workspace: input.workspace,
232
- binding,
233
- model: primaryModel,
234
- candidates,
235
- sessionId,
236
- requestId,
237
- recordedAt,
238
- existingRecords: existingRecords.filter((record) => record.status === "active"),
239
- focus: input.config.formation?.background?.scopeHints ?? ["workflow_patterns", "debugging_lessons", "reusable_procedures"],
240
- maxContextRecords: 8,
241
- modelResolver: input.modelResolver,
242
- });
243
- },
244
- };
245
- }
246
- export class ProceduralMemoryFormationSync {
247
- persistence;
248
- config;
249
- writer;
250
- stateStore;
251
- options;
252
- pending = new Set();
253
- syncChain = Promise.resolve();
254
- name = "procedural-memory-formation-sync";
255
- constructor(persistence, config, writer, runtimeRoot, stateStore = new FileBackedStore(path.join(runtimeRoot, config.formation?.background?.stateStorePath ?? "knowledge/procedural-memory-state.json")), options = {}) {
256
- this.persistence = persistence;
257
- this.config = config;
258
- this.writer = writer;
259
- this.stateStore = stateStore;
260
- this.options = options;
261
- }
262
- shouldHandle(event) {
263
- const background = this.config.formation?.background;
264
- if (!background?.enabled || !FORMATION_EVENT_TYPES.has(event.eventType)) {
265
- return false;
266
- }
267
- if (event.eventType === "approval.resolved") {
268
- return background.writeOnApprovalResolution;
269
- }
270
- return background.writeOnRequestCompletion && event.payload.state === "completed";
271
- }
272
- async handleEvent(event) {
273
- if (!this.shouldHandle(event)) {
274
- return;
275
- }
276
- const trigger = event.eventType === "approval.resolved" ? "approval.resolved" : "request.completed";
277
- const task = this.syncChain
278
- .then(() => this.reflectRun(event.sessionId, event.requestId, trigger, event.timestamp))
279
- .catch(() => {
280
- // Fail open: procedural reflection should not block runtime progress.
281
- });
282
- this.syncChain = task
283
- .catch(() => {
284
- // Fail open: procedural reflection should not block runtime progress.
285
- })
286
- .finally(() => {
287
- this.pending.delete(task);
288
- });
289
- this.pending.add(task);
290
- }
291
- async reflectRun(sessionId, requestId, trigger, recordedAt) {
292
- const background = this.config.formation?.background;
293
- if (!background) {
294
- return;
295
- }
296
- const [session, run, allMessages, approvals] = await Promise.all([
297
- this.persistence.getSession(sessionId),
298
- this.persistence.getRequest(requestId),
299
- this.persistence.listSessionMessages(sessionId, background.maxMessagesPerRequest),
300
- this.persistence.getRequestApprovals(sessionId, requestId),
301
- ]);
302
- if (!session || !run) {
303
- return;
304
- }
305
- const messages = allMessages.filter((message) => message.requestId === requestId);
306
- if (messages.length === 0) {
307
- return;
308
- }
309
- const fingerprint = fingerprintMessages(messages, background.scopeHints);
310
- const namespace = ["memories", "formation", "sessions", sessionId, "requests"];
311
- const cursor = await this.stateStore.get(namespace, requestId);
312
- const existing = cursor?.value;
313
- if (existing?.fingerprint === fingerprint && existing.trigger === trigger) {
314
- return;
315
- }
316
- const candidates = createBackgroundProceduralCandidates({
317
- session,
318
- requestId,
319
- agentId: run.agentId ?? session.agentId,
320
- trigger,
321
- recordedAt,
322
- messages,
323
- approvals,
324
- focus: background.scopeHints,
325
- });
326
- await this.writer({
327
- candidates,
328
- sessionId,
329
- requestId,
330
- agentId: run.agentId ?? session.agentId,
331
- userId: this.options.userId,
332
- projectId: this.options.projectId,
333
- recordedAt,
334
- });
335
- await this.stateStore.put(namespace, requestId, {
336
- fingerprint,
337
- candidateCount: candidates.length,
338
- syncedAt: new Date().toISOString(),
339
- trigger,
340
- });
341
- }
342
- async close() {
343
- await Promise.allSettled(Array.from(this.pending));
344
- }
345
- }
1
+ import k from"node:path";import{extractMessageText as h}from"../../utils/message-content.js";import{createResolvedModel as A}from"../../runtime/adapter/model/model-providers.js";import{FileBackedStore as S}from"../../runtime/harness/system/store.js";import{compileModel as R}from"../../workspace/resource-compilers.js";import{resolveRefId as x}from"../../workspace/support/workspace-ref-utils.js";import{renderProceduralMemoryManagerPrompt as $}from"../../runtime/prompts/runtime-prompts.js";const b=new Set(["request.state.changed","approval.resolved"]);function d(e){if(!e?.content)return;const t=h(e.content).replace(/\s+/g," ").trim();if(t)return t.length>240?`${t.slice(0,237)}...`:t}function M(e){return e.length===0?"No approvals were recorded in this run.":e.map(t=>`${t.toolName} (${t.status})`).join(", ")}function P(e,t){const r=e.map(n=>`${n.role}
2
+ ${n.createdAt}
3
+ ${h(n.content)}`).join(`
4
+ ---
5
+ `);return`${t.join(",")}::${r}`}function j(e,t,r){const n=`${e.summary??""}
6
+ ${e.content}`.toLowerCase().trim();return n?t.filter(o=>o.status==="active").map(o=>{let c=0;const s=`${o.summary}
7
+ ${o.content}`.toLowerCase();e.scope&&o.scope===e.scope&&(c+=2),(s.includes(n)||n.includes(s))&&(c+=4);const i=new Set(n.split(/[^a-z0-9_\u4e00-\u9fff]+/iu).filter(l=>l.length>1)),f=new Set(s.split(/[^a-z0-9_\u4e00-\u9fff]+/iu).filter(l=>l.length>1));let a=0;for(const l of i)f.has(l)&&(a+=1);return c+=a,{record:o,score:c}}).filter(o=>o.score>0).sort((o,c)=>c.score-o.score||c.record.lastConfirmedAt.localeCompare(o.record.lastConfirmedAt)).slice(0,r).map(o=>o.record):t.slice(0,r)}function C(e){if(typeof e=="string")return e;if(typeof e!="object"||e===null)return;if("content"in e&&typeof e.content=="string")return String(e.content);const t="kwargs"in e&&typeof e.kwargs=="object"&&e.kwargs!==null?e.kwargs:void 0;if(typeof t?.content=="string")return t.content}function T(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{const t=e.match(/\{[\s\S]*\}/);if(!t)return null;try{const r=JSON.parse(t[0]);return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:null}catch{return null}}}function u(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function I(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function O(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return t.length>0?Array.from(new Set(t)):void 0}function v(e){return e==="session"||e==="agent"||e==="workspace"||e==="user"||e==="project"?e:void 0}function q(e,t){return(Array.isArray(e.mutations)?e.mutations.filter(n=>typeof n=="object"&&n!==null&&!Array.isArray(n)):[e]).map(n=>({...t,kind:"procedural",scope:v(n.scope)??t.scope??"workspace",summary:u(n.summary)??t.summary,content:u(n.content)??t.content,confidence:I(n.confidence)??t.confidence??.72,tags:O(n.tags)??t.tags})).filter(n=>typeof n.content=="string"&&n.content.trim().length>0)}function N(e){const t=d(e.messages.filter(s=>s.role==="user").at(-1)),r=d(e.messages.filter(s=>s.role==="assistant").at(-1)),n=e.messages.slice(-6).map(s=>`${s.role}: ${d(s)??"(empty)"}`).join(`
8
+ `),o=M(e.approvals);return[{kind:"procedural",scope:"workspace",sourceType:"runtime-transcript",sourceRef:`runtime://sessions/${e.session.sessionId}/requests/${e.requestId}/procedural-reflection`,summary:t??r??`Procedural reflection for ${e.requestId}`,content:["Completed run transcript evidence for procedural memory extraction.",`Trigger: ${e.trigger}`,`Focus: ${e.focus.join(", ")}`,"","Latest user message:",t??"(none)","","Latest assistant response:",r??"(none)","","Recent transcript excerpt:",n||"(none)","","Approval snapshot:",o].join(`
9
+ `),confidence:.64,observedAt:e.recordedAt,tags:["procedural-background-extraction",e.trigger,...e.focus]}]}async function z(e){let t;try{t=await A(e.model,e.modelResolver)}catch{return e.candidates}const r=t;if(typeof r.invoke!="function")return e.candidates;const n=[];for(const o of e.candidates){const c=$({candidate:o,sessionId:e.sessionId,requestId:e.requestId,focus:e.focus,existingRecords:j(o,e.existingRecords,e.maxContextRecords??e.existingRecords.length)});let s;try{s=await r.invoke(c,{})}catch{continue}const i=T(C(s)??"");!i||i.store===!1||n.push(...q(i,o))}return n}function U(e){return{async transform({candidates:t,binding:r,sessionId:n,requestId:o,recordedAt:c,existingRecords:s}){if(e.config.enabled!==!0||t.length===0||!r.langchainAgentParams?.model)return t;const i=u(e.config.provider?.options?.modelRef),f=(()=>{if(!i)return r.langchainAgentParams.model;const a=e.workspace.models.get(x(i));return a?R(a):r.langchainAgentParams.model})();return z({workspace:e.workspace,binding:r,model:f,candidates:t,sessionId:n,requestId:o,recordedAt:c,existingRecords:s.filter(a=>a.status==="active"),focus:e.config.formation?.background?.scopeHints??["workflow_patterns","debugging_lessons","reusable_procedures"],maxContextRecords:8,modelResolver:e.modelResolver})}}}class V{persistence;config;writer;stateStore;options;pending=new Set;syncChain=Promise.resolve();name="procedural-memory-formation-sync";constructor(t,r,n,o,c=new S(k.join(o,r.formation?.background?.stateStorePath??"knowledge/procedural-memory-state.json")),s={}){this.persistence=t,this.config=r,this.writer=n,this.stateStore=c,this.options=s}shouldHandle(t){const r=this.config.formation?.background;return!r?.enabled||!b.has(t.eventType)?!1:t.eventType==="approval.resolved"?r.writeOnApprovalResolution:r.writeOnRequestCompletion&&t.payload.state==="completed"}async handleEvent(t){if(!this.shouldHandle(t))return;const r=t.eventType==="approval.resolved"?"approval.resolved":"request.completed",n=this.syncChain.then(()=>this.reflectRun(t.sessionId,t.requestId,r,t.timestamp)).catch(()=>{});this.syncChain=n.catch(()=>{}).finally(()=>{this.pending.delete(n)}),this.pending.add(n)}async reflectRun(t,r,n,o){const c=this.config.formation?.background;if(!c)return;const[s,i,f,a]=await Promise.all([this.persistence.getSession(t),this.persistence.getRequest(r),this.persistence.listSessionMessages(t,c.maxMessagesPerRequest),this.persistence.getRequestApprovals(t,r)]);if(!s||!i)return;const l=f.filter(w=>w.requestId===r);if(l.length===0)return;const m=P(l,c.scopeHints),p=["memories","formation","sessions",t,"requests"],g=(await this.stateStore.get(p,r))?.value;if(g?.fingerprint===m&&g.trigger===n)return;const y=N({session:s,requestId:r,agentId:i.agentId??s.agentId,trigger:n,recordedAt:o,messages:l,approvals:a,focus:c.scopeHints});await this.writer({candidates:y,sessionId:t,requestId:r,agentId:i.agentId??s.agentId,userId:this.options.userId,projectId:this.options.projectId,recordedAt:o}),await this.stateStore.put(p,r,{fingerprint:m,candidateCount:y.length,syncedAt:new Date().toISOString(),trigger:n})}async close(){await Promise.allSettled(Array.from(this.pending))}}export{V as ProceduralMemoryFormationSync,N as createBackgroundProceduralCandidates,U as createProceduralMemoryManager};
package/dist/mcp.js CHANGED
@@ -1,2 +1 @@
1
- export { AGENT_HARNESS_VERSION } from "./package-version.js";
2
- export * from "./protocol/mcp/server.js";
1
+ import{AGENT_HARNESS_VERSION as E}from"./package-version.js";export*from"./protocol/mcp/server.js";export{E as AGENT_HARNESS_VERSION};
@@ -1,2 +1,2 @@
1
- export declare const AGENT_HARNESS_VERSION = "0.0.475";
1
+ export declare const AGENT_HARNESS_VERSION = "0.0.476";
2
2
  export declare const AGENT_HARNESS_RELEASE_DATE = "2026-05-08";
@@ -1,2 +1 @@
1
- export const AGENT_HARNESS_VERSION = "0.0.475";
2
- export const AGENT_HARNESS_RELEASE_DATE = "2026-05-08";
1
+ const E="0.0.476",A="2026-05-08";export{A as AGENT_HARNESS_RELEASE_DATE,E as AGENT_HARNESS_VERSION};