@agentmemory/agentmemory 0.7.0

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 (259) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.github/workflows/ci.yml +22 -0
  3. package/.github/workflows/publish.yml +28 -0
  4. package/AGENTS.md +113 -0
  5. package/LICENSE +190 -0
  6. package/README.md +828 -0
  7. package/assets/banner.png +0 -0
  8. package/assets/demo.gif +0 -0
  9. package/assets/demo.mp4 +0 -0
  10. package/benchmark/QUALITY.md +73 -0
  11. package/benchmark/REAL-EMBEDDINGS.md +67 -0
  12. package/benchmark/SCALE.md +110 -0
  13. package/benchmark/dataset.ts +293 -0
  14. package/benchmark/quality-eval.ts +643 -0
  15. package/benchmark/real-embeddings-eval.ts +405 -0
  16. package/benchmark/scale-eval.ts +398 -0
  17. package/dist/cli.d.mts +1 -0
  18. package/dist/cli.mjs +137 -0
  19. package/dist/cli.mjs.map +1 -0
  20. package/dist/docker-compose.yml +14 -0
  21. package/dist/hooks/notification.d.mts +1 -0
  22. package/dist/hooks/notification.mjs +45 -0
  23. package/dist/hooks/notification.mjs.map +1 -0
  24. package/dist/hooks/post-tool-failure.d.mts +1 -0
  25. package/dist/hooks/post-tool-failure.mjs +45 -0
  26. package/dist/hooks/post-tool-failure.mjs.map +1 -0
  27. package/dist/hooks/post-tool-use.d.mts +1 -0
  28. package/dist/hooks/post-tool-use.mjs +53 -0
  29. package/dist/hooks/post-tool-use.mjs.map +1 -0
  30. package/dist/hooks/pre-compact.d.mts +1 -0
  31. package/dist/hooks/pre-compact.mjs +50 -0
  32. package/dist/hooks/pre-compact.mjs.map +1 -0
  33. package/dist/hooks/pre-tool-use.d.mts +1 -0
  34. package/dist/hooks/pre-tool-use.mjs +69 -0
  35. package/dist/hooks/pre-tool-use.mjs.map +1 -0
  36. package/dist/hooks/prompt-submit.d.mts +1 -0
  37. package/dist/hooks/prompt-submit.mjs +40 -0
  38. package/dist/hooks/prompt-submit.mjs.map +1 -0
  39. package/dist/hooks/session-end.d.mts +1 -0
  40. package/dist/hooks/session-end.mjs +61 -0
  41. package/dist/hooks/session-end.mjs.map +1 -0
  42. package/dist/hooks/session-start.d.mts +1 -0
  43. package/dist/hooks/session-start.mjs +42 -0
  44. package/dist/hooks/session-start.mjs.map +1 -0
  45. package/dist/hooks/stop.d.mts +1 -0
  46. package/dist/hooks/stop.mjs +33 -0
  47. package/dist/hooks/stop.mjs.map +1 -0
  48. package/dist/hooks/subagent-start.d.mts +1 -0
  49. package/dist/hooks/subagent-start.mjs +43 -0
  50. package/dist/hooks/subagent-start.mjs.map +1 -0
  51. package/dist/hooks/subagent-stop.d.mts +1 -0
  52. package/dist/hooks/subagent-stop.mjs +45 -0
  53. package/dist/hooks/subagent-stop.mjs.map +1 -0
  54. package/dist/hooks/task-completed.d.mts +1 -0
  55. package/dist/hooks/task-completed.mjs +46 -0
  56. package/dist/hooks/task-completed.mjs.map +1 -0
  57. package/dist/iii-config.yaml +51 -0
  58. package/dist/index.d.mts +2 -0
  59. package/dist/index.mjs +13776 -0
  60. package/dist/index.mjs.map +1 -0
  61. package/dist/src-QxitMPfJ.mjs +13775 -0
  62. package/dist/src-QxitMPfJ.mjs.map +1 -0
  63. package/dist/standalone.d.mts +1 -0
  64. package/dist/standalone.mjs +1155 -0
  65. package/dist/standalone.mjs.map +1 -0
  66. package/dist/transformers-BX_tgxdO.mjs +38684 -0
  67. package/dist/transformers-BX_tgxdO.mjs.map +1 -0
  68. package/dist/transformers-KMm1i9no.mjs +38683 -0
  69. package/dist/transformers-KMm1i9no.mjs.map +1 -0
  70. package/docker-compose.yml +14 -0
  71. package/iii-config.yaml +51 -0
  72. package/package.json +59 -0
  73. package/plugin/.claude-plugin/plugin.json +10 -0
  74. package/plugin/hooks/hooks.json +77 -0
  75. package/plugin/scripts/diagnostics.mjs +551 -0
  76. package/plugin/scripts/notification.mjs +45 -0
  77. package/plugin/scripts/post-tool-failure.mjs +45 -0
  78. package/plugin/scripts/post-tool-use.mjs +53 -0
  79. package/plugin/scripts/pre-compact.mjs +50 -0
  80. package/plugin/scripts/pre-tool-use.mjs +69 -0
  81. package/plugin/scripts/prompt-submit.mjs +40 -0
  82. package/plugin/scripts/session-end.mjs +61 -0
  83. package/plugin/scripts/session-start.mjs +42 -0
  84. package/plugin/scripts/stop.mjs +33 -0
  85. package/plugin/scripts/subagent-start.mjs +43 -0
  86. package/plugin/scripts/subagent-stop.mjs +45 -0
  87. package/plugin/scripts/task-completed.mjs +46 -0
  88. package/plugin/skills/forget/SKILL.md +32 -0
  89. package/plugin/skills/recall/SKILL.md +18 -0
  90. package/plugin/skills/remember/SKILL.md +25 -0
  91. package/plugin/skills/session-history/SKILL.md +17 -0
  92. package/src/auth.ts +12 -0
  93. package/src/cli.ts +159 -0
  94. package/src/config.ts +221 -0
  95. package/src/eval/metrics-store.ts +65 -0
  96. package/src/eval/quality.ts +51 -0
  97. package/src/eval/schemas.ts +124 -0
  98. package/src/eval/self-correct.ts +28 -0
  99. package/src/eval/validator.ts +31 -0
  100. package/src/functions/actions.ts +288 -0
  101. package/src/functions/audit.ts +61 -0
  102. package/src/functions/auto-forget.ts +169 -0
  103. package/src/functions/branch-aware.ts +169 -0
  104. package/src/functions/cascade.ts +80 -0
  105. package/src/functions/checkpoints.ts +209 -0
  106. package/src/functions/claude-bridge.ts +161 -0
  107. package/src/functions/compress.ts +194 -0
  108. package/src/functions/consolidate.ts +212 -0
  109. package/src/functions/consolidation-pipeline.ts +258 -0
  110. package/src/functions/context.ts +169 -0
  111. package/src/functions/crystallize.ts +293 -0
  112. package/src/functions/dedup.ts +57 -0
  113. package/src/functions/diagnostics.ts +785 -0
  114. package/src/functions/enrich.ts +132 -0
  115. package/src/functions/evict.ts +163 -0
  116. package/src/functions/export-import.ts +508 -0
  117. package/src/functions/facets.ts +248 -0
  118. package/src/functions/file-index.ts +106 -0
  119. package/src/functions/flow-compress.ts +214 -0
  120. package/src/functions/frontier.ts +196 -0
  121. package/src/functions/governance.ts +131 -0
  122. package/src/functions/graph-retrieval.ts +277 -0
  123. package/src/functions/graph.ts +275 -0
  124. package/src/functions/leases.ts +216 -0
  125. package/src/functions/lessons.ts +253 -0
  126. package/src/functions/mesh.ts +434 -0
  127. package/src/functions/migrate.ts +165 -0
  128. package/src/functions/observe.ts +144 -0
  129. package/src/functions/obsidian-export.ts +310 -0
  130. package/src/functions/patterns.ts +138 -0
  131. package/src/functions/privacy.ts +39 -0
  132. package/src/functions/profile.ts +155 -0
  133. package/src/functions/query-expansion.ts +186 -0
  134. package/src/functions/relations.ts +237 -0
  135. package/src/functions/remember.ts +162 -0
  136. package/src/functions/retention.ts +235 -0
  137. package/src/functions/routines.ts +289 -0
  138. package/src/functions/search.ts +80 -0
  139. package/src/functions/sentinels.ts +417 -0
  140. package/src/functions/signals.ts +186 -0
  141. package/src/functions/sketches.ts +274 -0
  142. package/src/functions/sliding-window.ts +257 -0
  143. package/src/functions/smart-search.ts +115 -0
  144. package/src/functions/snapshot.ts +219 -0
  145. package/src/functions/summarize.ts +155 -0
  146. package/src/functions/team.ts +147 -0
  147. package/src/functions/temporal-graph.ts +476 -0
  148. package/src/functions/timeline.ts +138 -0
  149. package/src/functions/verify.ts +117 -0
  150. package/src/health/monitor.ts +110 -0
  151. package/src/health/thresholds.ts +73 -0
  152. package/src/hooks/notification.ts +52 -0
  153. package/src/hooks/post-tool-failure.ts +58 -0
  154. package/src/hooks/post-tool-use.ts +62 -0
  155. package/src/hooks/pre-compact.ts +60 -0
  156. package/src/hooks/pre-tool-use.ts +72 -0
  157. package/src/hooks/prompt-submit.ts +46 -0
  158. package/src/hooks/session-end.ts +71 -0
  159. package/src/hooks/session-start.ts +48 -0
  160. package/src/hooks/stop.ts +39 -0
  161. package/src/hooks/subagent-start.ts +49 -0
  162. package/src/hooks/subagent-stop.ts +54 -0
  163. package/src/hooks/task-completed.ts +54 -0
  164. package/src/index.ts +342 -0
  165. package/src/mcp/in-memory-kv.ts +61 -0
  166. package/src/mcp/server.ts +1455 -0
  167. package/src/mcp/standalone.ts +177 -0
  168. package/src/mcp/tools-registry.ts +769 -0
  169. package/src/mcp/transport.ts +91 -0
  170. package/src/prompts/compression.ts +67 -0
  171. package/src/prompts/consolidation.ts +48 -0
  172. package/src/prompts/graph-extraction.ts +35 -0
  173. package/src/prompts/summary.ts +38 -0
  174. package/src/prompts/xml.ts +26 -0
  175. package/src/providers/agent-sdk.ts +34 -0
  176. package/src/providers/anthropic.ts +35 -0
  177. package/src/providers/circuit-breaker.ts +82 -0
  178. package/src/providers/embedding/cohere.ts +46 -0
  179. package/src/providers/embedding/gemini.ts +54 -0
  180. package/src/providers/embedding/index.ts +39 -0
  181. package/src/providers/embedding/local.ts +52 -0
  182. package/src/providers/embedding/openai.ts +45 -0
  183. package/src/providers/embedding/openrouter.ts +51 -0
  184. package/src/providers/embedding/voyage.ts +46 -0
  185. package/src/providers/fallback-chain.ts +31 -0
  186. package/src/providers/index.ts +84 -0
  187. package/src/providers/openrouter.ts +71 -0
  188. package/src/providers/resilient.ts +37 -0
  189. package/src/state/hybrid-search.ts +295 -0
  190. package/src/state/index-persistence.ts +63 -0
  191. package/src/state/keyed-mutex.ts +18 -0
  192. package/src/state/kv.ts +33 -0
  193. package/src/state/schema.ts +71 -0
  194. package/src/state/search-index.ts +245 -0
  195. package/src/state/stemmer.ts +104 -0
  196. package/src/state/synonyms.ts +63 -0
  197. package/src/state/vector-index.ts +130 -0
  198. package/src/telemetry/setup.ts +116 -0
  199. package/src/triggers/api.ts +1904 -0
  200. package/src/triggers/events.ts +71 -0
  201. package/src/types.ts +769 -0
  202. package/src/version.ts +1 -0
  203. package/src/viewer/index.html +2497 -0
  204. package/src/viewer/server.ts +207 -0
  205. package/src/xenova.d.ts +3 -0
  206. package/test/actions.test.ts +490 -0
  207. package/test/audit.test.ts +108 -0
  208. package/test/auto-forget.test.ts +188 -0
  209. package/test/cascade.test.ts +277 -0
  210. package/test/checkpoints.test.ts +493 -0
  211. package/test/circuit-breaker.test.ts +107 -0
  212. package/test/claude-bridge.test.ts +178 -0
  213. package/test/confidence.test.ts +247 -0
  214. package/test/consistency.test.ts +61 -0
  215. package/test/consolidation-pipeline.test.ts +251 -0
  216. package/test/crystallize.test.ts +521 -0
  217. package/test/diagnostics.test.ts +638 -0
  218. package/test/embedding-provider.test.ts +49 -0
  219. package/test/enrich.test.ts +209 -0
  220. package/test/eval.test.ts +300 -0
  221. package/test/export-import.test.ts +251 -0
  222. package/test/facets.test.ts +448 -0
  223. package/test/fallback-chain.test.ts +93 -0
  224. package/test/frontier.test.ts +485 -0
  225. package/test/governance.test.ts +147 -0
  226. package/test/graph-retrieval.test.ts +186 -0
  227. package/test/graph.test.ts +160 -0
  228. package/test/helpers/mocks.ts +40 -0
  229. package/test/hybrid-search.test.ts +145 -0
  230. package/test/index-persistence.test.ts +124 -0
  231. package/test/integration.test.ts +265 -0
  232. package/test/leases.test.ts +399 -0
  233. package/test/mcp-prompts.test.ts +218 -0
  234. package/test/mcp-resources.test.ts +286 -0
  235. package/test/mcp-standalone.test.ts +113 -0
  236. package/test/mesh.test.ts +700 -0
  237. package/test/privacy.test.ts +87 -0
  238. package/test/profile.test.ts +161 -0
  239. package/test/query-expansion.test.ts +154 -0
  240. package/test/relations.test.ts +198 -0
  241. package/test/retention.test.ts +245 -0
  242. package/test/routines.test.ts +497 -0
  243. package/test/schema-fingerprint.test.ts +81 -0
  244. package/test/schema.test.ts +42 -0
  245. package/test/search-index.test.ts +128 -0
  246. package/test/sentinels.test.ts +626 -0
  247. package/test/signals.test.ts +410 -0
  248. package/test/sketches.test.ts +549 -0
  249. package/test/sliding-window.test.ts +199 -0
  250. package/test/smart-search.test.ts +169 -0
  251. package/test/snapshot.test.ts +165 -0
  252. package/test/team.test.ts +156 -0
  253. package/test/temporal-graph.test.ts +378 -0
  254. package/test/timeline.test.ts +148 -0
  255. package/test/vector-index.test.ts +79 -0
  256. package/test/verify.test.ts +209 -0
  257. package/test/xml.test.ts +65 -0
  258. package/tsconfig.json +22 -0
  259. package/tsdown.config.ts +62 -0
@@ -0,0 +1,275 @@
1
+ import type { ISdk } from "iii-sdk";
2
+ import { getContext } from "iii-sdk";
3
+ import type {
4
+ GraphNode,
5
+ GraphEdge,
6
+ GraphQueryResult,
7
+ CompressedObservation,
8
+ MemoryProvider,
9
+ } from "../types.js";
10
+ import { KV, generateId } from "../state/schema.js";
11
+ import type { StateKV } from "../state/kv.js";
12
+ import {
13
+ GRAPH_EXTRACTION_SYSTEM,
14
+ buildGraphExtractionPrompt,
15
+ } from "../prompts/graph-extraction.js";
16
+ import { recordAudit } from "./audit.js";
17
+
18
+ function parseGraphXml(
19
+ xml: string,
20
+ observationIds: string[],
21
+ ): {
22
+ nodes: GraphNode[];
23
+ edges: GraphEdge[];
24
+ } {
25
+ const nodes: GraphNode[] = [];
26
+ const edges: GraphEdge[] = [];
27
+ const now = new Date().toISOString();
28
+
29
+ const entityRegex =
30
+ /<entity\s+type="([^"]+)"\s+name="([^"]+)"[^>]*>([\s\S]*?)<\/entity>/g;
31
+ let match;
32
+ while ((match = entityRegex.exec(xml)) !== null) {
33
+ const type = match[1] as GraphNode["type"];
34
+ const name = match[2];
35
+ const propsBlock = match[3];
36
+ const properties: Record<string, string> = {};
37
+
38
+ const propRegex = /<property\s+key="([^"]+)">([^<]*)<\/property>/g;
39
+ let propMatch;
40
+ while ((propMatch = propRegex.exec(propsBlock)) !== null) {
41
+ properties[propMatch[1]] = propMatch[2];
42
+ }
43
+
44
+ nodes.push({
45
+ id: generateId("gn"),
46
+ type,
47
+ name,
48
+ properties,
49
+ sourceObservationIds: observationIds,
50
+ createdAt: now,
51
+ });
52
+ }
53
+
54
+ const relRegex =
55
+ /<relationship\s+type="([^"]+)"\s+source="([^"]+)"\s+target="([^"]+)"\s+weight="([^"]+)"\s*\/>/g;
56
+ while ((match = relRegex.exec(xml)) !== null) {
57
+ const type = match[1] as GraphEdge["type"];
58
+ const sourceName = match[2];
59
+ const targetName = match[3];
60
+ const parsedWeight = parseFloat(match[4]);
61
+ const weight = Number.isNaN(parsedWeight) ? 0.5 : parsedWeight;
62
+
63
+ const sourceNode = nodes.find((n) => n.name === sourceName);
64
+ const targetNode = nodes.find((n) => n.name === targetName);
65
+
66
+ if (sourceNode && targetNode) {
67
+ edges.push({
68
+ id: generateId("ge"),
69
+ type,
70
+ sourceNodeId: sourceNode.id,
71
+ targetNodeId: targetNode.id,
72
+ weight: Math.max(0, Math.min(1, weight)),
73
+ sourceObservationIds: observationIds,
74
+ createdAt: now,
75
+ });
76
+ }
77
+ }
78
+
79
+ return { nodes, edges };
80
+ }
81
+
82
+ export function registerGraphFunction(
83
+ sdk: ISdk,
84
+ kv: StateKV,
85
+ provider: MemoryProvider,
86
+ ): void {
87
+ sdk.registerFunction(
88
+ { id: "mem::graph-extract" },
89
+ async (data: { observations: CompressedObservation[] }) => {
90
+ const ctx = getContext();
91
+ if (!data.observations || data.observations.length === 0) {
92
+ return { success: false, error: "No observations provided" };
93
+ }
94
+
95
+ const prompt = buildGraphExtractionPrompt(
96
+ data.observations.map((o) => ({
97
+ title: o.title,
98
+ narrative: o.narrative,
99
+ concepts: o.concepts,
100
+ files: o.files,
101
+ type: o.type,
102
+ })),
103
+ );
104
+
105
+ try {
106
+ const response = await provider.compress(
107
+ GRAPH_EXTRACTION_SYSTEM,
108
+ prompt,
109
+ );
110
+
111
+ const obsIds = data.observations.map((o) => o.id);
112
+ const { nodes, edges } = parseGraphXml(response, obsIds);
113
+
114
+ const existingNodes = await kv.list<GraphNode>(KV.graphNodes);
115
+ const existingEdges = await kv.list<GraphEdge>(KV.graphEdges);
116
+
117
+ for (const node of nodes) {
118
+ const existing = existingNodes.find(
119
+ (n) => n.name === node.name && n.type === node.type,
120
+ );
121
+ if (existing) {
122
+ const merged = {
123
+ ...existing,
124
+ sourceObservationIds: [
125
+ ...new Set([...existing.sourceObservationIds, ...obsIds]),
126
+ ],
127
+ properties: { ...existing.properties, ...node.properties },
128
+ };
129
+ await kv.set(KV.graphNodes, existing.id, merged);
130
+ const idx = existingNodes.findIndex((n) => n.id === existing.id);
131
+ if (idx !== -1) existingNodes[idx] = merged;
132
+ } else {
133
+ await kv.set(KV.graphNodes, node.id, node);
134
+ existingNodes.push(node);
135
+ }
136
+ }
137
+
138
+ for (const edge of edges) {
139
+ const edgeKey = `${edge.sourceNodeId}|${edge.targetNodeId}|${edge.type}`;
140
+ const existingEdge = existingEdges.find(
141
+ (e) => `${e.sourceNodeId}|${e.targetNodeId}|${e.type}` === edgeKey,
142
+ );
143
+ if (existingEdge) {
144
+ existingEdge.sourceObservationIds = [
145
+ ...new Set([...existingEdge.sourceObservationIds, ...obsIds]),
146
+ ];
147
+ await kv.set(KV.graphEdges, existingEdge.id, existingEdge);
148
+ } else {
149
+ await kv.set(KV.graphEdges, edge.id, edge);
150
+ existingEdges.push(edge);
151
+ }
152
+ }
153
+
154
+ await recordAudit(kv, "observe", "mem::graph-extract", obsIds, {
155
+ nodesExtracted: nodes.length,
156
+ edgesExtracted: edges.length,
157
+ });
158
+
159
+ ctx.logger.info("Graph extraction complete", {
160
+ nodes: nodes.length,
161
+ edges: edges.length,
162
+ });
163
+ return {
164
+ success: true,
165
+ nodesAdded: nodes.length,
166
+ edgesAdded: edges.length,
167
+ };
168
+ } catch (err) {
169
+ const msg = err instanceof Error ? err.message : String(err);
170
+ ctx.logger.error("Graph extraction failed", { error: msg });
171
+ return { success: false, error: msg };
172
+ }
173
+ },
174
+ );
175
+
176
+ sdk.registerFunction(
177
+ { id: "mem::graph-query" },
178
+ async (data: {
179
+ startNodeId?: string;
180
+ nodeType?: string;
181
+ maxDepth?: number;
182
+ query?: string;
183
+ }): Promise<GraphQueryResult> => {
184
+ const allNodes = (await kv.list<GraphNode>(KV.graphNodes)).filter((n) => !n.stale);
185
+ const allEdges = (await kv.list<GraphEdge>(KV.graphEdges)).filter((e) => !e.stale);
186
+ const maxDepth = Math.min(data.maxDepth || 3, 5);
187
+
188
+ if (data.query) {
189
+ const lower = data.query.toLowerCase();
190
+ const matchingNodes = allNodes.filter(
191
+ (n) =>
192
+ n.name.toLowerCase().includes(lower) ||
193
+ Object.values(n.properties).some(
194
+ (v) => typeof v === "string" && v.toLowerCase().includes(lower),
195
+ ),
196
+ );
197
+ const nodeIds = new Set(matchingNodes.map((n) => n.id));
198
+ const relatedEdges = allEdges.filter(
199
+ (e) => nodeIds.has(e.sourceNodeId) || nodeIds.has(e.targetNodeId),
200
+ );
201
+ return { nodes: matchingNodes, edges: relatedEdges, depth: 0 };
202
+ }
203
+
204
+ if (data.startNodeId) {
205
+ const visited = new Set<string>();
206
+ const visitedEdges = new Set<string>();
207
+ const resultNodes: GraphNode[] = [];
208
+ const resultEdges: GraphEdge[] = [];
209
+ const queue: Array<{ nodeId: string; depth: number }> = [
210
+ { nodeId: data.startNodeId, depth: 0 },
211
+ ];
212
+
213
+ while (queue.length > 0) {
214
+ const { nodeId, depth } = queue.shift()!;
215
+ if (visited.has(nodeId) || depth > maxDepth) continue;
216
+ visited.add(nodeId);
217
+
218
+ const node = allNodes.find((n) => n.id === nodeId);
219
+ if (node) {
220
+ if (!data.nodeType || node.type === data.nodeType) {
221
+ resultNodes.push(node);
222
+ }
223
+ }
224
+
225
+ const neighborEdges = allEdges.filter(
226
+ (e) => e.sourceNodeId === nodeId || e.targetNodeId === nodeId,
227
+ );
228
+ for (const edge of neighborEdges) {
229
+ if (!visitedEdges.has(edge.id)) {
230
+ visitedEdges.add(edge.id);
231
+ resultEdges.push(edge);
232
+ }
233
+ const nextId =
234
+ edge.sourceNodeId === nodeId
235
+ ? edge.targetNodeId
236
+ : edge.sourceNodeId;
237
+ if (!visited.has(nextId)) {
238
+ queue.push({ nodeId: nextId, depth: depth + 1 });
239
+ }
240
+ }
241
+ }
242
+
243
+ return { nodes: resultNodes, edges: resultEdges, depth: maxDepth };
244
+ }
245
+
246
+ let filtered = allNodes;
247
+ if (data.nodeType) {
248
+ filtered = allNodes.filter((n) => n.type === data.nodeType);
249
+ }
250
+ return { nodes: filtered, edges: allEdges, depth: 0 };
251
+ },
252
+ );
253
+
254
+ sdk.registerFunction({ id: "mem::graph-stats" }, async () => {
255
+ const nodes = await kv.list<GraphNode>(KV.graphNodes);
256
+ const edges = await kv.list<GraphEdge>(KV.graphEdges);
257
+
258
+ const nodesByType: Record<string, number> = {};
259
+ for (const n of nodes) {
260
+ nodesByType[n.type] = (nodesByType[n.type] || 0) + 1;
261
+ }
262
+
263
+ const edgesByType: Record<string, number> = {};
264
+ for (const e of edges) {
265
+ edgesByType[e.type] = (edgesByType[e.type] || 0) + 1;
266
+ }
267
+
268
+ return {
269
+ totalNodes: nodes.length,
270
+ totalEdges: edges.length,
271
+ nodesByType,
272
+ edgesByType,
273
+ };
274
+ });
275
+ }
@@ -0,0 +1,216 @@
1
+ import type { ISdk } from "iii-sdk";
2
+ import type { StateKV } from "../state/kv.js";
3
+ import { KV, generateId } from "../state/schema.js";
4
+ import { withKeyedLock } from "../state/keyed-mutex.js";
5
+ import type { Action, Lease } from "../types.js";
6
+
7
+ const DEFAULT_LEASE_TTL_MS = 10 * 60 * 1000;
8
+ const MAX_LEASE_TTL_MS = 60 * 60 * 1000;
9
+
10
+ export function registerLeasesFunction(sdk: ISdk, kv: StateKV): void {
11
+ sdk.registerFunction(
12
+ { id: "mem::lease-acquire" },
13
+ async (data: { actionId: string; agentId: string; ttlMs?: number }) => {
14
+ if (!data.actionId || !data.agentId) {
15
+ return { success: false, error: "actionId and agentId are required" };
16
+ }
17
+
18
+ const rawTtl = typeof data.ttlMs === "number" && Number.isFinite(data.ttlMs) && data.ttlMs > 0
19
+ ? data.ttlMs
20
+ : DEFAULT_LEASE_TTL_MS;
21
+ const ttl = Math.min(rawTtl, MAX_LEASE_TTL_MS);
22
+
23
+ return withKeyedLock(`mem:action:${data.actionId}`, async () => {
24
+ const action = await kv.get<Action>(KV.actions, data.actionId);
25
+ if (!action) {
26
+ return { success: false, error: "action not found" };
27
+ }
28
+ if (action.status === "done" || action.status === "cancelled") {
29
+ return { success: false, error: "action already completed" };
30
+ }
31
+ if (action.status === "blocked") {
32
+ return { success: false, error: "action is blocked" };
33
+ }
34
+
35
+ const existingLeases = await kv.list<Lease>(KV.leases);
36
+ const activeLease = existingLeases.find(
37
+ (l) =>
38
+ l.actionId === data.actionId &&
39
+ l.status === "active" &&
40
+ new Date(l.expiresAt).getTime() > Date.now(),
41
+ );
42
+
43
+ if (activeLease) {
44
+ if (activeLease.agentId === data.agentId) {
45
+ return {
46
+ success: true,
47
+ lease: activeLease,
48
+ renewed: false,
49
+ message: "Already holding this lease",
50
+ };
51
+ }
52
+ return {
53
+ success: false,
54
+ error: "action already leased",
55
+ heldBy: activeLease.agentId,
56
+ expiresAt: activeLease.expiresAt,
57
+ };
58
+ }
59
+
60
+ const now = new Date();
61
+ const lease: Lease = {
62
+ id: generateId("lse"),
63
+ actionId: data.actionId,
64
+ agentId: data.agentId,
65
+ acquiredAt: now.toISOString(),
66
+ expiresAt: new Date(now.getTime() + ttl).toISOString(),
67
+ status: "active",
68
+ };
69
+
70
+ await kv.set(KV.leases, lease.id, lease);
71
+
72
+ action.status = "active";
73
+ action.assignedTo = data.agentId;
74
+ action.updatedAt = now.toISOString();
75
+ await kv.set(KV.actions, action.id, action);
76
+
77
+ return { success: true, lease, renewed: false };
78
+ });
79
+ },
80
+ );
81
+
82
+ sdk.registerFunction(
83
+ { id: "mem::lease-release" },
84
+ async (data: { actionId: string; agentId: string; result?: string }) => {
85
+ if (!data.actionId || !data.agentId) {
86
+ return { success: false, error: "actionId and agentId are required" };
87
+ }
88
+
89
+ return withKeyedLock(`mem:action:${data.actionId}`, async () => {
90
+ const leases = await kv.list<Lease>(KV.leases);
91
+ const activeLease = leases.find(
92
+ (l) =>
93
+ l.actionId === data.actionId &&
94
+ l.agentId === data.agentId &&
95
+ l.status === "active" &&
96
+ new Date(l.expiresAt).getTime() > Date.now(),
97
+ );
98
+
99
+ if (!activeLease) {
100
+ return { success: false, error: "no active lease found for this agent" };
101
+ }
102
+
103
+ activeLease.status = "released";
104
+ await kv.set(KV.leases, activeLease.id, activeLease);
105
+
106
+ const action = await kv.get<Action>(KV.actions, data.actionId);
107
+ if (action && action.status === "active" && action.assignedTo === data.agentId) {
108
+ if (data.result) {
109
+ action.status = "done";
110
+ action.result = data.result;
111
+ } else {
112
+ action.status = "pending";
113
+ }
114
+ action.assignedTo = undefined;
115
+ action.updatedAt = new Date().toISOString();
116
+ await kv.set(KV.actions, action.id, action);
117
+ }
118
+
119
+ return { success: true, released: true };
120
+ });
121
+ },
122
+ );
123
+
124
+ sdk.registerFunction(
125
+ { id: "mem::lease-renew" },
126
+ async (data: { actionId: string; agentId: string; ttlMs?: number }) => {
127
+ if (!data.actionId || !data.agentId) {
128
+ return { success: false, error: "actionId and agentId are required" };
129
+ }
130
+
131
+ const rawTtl = typeof data.ttlMs === "number" && Number.isFinite(data.ttlMs) && data.ttlMs > 0
132
+ ? data.ttlMs
133
+ : DEFAULT_LEASE_TTL_MS;
134
+ const ttl = Math.min(rawTtl, MAX_LEASE_TTL_MS);
135
+
136
+ return withKeyedLock(`mem:action:${data.actionId}`, async () => {
137
+ const leases = await kv.list<Lease>(KV.leases);
138
+ const activeLease = leases.find(
139
+ (l) =>
140
+ l.actionId === data.actionId &&
141
+ l.agentId === data.agentId &&
142
+ l.status === "active" &&
143
+ new Date(l.expiresAt).getTime() > Date.now(),
144
+ );
145
+
146
+ if (!activeLease) {
147
+ return { success: false, error: "no active (non-expired) lease to renew" };
148
+ }
149
+
150
+ const now = new Date();
151
+ const base = Math.max(now.getTime(), new Date(activeLease.expiresAt).getTime());
152
+ activeLease.expiresAt = new Date(base + ttl).toISOString();
153
+ activeLease.renewedAt = now.toISOString();
154
+ await kv.set(KV.leases, activeLease.id, activeLease);
155
+
156
+ return { success: true, lease: activeLease };
157
+ });
158
+ },
159
+ );
160
+
161
+ sdk.registerFunction(
162
+ { id: "mem::lease-cleanup" },
163
+ async () => {
164
+ const leases = await kv.list<Lease>(KV.leases);
165
+ const now = Date.now();
166
+ let expired = 0;
167
+
168
+ for (const lease of leases) {
169
+ if (
170
+ lease.status === "active" &&
171
+ new Date(lease.expiresAt).getTime() <= now
172
+ ) {
173
+ const didExpire = await withKeyedLock(
174
+ `mem:action:${lease.actionId}`,
175
+ async () => {
176
+ const currentLease = await kv.get<Lease>(KV.leases, lease.id);
177
+ if (
178
+ !currentLease ||
179
+ currentLease.status !== "active" ||
180
+ new Date(currentLease.expiresAt).getTime() > Date.now()
181
+ ) {
182
+ return false;
183
+ }
184
+ currentLease.status = "expired";
185
+ await kv.set(KV.leases, currentLease.id, currentLease);
186
+
187
+ const action = await kv.get<Action>(KV.actions, currentLease.actionId);
188
+ const otherActiveLease = (await kv.list<Lease>(KV.leases)).some(
189
+ (l) =>
190
+ l.id !== currentLease.id &&
191
+ l.actionId === currentLease.actionId &&
192
+ l.status === "active" &&
193
+ new Date(l.expiresAt).getTime() > Date.now(),
194
+ );
195
+ if (
196
+ action &&
197
+ !otherActiveLease &&
198
+ action.status === "active" &&
199
+ action.assignedTo === currentLease.agentId
200
+ ) {
201
+ action.status = "pending";
202
+ action.assignedTo = undefined;
203
+ action.updatedAt = new Date().toISOString();
204
+ await kv.set(KV.actions, action.id, action);
205
+ }
206
+ return true;
207
+ },
208
+ );
209
+ if (didExpire) expired++;
210
+ }
211
+ }
212
+
213
+ return { success: true, expired };
214
+ },
215
+ );
216
+ }