@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,129 +1 @@
1
- import { readSkillMetadata } from "../../skills/skill-metadata.js";
2
- import { getBindingBackendConfig, getBindingPrimaryModel, getBindingPrimaryTools, getBindingSkills, getBindingSubagents, } from "../../support/compiled-binding.js";
3
- import { assessSkillRequirements, } from "./skill-requirements.js";
4
- import { createRuntimeEnv } from "../../env/runtime-env.js";
5
- function listHostBindings(workspace) {
6
- return Array.from(workspace.bindings.values());
7
- }
8
- export function findAgentBinding(workspace, agentId) {
9
- return workspace.bindings.get(agentId);
10
- }
11
- function dedupeTools(tools) {
12
- const deduped = new Map();
13
- for (const tool of tools) {
14
- deduped.set(tool.name, { name: tool.name, description: tool.description });
15
- }
16
- return Array.from(deduped.values());
17
- }
18
- function readBackendRequirementOptions(binding) {
19
- const backend = getBindingBackendConfig(binding);
20
- if (!backend) {
21
- return {};
22
- }
23
- const backendState = typeof backend.state === "object" && backend.state
24
- ? backend.state
25
- : backend;
26
- const env = typeof backendState.env === "object" && backendState.env
27
- ? Object.fromEntries(Object.entries(backendState.env).filter((entry) => typeof entry[1] === "string"))
28
- : undefined;
29
- const inheritedEnv = backendState.inheritEnv === false ? {} : process.env;
30
- const runtimeEnv = createRuntimeEnv(env, inheritedEnv);
31
- return {
32
- env: runtimeEnv,
33
- path: runtimeEnv.PATH,
34
- };
35
- }
36
- function mergeRequirementOptions(binding, options = {}) {
37
- const fromBackend = readBackendRequirementOptions(binding);
38
- return {
39
- ...fromBackend,
40
- ...options,
41
- assessRequirements: options.assessRequirements ?? true,
42
- env: options.env ? { ...(fromBackend.env ?? {}), ...options.env } : fromBackend.env,
43
- path: options.path ?? fromBackend.path,
44
- };
45
- }
46
- function toSkillRecords(skillPaths, options = {}) {
47
- return Array.from(new Set(skillPaths)).map((skillPath) => {
48
- const metadata = readSkillMetadata(skillPath);
49
- return {
50
- name: metadata.name,
51
- path: skillPath,
52
- description: metadata.description,
53
- license: metadata.license,
54
- compatibility: metadata.compatibility,
55
- metadata: metadata.metadata,
56
- allowedTools: metadata.allowedTools,
57
- userInvocable: metadata.userInvocable,
58
- openclaw: metadata.openclaw,
59
- ...(options.assessRequirements === false ? {} : { requirements: assessSkillRequirements(metadata, options) }),
60
- };
61
- });
62
- }
63
- function toInventoryModelRecord(model) {
64
- if (!model) {
65
- return undefined;
66
- }
67
- const init = typeof model.init === "object" && model.init ? model.init : {};
68
- const baseUrl = typeof init.baseUrl === "string" && init.baseUrl.trim().length > 0
69
- ? init.baseUrl.trim()
70
- : typeof init.baseURL === "string" && init.baseURL.trim().length > 0
71
- ? init.baseURL.trim()
72
- : undefined;
73
- return {
74
- id: model.id,
75
- provider: model.provider,
76
- model: model.model,
77
- ...(baseUrl ? { baseUrl } : {}),
78
- };
79
- }
80
- export function listAgentTools(workspace, agentId) {
81
- const binding = findAgentBinding(workspace, agentId);
82
- if (!binding) {
83
- return [];
84
- }
85
- return dedupeTools(getBindingPrimaryTools(binding));
86
- }
87
- export function listAgentSkills(workspace, agentId, options = {}) {
88
- const binding = findAgentBinding(workspace, agentId);
89
- if (!binding) {
90
- return [];
91
- }
92
- const resolvedOptions = mergeRequirementOptions(binding, options);
93
- return toSkillRecords(getBindingSkills(binding), resolvedOptions);
94
- }
95
- function describeSubagent(subagent, parentAgentId, options = {}) {
96
- return {
97
- id: subagent.name,
98
- description: subagent.description,
99
- parentAgentId,
100
- model: toInventoryModelRecord(subagent.model),
101
- tools: dedupeTools(subagent.tools ?? []),
102
- skills: toSkillRecords(subagent.skills ?? [], options),
103
- };
104
- }
105
- export function listSubagents(workspace, options = {}) {
106
- return listHostBindings(workspace).flatMap((binding) => {
107
- const resolvedOptions = mergeRequirementOptions(binding, options);
108
- return getBindingSubagents(binding).map((subagent) => describeSubagent(subagent, binding.agent.id, resolvedOptions));
109
- });
110
- }
111
- export function listAvailableAgents(workspace, options = {}) {
112
- const topLevel = listHostBindings(workspace).map((binding) => ({
113
- id: binding.agent.id,
114
- description: binding.agent.description,
115
- model: toInventoryModelRecord(getBindingPrimaryModel(binding)),
116
- tools: listAgentTools(workspace, binding.agent.id),
117
- skills: listAgentSkills(workspace, binding.agent.id, options),
118
- }));
119
- return [...topLevel, ...listSubagents(workspace, options)];
120
- }
121
- export function getAgentInventoryRecord(workspace, agentId, options = {}) {
122
- return listAvailableAgents(workspace, options).find((agent) => agent.id === agentId) ?? null;
123
- }
124
- export function describeWorkspaceInventory(workspace, options = {}) {
125
- return {
126
- workspaceRoot: workspace.workspaceRoot,
127
- agents: listAvailableAgents(workspace, options),
128
- };
129
- }
1
+ import{readSkillMetadata as m}from"../../skills/skill-metadata.js";import{getBindingBackendConfig as g,getBindingPrimaryModel as v,getBindingPrimaryTools as b,getBindingSkills as y,getBindingSubagents as R}from"../../support/compiled-binding.js";import{assessSkillRequirements as k}from"./skill-requirements.js";import{createRuntimeEnv as A}from"../../env/runtime-env.js";function s(e){return Array.from(e.bindings.values())}function a(e,t){return e.bindings.get(t)}function c(e){const t=new Map;for(const n of e)t.set(n.name,{name:n.name,description:n.description});return Array.from(t.values())}function B(e){const t=g(e);if(!t)return{};const n=typeof t.state=="object"&&t.state?t.state:t,r=typeof n.env=="object"&&n.env?Object.fromEntries(Object.entries(n.env).filter(p=>typeof p[1]=="string")):void 0,i=n.inheritEnv===!1?{}:process.env,o=A(r,i);return{env:o,path:o.PATH}}function l(e,t={}){const n=B(e);return{...n,...t,assessRequirements:t.assessRequirements??!0,env:t.env?{...n.env??{},...t.env}:n.env,path:t.path??n.path}}function d(e,t={}){return Array.from(new Set(e)).map(n=>{const r=m(n);return{name:r.name,path:n,description:r.description,license:r.license,compatibility:r.compatibility,metadata:r.metadata,allowedTools:r.allowedTools,userInvocable:r.userInvocable,openclaw:r.openclaw,...t.assessRequirements===!1?{}:{requirements:k(r,t)}}})}function u(e){if(!e)return;const t=typeof e.init=="object"&&e.init?e.init:{},n=typeof t.baseUrl=="string"&&t.baseUrl.trim().length>0?t.baseUrl.trim():typeof t.baseURL=="string"&&t.baseURL.trim().length>0?t.baseURL.trim():void 0;return{id:e.id,provider:e.provider,model:e.model,...n?{baseUrl:n}:{}}}function S(e,t){const n=a(e,t);return n?c(b(n)):[]}function h(e,t,n={}){const r=a(e,t);if(!r)return[];const i=l(r,n);return d(y(r),i)}function q(e,t,n={}){return{id:e.name,description:e.description,parentAgentId:t,model:u(e.model),tools:c(e.tools??[]),skills:d(e.skills??[],n)}}function x(e,t={}){return s(e).flatMap(n=>{const r=l(n,t);return R(n).map(i=>q(i,n.agent.id,r))})}function f(e,t={}){return[...s(e).map(r=>({id:r.agent.id,description:r.agent.description,model:u(v(r)),tools:S(e,r.agent.id),skills:h(e,r.agent.id,t)})),...x(e,t)]}function E(e,t,n={}){return f(e,n).find(r=>r.id===t)??null}function I(e,t={}){return{workspaceRoot:e.workspaceRoot,agents:f(e,t)}}export{I as describeWorkspaceInventory,a as findAgentBinding,E as getAgentInventoryRecord,h as listAgentSkills,S as listAgentTools,f as listAvailableAgents,x as listSubagents};
@@ -1,345 +1,5 @@
1
- import { createHash } from "node:crypto";
2
- import path from "node:path";
3
- import { extractMessageText } from "../../../utils/message-content.js";
4
- import { FileBackedStore } from "./store.js";
5
- const MEM0_EVENT_TYPES = new Set([
6
- "request.state.changed",
7
- "approval.resolved",
8
- ]);
9
- function asRecord(value) {
10
- return typeof value === "object" && value && !Array.isArray(value) ? value : undefined;
11
- }
12
- function asNonEmptyString(value) {
13
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
14
- }
15
- function asPositiveInteger(value) {
16
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
17
- }
18
- function asBoolean(value) {
19
- return typeof value === "boolean" ? value : undefined;
20
- }
21
- function normalizeMessages(messages) {
22
- const normalized = [];
23
- for (const message of messages) {
24
- const content = extractMessageText(message.content).trim();
25
- if (!content) {
26
- continue;
27
- }
28
- normalized.push({
29
- role: message.role,
30
- content,
31
- });
32
- }
33
- return normalized;
34
- }
35
- function fingerprintMessages(messages) {
36
- const hash = createHash("sha256");
37
- for (const message of messages) {
38
- hash.update(message.role);
39
- hash.update("\n");
40
- hash.update(message.createdAt);
41
- hash.update("\n");
42
- hash.update(extractMessageText(message.content));
43
- hash.update("\n---\n");
44
- }
45
- return hash.digest("hex");
46
- }
47
- export function readMem0RuntimeConfig(runtimeMemory, workspaceRoot) {
48
- if (runtimeMemory?.enabled !== true) {
49
- return undefined;
50
- }
51
- const mem0 = asRecord(runtimeMemory.mem0);
52
- if (!mem0 || mem0.enabled !== true) {
53
- return undefined;
54
- }
55
- const ingestion = asRecord(runtimeMemory.ingestion);
56
- const workspaceBaseName = path.basename(workspaceRoot) || "agent-harness";
57
- return {
58
- enabled: true,
59
- apiKeyEnv: asNonEmptyString(mem0.apiKeyEnv) ?? "MEM0_API_KEY",
60
- host: asNonEmptyString(mem0.host),
61
- organizationName: asNonEmptyString(mem0.organizationName),
62
- projectName: asNonEmptyString(mem0.projectName),
63
- organizationId: asNonEmptyString(mem0.organizationId),
64
- projectId: asNonEmptyString(mem0.projectId),
65
- appId: asNonEmptyString(mem0.appId) ?? workspaceBaseName,
66
- userIdPrefix: asNonEmptyString(mem0.userIdPrefix),
67
- stateStorePath: asNonEmptyString(mem0.stateStorePath) ?? "knowledge/mem0-sync-state.json",
68
- maxMessagesPerRequest: asPositiveInteger(mem0.maxMessagesPerRequest) ?? 200,
69
- writeOnApprovalResolution: asBoolean(mem0.writeOnApprovalResolution) ?? asBoolean(ingestion?.writeOnApprovalResolution) ?? true,
70
- writeOnRequestCompletion: asBoolean(mem0.writeOnRequestCompletion) ?? asBoolean(ingestion?.writeOnRequestCompletion) ?? true,
71
- };
72
- }
73
- async function createDefaultMem0Client(config) {
74
- const apiKey = process.env[config.apiKeyEnv]?.trim();
75
- if (!apiKey && config.host) {
76
- return createSelfHostedMem0Client(config);
77
- }
78
- if (!apiKey) {
79
- throw new Error(`runtimeMemory.mem0 is enabled but environment variable ${config.apiKeyEnv} is not set`);
80
- }
81
- return createCloudMem0Client(config, apiKey);
82
- }
83
- function normalizeMem0Host(host) {
84
- return host.replace(/\/+$/, "");
85
- }
86
- function buildMem0Headers(apiKey) {
87
- return {
88
- "Content-Type": "application/json",
89
- ...(apiKey ? { Authorization: `Token ${apiKey}` } : {}),
90
- };
91
- }
92
- async function selfHostedMem0Request(config, pathname, options = {}) {
93
- if (!config.host) {
94
- throw new Error("Self-hosted mem0 client requires runtimeMemory.mem0.host.");
95
- }
96
- const response = await fetch(`${normalizeMem0Host(config.host)}${pathname}`, {
97
- method: options.method ?? "GET",
98
- headers: buildMem0Headers(),
99
- ...(options.body ? { body: JSON.stringify(options.body) } : {}),
100
- });
101
- if (!response.ok) {
102
- throw new Error(`Self-hosted mem0 request failed: ${response.status} ${response.statusText}`);
103
- }
104
- return response.json();
105
- }
106
- function applyMem0Scope(payload, config) {
107
- const scoped = { ...payload };
108
- if (config.organizationName && config.projectName) {
109
- scoped.org_name = config.organizationName;
110
- scoped.project_name = config.projectName;
111
- }
112
- if (config.organizationId && config.projectId) {
113
- scoped.org_id = config.organizationId;
114
- scoped.project_id = config.projectId;
115
- delete scoped.org_name;
116
- delete scoped.project_name;
117
- }
118
- return scoped;
119
- }
120
- async function cloudMem0Request(config, apiKey, pathname, options = {}) {
121
- const host = normalizeMem0Host(config.host ?? "https://api.mem0.ai");
122
- const response = await fetch(`${host}${pathname}`, {
123
- method: options.method ?? "GET",
124
- headers: buildMem0Headers(apiKey),
125
- ...(options.body ? { body: JSON.stringify(applyMem0Scope(options.body, config)) } : {}),
126
- });
127
- if (!response.ok) {
128
- throw new Error(`Mem0 request failed: ${response.status} ${response.statusText}`);
129
- }
130
- return response.json();
131
- }
132
- function createCloudMem0Client(config, apiKey) {
133
- return {
134
- async add(messages, options = {}) {
135
- return cloudMem0Request(config, apiKey, "/v1/memories/", {
136
- method: "POST",
137
- body: {
138
- messages,
139
- ...options,
140
- },
141
- });
142
- },
143
- async search(query, options = {}) {
144
- return cloudMem0Request(config, apiKey, "/v1/memories/search/", {
145
- method: "POST",
146
- body: {
147
- query,
148
- ...options,
149
- },
150
- });
151
- },
152
- };
153
- }
154
- function createSelfHostedMem0Client(config) {
155
- return {
156
- async add(messages, options = {}) {
157
- return selfHostedMem0Request(config, "/v1/memories/", {
158
- method: "POST",
159
- body: {
160
- messages,
161
- ...options,
162
- },
163
- });
164
- },
165
- async search(query, options = {}) {
166
- return selfHostedMem0Request(config, "/v1/memories/search/", {
167
- method: "POST",
168
- body: {
169
- query,
170
- ...options,
171
- },
172
- });
173
- },
174
- };
175
- }
176
- export class Mem0IngestionSync {
177
- persistence;
178
- config;
179
- runtimeRoot;
180
- stateStore;
181
- clientFactory;
182
- pending = new Set();
183
- syncChain = Promise.resolve();
184
- clientPromise = null;
185
- name = "mem0-ingestion-sync";
186
- constructor(persistence, config, runtimeRoot, stateStore = new FileBackedStore(path.join(runtimeRoot, config.stateStorePath)), clientFactory = createDefaultMem0Client) {
187
- this.persistence = persistence;
188
- this.config = config;
189
- this.runtimeRoot = runtimeRoot;
190
- this.stateStore = stateStore;
191
- this.clientFactory = clientFactory;
192
- }
193
- shouldHandle(event) {
194
- if (!MEM0_EVENT_TYPES.has(event.eventType)) {
195
- return false;
196
- }
197
- if (event.eventType === "approval.resolved") {
198
- return this.config.writeOnApprovalResolution;
199
- }
200
- if (event.eventType === "request.state.changed") {
201
- return this.config.writeOnRequestCompletion && event.payload.state === "completed";
202
- }
203
- return false;
204
- }
205
- async handleEvent(event) {
206
- if (!this.shouldHandle(event)) {
207
- return;
208
- }
209
- const trigger = event.eventType === "approval.resolved" ? "approval.resolved" : "request.completed";
210
- const task = this.syncChain
211
- .then(() => this.syncRun(event.sessionId, event.requestId, trigger))
212
- .catch(() => {
213
- // Fail open: memory ingestion must not break run execution.
214
- });
215
- this.syncChain = task
216
- .catch(() => {
217
- // Fail open: memory ingestion must not break run execution.
218
- })
219
- .finally(() => {
220
- this.pending.delete(task);
221
- });
222
- this.pending.add(task);
223
- }
224
- async getClient() {
225
- if (!this.clientPromise) {
226
- this.clientPromise = Promise.resolve(this.clientFactory(this.config));
227
- }
228
- return this.clientPromise;
229
- }
230
- async syncRun(sessionId, requestId, trigger) {
231
- const allMessages = await this.persistence.listSessionMessages(sessionId, this.config.maxMessagesPerRequest);
232
- const runMessages = allMessages.filter((message) => message.requestId === requestId);
233
- const normalized = normalizeMessages(runMessages);
234
- if (normalized.length === 0) {
235
- return;
236
- }
237
- const fingerprint = fingerprintMessages(runMessages);
238
- const namespace = ["mem0", "sessions", sessionId, "requests"];
239
- const existingCursor = await this.stateStore.get(namespace, requestId);
240
- const existing = existingCursor?.value;
241
- if (existing?.fingerprint === fingerprint) {
242
- return;
243
- }
244
- const [session, request, client] = await Promise.all([
245
- this.persistence.getSession(sessionId),
246
- this.persistence.getRequest(requestId),
247
- this.getClient(),
248
- ]);
249
- await client.add(normalized, {
250
- ...(this.config.userIdPrefix ? { user_id: `${this.config.userIdPrefix}${sessionId}` } : {}),
251
- request_id: requestId,
252
- agent_id: request?.agentId ?? session?.agentId,
253
- app_id: this.config.appId,
254
- metadata: {
255
- source: "agent-harness",
256
- sessionId: sessionId,
257
- requestId: requestId,
258
- agentId: request?.agentId ?? session?.agentId,
259
- trigger,
260
- },
261
- });
262
- await this.stateStore.put(namespace, requestId, {
263
- fingerprint,
264
- messageCount: normalized.length,
265
- syncedAt: new Date().toISOString(),
266
- trigger,
267
- });
268
- }
269
- async close() {
270
- await Promise.allSettled(Array.from(this.pending));
271
- }
272
- }
273
- function toIsoString(value) {
274
- if (value instanceof Date && !Number.isNaN(value.getTime())) {
275
- return value.toISOString();
276
- }
277
- if (typeof value === "string" && value.trim().length > 0) {
278
- const parsed = new Date(value);
279
- return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();
280
- }
281
- return undefined;
282
- }
283
- export class Mem0SemanticRecall {
284
- config;
285
- clientFactory;
286
- clientPromise = null;
287
- constructor(config, clientFactory = createDefaultMem0Client) {
288
- this.config = config;
289
- this.clientFactory = clientFactory;
290
- }
291
- async getClient() {
292
- if (!this.clientPromise) {
293
- this.clientPromise = Promise.resolve(this.clientFactory(this.config));
294
- }
295
- return this.clientPromise;
296
- }
297
- async search(input) {
298
- if (input.query.trim().length === 0 || input.topK <= 0) {
299
- return [];
300
- }
301
- const client = await this.getClient();
302
- const records = await client.search(input.query, {
303
- top_k: input.topK,
304
- limit: input.topK,
305
- app_id: this.config.appId,
306
- ...(input.agentId ? { agent_id: input.agentId } : {}),
307
- ...(input.sessionId && this.config.userIdPrefix ? { user_id: `${this.config.userIdPrefix}${input.sessionId}` } : {}),
308
- });
309
- return records
310
- .map((record) => {
311
- const memory = typeof record.memory === "string" && record.memory.trim().length > 0
312
- ? record.memory.trim()
313
- : typeof record.data?.memory === "string" && record.data.memory.trim().length > 0
314
- ? record.data.memory.trim()
315
- : "";
316
- if (!memory) {
317
- return null;
318
- }
319
- const createdAt = toIsoString(record.created_at) ?? new Date(0).toISOString();
320
- const updatedAt = toIsoString(record.updated_at) ?? createdAt;
321
- return {
322
- id: typeof record.id === "string" && record.id.trim().length > 0 ? record.id : memory,
323
- memory,
324
- score: typeof record.score === "number" && Number.isFinite(record.score) ? record.score : 0,
325
- categories: Array.isArray(record.categories)
326
- ? record.categories.filter((item) => typeof item === "string" && item.trim().length > 0)
327
- : [],
328
- metadata: typeof record.metadata === "object" && record.metadata && !Array.isArray(record.metadata)
329
- ? { ...record.metadata }
330
- : {},
331
- createdAt,
332
- updatedAt,
333
- agentId: typeof record.agent_id === "string" && record.agent_id.trim().length > 0 ? record.agent_id : undefined,
334
- requestId: (() => {
335
- const requestId = record.request_id;
336
- if (typeof requestId === "string" && requestId.trim().length > 0) {
337
- return requestId;
338
- }
339
- return undefined;
340
- })(),
341
- };
342
- })
343
- .filter((record) => record !== null);
344
- }
345
- }
1
+ import{createHash as _}from"node:crypto";import h from"node:path";import{extractMessageText as p}from"../../../utils/message-content.js";import{FileBackedStore as q}from"./store.js";const x=new Set(["request.state.changed","approval.resolved"]);function g(t){return typeof t=="object"&&t&&!Array.isArray(t)?t:void 0}function a(t){return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function N(t){return typeof t=="number"&&Number.isInteger(t)&&t>0?t:void 0}function d(t){return typeof t=="boolean"?t:void 0}function C(t){const e=[];for(const n of t){const i=p(n.content).trim();i&&e.push({role:n.role,content:i})}return e}function R(t){const e=_("sha256");for(const n of t)e.update(n.role),e.update(`
2
+ `),e.update(n.createdAt),e.update(`
3
+ `),e.update(p(n.content)),e.update(`
4
+ ---
5
+ `);return e.digest("hex")}function F(t,e){if(t?.enabled!==!0)return;const n=g(t.mem0);if(!n||n.enabled!==!0)return;const i=g(t.ingestion),s=h.basename(e)||"agent-harness";return{enabled:!0,apiKeyEnv:a(n.apiKeyEnv)??"MEM0_API_KEY",host:a(n.host),organizationName:a(n.organizationName),projectName:a(n.projectName),organizationId:a(n.organizationId),projectId:a(n.projectId),appId:a(n.appId)??s,userIdPrefix:a(n.userIdPrefix),stateStorePath:a(n.stateStorePath)??"knowledge/mem0-sync-state.json",maxMessagesPerRequest:N(n.maxMessagesPerRequest)??200,writeOnApprovalResolution:d(n.writeOnApprovalResolution)??d(i?.writeOnApprovalResolution)??!0,writeOnRequestCompletion:d(n.writeOnRequestCompletion)??d(i?.writeOnRequestCompletion)??!0}}async function f(t){const e=process.env[t.apiKeyEnv]?.trim();if(!e&&t.host)return E(t);if(!e)throw new Error(`runtimeMemory.mem0 is enabled but environment variable ${t.apiKeyEnv} is not set`);return j(t,e)}function y(t){return t.replace(/\/+$/,"")}function S(t){return{"Content-Type":"application/json",...t?{Authorization:`Token ${t}`}:{}}}async function I(t,e,n={}){if(!t.host)throw new Error("Self-hosted mem0 client requires runtimeMemory.mem0.host.");const i=await fetch(`${y(t.host)}${e}`,{method:n.method??"GET",headers:S(),...n.body?{body:JSON.stringify(n.body)}:{}});if(!i.ok)throw new Error(`Self-hosted mem0 request failed: ${i.status} ${i.statusText}`);return i.json()}function T(t,e){const n={...t};return e.organizationName&&e.projectName&&(n.org_name=e.organizationName,n.project_name=e.projectName),e.organizationId&&e.projectId&&(n.org_id=e.organizationId,n.project_id=e.projectId,delete n.org_name,delete n.project_name),n}async function w(t,e,n,i={}){const s=y(t.host??"https://api.mem0.ai"),r=await fetch(`${s}${n}`,{method:i.method??"GET",headers:S(e),...i.body?{body:JSON.stringify(T(i.body,t))}:{}});if(!r.ok)throw new Error(`Mem0 request failed: ${r.status} ${r.statusText}`);return r.json()}function j(t,e){return{async add(n,i={}){return w(t,e,"/v1/memories/",{method:"POST",body:{messages:n,...i}})},async search(n,i={}){return w(t,e,"/v1/memories/search/",{method:"POST",body:{query:n,...i}})}}}function E(t){return{async add(e,n={}){return I(t,"/v1/memories/",{method:"POST",body:{messages:e,...n}})},async search(e,n={}){return I(t,"/v1/memories/search/",{method:"POST",body:{query:e,...n}})}}}class H{persistence;config;runtimeRoot;stateStore;clientFactory;pending=new Set;syncChain=Promise.resolve();clientPromise=null;name="mem0-ingestion-sync";constructor(e,n,i,s=new q(h.join(i,n.stateStorePath)),r=f){this.persistence=e,this.config=n,this.runtimeRoot=i,this.stateStore=s,this.clientFactory=r}shouldHandle(e){return x.has(e.eventType)?e.eventType==="approval.resolved"?this.config.writeOnApprovalResolution:e.eventType==="request.state.changed"?this.config.writeOnRequestCompletion&&e.payload.state==="completed":!1:!1}async handleEvent(e){if(!this.shouldHandle(e))return;const n=e.eventType==="approval.resolved"?"approval.resolved":"request.completed",i=this.syncChain.then(()=>this.syncRun(e.sessionId,e.requestId,n)).catch(()=>{});this.syncChain=i.catch(()=>{}).finally(()=>{this.pending.delete(i)}),this.pending.add(i)}async getClient(){return this.clientPromise||(this.clientPromise=Promise.resolve(this.clientFactory(this.config))),this.clientPromise}async syncRun(e,n,i){const r=(await this.persistence.listSessionMessages(e,this.config.maxMessagesPerRequest)).filter(M=>M.requestId===n),m=C(r);if(m.length===0)return;const c=R(r),o=["mem0","sessions",e,"requests"];if((await this.stateStore.get(o,n))?.value?.fingerprint===c)return;const[u,l,b]=await Promise.all([this.persistence.getSession(e),this.persistence.getRequest(n),this.getClient()]);await b.add(m,{...this.config.userIdPrefix?{user_id:`${this.config.userIdPrefix}${e}`}:{},request_id:n,agent_id:l?.agentId??u?.agentId,app_id:this.config.appId,metadata:{source:"agent-harness",sessionId:e,requestId:n,agentId:l?.agentId??u?.agentId,trigger:i}}),await this.stateStore.put(o,n,{fingerprint:c,messageCount:m.length,syncedAt:new Date().toISOString(),trigger:i})}async close(){await Promise.allSettled(Array.from(this.pending))}}function P(t){if(t instanceof Date&&!Number.isNaN(t.getTime()))return t.toISOString();if(typeof t=="string"&&t.trim().length>0){const e=new Date(t);return Number.isNaN(e.getTime())?void 0:e.toISOString()}}class K{config;clientFactory;clientPromise=null;constructor(e,n=f){this.config=e,this.clientFactory=n}async getClient(){return this.clientPromise||(this.clientPromise=Promise.resolve(this.clientFactory(this.config))),this.clientPromise}async search(e){return e.query.trim().length===0||e.topK<=0?[]:(await(await this.getClient()).search(e.query,{top_k:e.topK,limit:e.topK,app_id:this.config.appId,...e.agentId?{agent_id:e.agentId}:{},...e.sessionId&&this.config.userIdPrefix?{user_id:`${this.config.userIdPrefix}${e.sessionId}`}:{}})).map(s=>{const r=typeof s.memory=="string"&&s.memory.trim().length>0?s.memory.trim():typeof s.data?.memory=="string"&&s.data.memory.trim().length>0?s.data.memory.trim():"";if(!r)return null;const m=P(s.created_at)??new Date(0).toISOString(),c=P(s.updated_at)??m;return{id:typeof s.id=="string"&&s.id.trim().length>0?s.id:r,memory:r,score:typeof s.score=="number"&&Number.isFinite(s.score)?s.score:0,categories:Array.isArray(s.categories)?s.categories.filter(o=>typeof o=="string"&&o.trim().length>0):[],metadata:typeof s.metadata=="object"&&s.metadata&&!Array.isArray(s.metadata)?{...s.metadata}:{},createdAt:m,updatedAt:c,agentId:typeof s.agent_id=="string"&&s.agent_id.trim().length>0?s.agent_id:void 0,requestId:(()=>{const o=s.request_id;if(typeof o=="string"&&o.trim().length>0)return o})()}}).filter(s=>s!==null)}}export{H as Mem0IngestionSync,K as Mem0SemanticRecall,F as readMem0RuntimeConfig};