@providerkit/agents 0.1.0 → 0.2.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 (291) hide show
  1. package/LICENSE-APACHE-2.0 +202 -0
  2. package/README.md +2108 -52
  3. package/THIRD_PARTY_NOTICES.md +521 -0
  4. package/dist/a2a/auth.d.ts +10 -0
  5. package/dist/a2a/auth.d.ts.map +1 -0
  6. package/dist/a2a/auth.js +52 -0
  7. package/dist/a2a/auth.js.map +1 -0
  8. package/dist/a2a/client.d.ts +74 -0
  9. package/dist/a2a/client.d.ts.map +1 -0
  10. package/dist/a2a/client.js +601 -0
  11. package/dist/a2a/client.js.map +1 -0
  12. package/dist/a2a/index.d.ts +22 -0
  13. package/dist/a2a/index.d.ts.map +1 -0
  14. package/dist/a2a/index.js +11 -0
  15. package/dist/a2a/index.js.map +1 -0
  16. package/dist/a2a/memory-runs.d.ts +62 -0
  17. package/dist/a2a/memory-runs.d.ts.map +1 -0
  18. package/dist/a2a/memory-runs.js +349 -0
  19. package/dist/a2a/memory-runs.js.map +1 -0
  20. package/dist/a2a/policy.d.ts +15 -0
  21. package/dist/a2a/policy.d.ts.map +1 -0
  22. package/dist/a2a/policy.js +114 -0
  23. package/dist/a2a/policy.js.map +1 -0
  24. package/dist/a2a/push.d.ts +34 -0
  25. package/dist/a2a/push.d.ts.map +1 -0
  26. package/dist/a2a/push.js +180 -0
  27. package/dist/a2a/push.js.map +1 -0
  28. package/dist/a2a/remote.d.ts +155 -0
  29. package/dist/a2a/remote.d.ts.map +1 -0
  30. package/dist/a2a/remote.js +1196 -0
  31. package/dist/a2a/remote.js.map +1 -0
  32. package/dist/a2a/server.d.ts +110 -0
  33. package/dist/a2a/server.d.ts.map +1 -0
  34. package/dist/a2a/server.js +1139 -0
  35. package/dist/a2a/server.js.map +1 -0
  36. package/dist/a2a/signing.d.ts +21 -0
  37. package/dist/a2a/signing.d.ts.map +1 -0
  38. package/dist/a2a/signing.js +305 -0
  39. package/dist/a2a/signing.js.map +1 -0
  40. package/dist/a2a/tasks.d.ts +88 -0
  41. package/dist/a2a/tasks.d.ts.map +1 -0
  42. package/dist/a2a/tasks.js +170 -0
  43. package/dist/a2a/tasks.js.map +1 -0
  44. package/dist/a2a/wire.d.ts +267 -0
  45. package/dist/a2a/wire.d.ts.map +1 -0
  46. package/dist/a2a/wire.js +1202 -0
  47. package/dist/a2a/wire.js.map +1 -0
  48. package/dist/background-types.d.ts +76 -0
  49. package/dist/background-types.d.ts.map +1 -0
  50. package/dist/background-types.js +2 -0
  51. package/dist/background-types.js.map +1 -0
  52. package/dist/child.d.ts +25 -0
  53. package/dist/child.d.ts.map +1 -0
  54. package/dist/child.js +129 -0
  55. package/dist/child.js.map +1 -0
  56. package/dist/code-driver.d.ts +40 -0
  57. package/dist/code-driver.d.ts.map +1 -0
  58. package/dist/code-driver.js +2 -0
  59. package/dist/code-driver.js.map +1 -0
  60. package/dist/code-mode.d.ts +3 -0
  61. package/dist/code-mode.d.ts.map +1 -0
  62. package/dist/code-mode.js +2 -0
  63. package/dist/code-mode.js.map +1 -0
  64. package/dist/code-script.d.ts +3 -0
  65. package/dist/code-script.d.ts.map +1 -0
  66. package/dist/code-script.js +149 -0
  67. package/dist/code-script.js.map +1 -0
  68. package/dist/code.d.ts +75 -0
  69. package/dist/code.d.ts.map +1 -0
  70. package/dist/code.js +326 -0
  71. package/dist/code.js.map +1 -0
  72. package/dist/compaction.d.ts +15 -0
  73. package/dist/compaction.d.ts.map +1 -0
  74. package/dist/compaction.js +168 -0
  75. package/dist/compaction.js.map +1 -0
  76. package/dist/delegation.d.ts +85 -16
  77. package/dist/delegation.d.ts.map +1 -1
  78. package/dist/delegation.js +240 -106
  79. package/dist/delegation.js.map +1 -1
  80. package/dist/evals/driver.d.ts +10 -0
  81. package/dist/evals/driver.d.ts.map +1 -0
  82. package/dist/evals/driver.js +192 -0
  83. package/dist/evals/driver.js.map +1 -0
  84. package/dist/evals/journal.d.ts +26 -0
  85. package/dist/evals/journal.d.ts.map +1 -0
  86. package/dist/evals/journal.js +483 -0
  87. package/dist/evals/journal.js.map +1 -0
  88. package/dist/evals/judge.d.ts +31 -0
  89. package/dist/evals/judge.d.ts.map +1 -0
  90. package/dist/evals/judge.js +142 -0
  91. package/dist/evals/judge.js.map +1 -0
  92. package/dist/evals/report.d.ts +38 -0
  93. package/dist/evals/report.d.ts.map +1 -0
  94. package/dist/evals/report.js +241 -0
  95. package/dist/evals/report.js.map +1 -0
  96. package/dist/evals/runner.d.ts +24 -0
  97. package/dist/evals/runner.d.ts.map +1 -0
  98. package/dist/evals/runner.js +655 -0
  99. package/dist/evals/runner.js.map +1 -0
  100. package/dist/evals/scorers.d.ts +36 -0
  101. package/dist/evals/scorers.d.ts.map +1 -0
  102. package/dist/evals/scorers.js +259 -0
  103. package/dist/evals/scorers.js.map +1 -0
  104. package/dist/evals/simulation.d.ts +7 -0
  105. package/dist/evals/simulation.d.ts.map +1 -0
  106. package/dist/evals/simulation.js +38 -0
  107. package/dist/evals/simulation.js.map +1 -0
  108. package/dist/evals/testing.d.ts +36 -0
  109. package/dist/evals/testing.d.ts.map +1 -0
  110. package/dist/evals/testing.js +87 -0
  111. package/dist/evals/testing.js.map +1 -0
  112. package/dist/evals/trajectory.d.ts +11 -0
  113. package/dist/evals/trajectory.d.ts.map +1 -0
  114. package/dist/evals/trajectory.js +180 -0
  115. package/dist/evals/trajectory.js.map +1 -0
  116. package/dist/evals/types.d.ts +431 -0
  117. package/dist/evals/types.d.ts.map +1 -0
  118. package/dist/evals/types.js +4 -0
  119. package/dist/evals/types.js.map +1 -0
  120. package/dist/evals.d.ts +14 -0
  121. package/dist/evals.d.ts.map +1 -0
  122. package/dist/evals.js +9 -0
  123. package/dist/evals.js.map +1 -0
  124. package/dist/extensions.d.ts +33 -0
  125. package/dist/extensions.d.ts.map +1 -0
  126. package/dist/extensions.js +188 -0
  127. package/dist/extensions.js.map +1 -0
  128. package/dist/handoff.d.ts +58 -0
  129. package/dist/handoff.d.ts.map +1 -0
  130. package/dist/handoff.js +160 -0
  131. package/dist/handoff.js.map +1 -0
  132. package/dist/index.d.ts +14 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +8 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/input.d.ts +42 -0
  137. package/dist/input.d.ts.map +1 -0
  138. package/dist/input.js +266 -0
  139. package/dist/input.js.map +1 -0
  140. package/dist/mcp.d.ts +77 -0
  141. package/dist/mcp.d.ts.map +1 -0
  142. package/dist/mcp.js +505 -0
  143. package/dist/mcp.js.map +1 -0
  144. package/dist/memory-store.d.ts +11 -0
  145. package/dist/memory-store.d.ts.map +1 -0
  146. package/dist/memory-store.js +272 -0
  147. package/dist/memory-store.js.map +1 -0
  148. package/dist/memory.d.ts +212 -0
  149. package/dist/memory.d.ts.map +1 -0
  150. package/dist/memory.js +613 -0
  151. package/dist/memory.js.map +1 -0
  152. package/dist/otel.d.ts +74 -0
  153. package/dist/otel.d.ts.map +1 -0
  154. package/dist/otel.js +427 -0
  155. package/dist/otel.js.map +1 -0
  156. package/dist/progress.d.ts +17 -0
  157. package/dist/progress.d.ts.map +1 -0
  158. package/dist/progress.js +193 -0
  159. package/dist/progress.js.map +1 -0
  160. package/dist/quickjs.d.ts +19 -0
  161. package/dist/quickjs.d.ts.map +1 -0
  162. package/dist/quickjs.js +519 -0
  163. package/dist/quickjs.js.map +1 -0
  164. package/dist/recovery.d.ts +10 -0
  165. package/dist/recovery.d.ts.map +1 -0
  166. package/dist/recovery.js +62 -0
  167. package/dist/recovery.js.map +1 -0
  168. package/dist/request.d.ts +88 -0
  169. package/dist/request.d.ts.map +1 -0
  170. package/dist/request.js +422 -0
  171. package/dist/request.js.map +1 -0
  172. package/dist/run.d.ts +16 -4
  173. package/dist/run.d.ts.map +1 -1
  174. package/dist/run.js +2016 -245
  175. package/dist/run.js.map +1 -1
  176. package/dist/runs.d.ts +77 -34
  177. package/dist/runs.d.ts.map +1 -1
  178. package/dist/runs.js +267 -85
  179. package/dist/runs.js.map +1 -1
  180. package/dist/schema-to-ts.d.ts +4 -0
  181. package/dist/schema-to-ts.d.ts.map +1 -0
  182. package/dist/schema-to-ts.js +191 -0
  183. package/dist/schema-to-ts.js.map +1 -0
  184. package/dist/session.d.ts +23 -0
  185. package/dist/session.d.ts.map +1 -0
  186. package/dist/session.js +137 -0
  187. package/dist/session.js.map +1 -0
  188. package/dist/snapshot.d.ts +57 -8
  189. package/dist/snapshot.d.ts.map +1 -1
  190. package/dist/snapshot.js +1206 -109
  191. package/dist/snapshot.js.map +1 -1
  192. package/dist/steering.d.ts +75 -0
  193. package/dist/steering.d.ts.map +1 -0
  194. package/dist/steering.js +214 -0
  195. package/dist/steering.js.map +1 -0
  196. package/dist/subagents.d.ts +141 -0
  197. package/dist/subagents.d.ts.map +1 -0
  198. package/dist/subagents.js +746 -0
  199. package/dist/subagents.js.map +1 -0
  200. package/dist/tool-retry.d.ts +12 -0
  201. package/dist/tool-retry.d.ts.map +1 -0
  202. package/dist/tool-retry.js +53 -0
  203. package/dist/tool-retry.js.map +1 -0
  204. package/dist/tree.d.ts +62 -6
  205. package/dist/tree.d.ts.map +1 -1
  206. package/dist/tree.js +192 -23
  207. package/dist/tree.js.map +1 -1
  208. package/dist/types.d.ts +767 -52
  209. package/dist/types.d.ts.map +1 -1
  210. package/dist/workflow-snapshot.d.ts +8 -0
  211. package/dist/workflow-snapshot.d.ts.map +1 -0
  212. package/dist/workflow-snapshot.js +276 -0
  213. package/dist/workflow-snapshot.js.map +1 -0
  214. package/dist/workflow-types.d.ts +171 -0
  215. package/dist/workflow-types.d.ts.map +1 -0
  216. package/dist/workflow-types.js +2 -0
  217. package/dist/workflow-types.js.map +1 -0
  218. package/dist/workflow.d.ts +19 -0
  219. package/dist/workflow.d.ts.map +1 -0
  220. package/dist/workflow.js +1053 -0
  221. package/dist/workflow.js.map +1 -0
  222. package/examples/a2a-remote.ts +85 -0
  223. package/examples/a2a-server.ts +100 -0
  224. package/examples/background.ts +18 -4
  225. package/examples/code-mode.ts +76 -0
  226. package/examples/conversation.ts +57 -0
  227. package/examples/evals.ts +79 -0
  228. package/examples/guardrails.ts +56 -0
  229. package/examples/handoff.ts +79 -0
  230. package/examples/memory.ts +44 -0
  231. package/examples/otel.ts +99 -0
  232. package/examples/steering.ts +69 -0
  233. package/examples/structured-handoff.ts +92 -0
  234. package/examples/subagents.ts +127 -0
  235. package/examples/workflow.ts +74 -0
  236. package/package.json +58 -6
  237. package/src/a2a/auth.ts +62 -0
  238. package/src/a2a/client.ts +733 -0
  239. package/src/a2a/index.ts +74 -0
  240. package/src/a2a/memory-runs.ts +448 -0
  241. package/src/a2a/policy.ts +148 -0
  242. package/src/a2a/push.ts +251 -0
  243. package/src/a2a/remote.ts +1652 -0
  244. package/src/a2a/server.ts +1390 -0
  245. package/src/a2a/signing.ts +348 -0
  246. package/src/a2a/tasks.ts +260 -0
  247. package/src/a2a/wire.ts +1443 -0
  248. package/src/background-types.ts +86 -0
  249. package/src/child.ts +181 -0
  250. package/src/code-driver.ts +48 -0
  251. package/src/code-mode.ts +12 -0
  252. package/src/code-script.ts +149 -0
  253. package/src/code.ts +424 -0
  254. package/src/compaction.ts +212 -0
  255. package/src/delegation.ts +444 -155
  256. package/src/evals/driver.ts +222 -0
  257. package/src/evals/journal.ts +605 -0
  258. package/src/evals/judge.ts +188 -0
  259. package/src/evals/report.ts +295 -0
  260. package/src/evals/runner.ts +826 -0
  261. package/src/evals/scorers.ts +339 -0
  262. package/src/evals/simulation.ts +46 -0
  263. package/src/evals/testing.ts +126 -0
  264. package/src/evals/trajectory.ts +223 -0
  265. package/src/evals/types.ts +463 -0
  266. package/src/evals.ts +72 -0
  267. package/src/extensions.ts +247 -0
  268. package/src/handoff.ts +214 -0
  269. package/src/index.ts +51 -0
  270. package/src/input.ts +319 -0
  271. package/src/mcp.ts +690 -0
  272. package/src/memory-store.ts +366 -0
  273. package/src/memory.ts +893 -0
  274. package/src/otel.ts +568 -0
  275. package/src/progress.ts +214 -0
  276. package/src/quickjs.ts +524 -0
  277. package/src/recovery.ts +90 -0
  278. package/src/request.ts +513 -0
  279. package/src/run.ts +2678 -313
  280. package/src/runs.ts +464 -133
  281. package/src/schema-to-ts.ts +194 -0
  282. package/src/session.ts +178 -0
  283. package/src/snapshot.ts +1595 -124
  284. package/src/steering.ts +329 -0
  285. package/src/subagents.ts +1084 -0
  286. package/src/tool-retry.ts +86 -0
  287. package/src/tree.ts +223 -27
  288. package/src/types.ts +711 -52
  289. package/src/workflow-snapshot.ts +366 -0
  290. package/src/workflow-types.ts +213 -0
  291. package/src/workflow.ts +1316 -0
@@ -0,0 +1,366 @@
1
+ // Adapted from TanStack AI (MIT), ai-memory/internal/store.ts and testkit/contract.ts.
2
+ // Copyright (c) 2025 Tanner Linsley. Changed: Unicode words, every scope dimension,
3
+ // atomic version checks, erasure generations and ingestion receipts; no vector calls.
4
+ import {
5
+ MEMORY_LIMITS,
6
+ MemoryConflictError,
7
+ MemoryErasedError,
8
+ isMemoryAccess,
9
+ isMemoryScope,
10
+ memoryKey,
11
+ memoryScopeKey,
12
+ readMemoryDeletions,
13
+ readMemoryIngest,
14
+ readMemoryNotes,
15
+ sameMemoryScope,
16
+ type MemoryAccess,
17
+ type MemoryCall,
18
+ type MemoryIngestReceipt,
19
+ type MemoryInput,
20
+ type MemoryRecord,
21
+ type MemoryScope,
22
+ type MemoryStore,
23
+ } from "./memory.ts";
24
+ import { requestHash } from "./request.ts";
25
+ import { copyData, equalData, isId } from "./snapshot.ts";
26
+
27
+ /** Process-lifetime reference only: no persistence, database, embedding calls or scheduler. */
28
+ export function createMemoryStore(options: { now?: () => number } = {}): MemoryStore {
29
+ const now = options.now ?? Date.now;
30
+ const records = new Map<string, MemoryRecord>();
31
+ const revisions = new Map<string, string>();
32
+ const receipts = new Map<string, { access: MemoryAccess; receipt: MemoryIngestReceipt }>();
33
+ const personKey = (scope: MemoryScope) => JSON.stringify([scope.tenantId, scope.userId ?? null]);
34
+ const recordKey = (scope: MemoryScope, key: string) =>
35
+ JSON.stringify([memoryScopeKey(scope), key]);
36
+ const receiptKey = (access: MemoryAccess, runId: string) =>
37
+ JSON.stringify([memoryScopeKey(access.scope), access.revision, runId]);
38
+ function revision(scope: MemoryScope): string {
39
+ const key = personKey(scope);
40
+ let value = revisions.get(key);
41
+ if (!value) {
42
+ value = crypto.randomUUID();
43
+ revisions.set(key, value);
44
+ }
45
+ return value;
46
+ }
47
+ function check(access: MemoryAccess, call: MemoryCall): void {
48
+ call.signal.throwIfAborted();
49
+ if (!isMemoryAccess(access))
50
+ throw new TypeError("Memory needs an exact scope and erasure revision.");
51
+ if (revision(access.scope) !== access.revision) throw new MemoryErasedError();
52
+ }
53
+ function live(record?: MemoryRecord): record is MemoryRecord {
54
+ return !!record && (record.expiresAt === undefined || record.expiresAt > now());
55
+ }
56
+ function current(access: MemoryAccess, key: string): MemoryRecord | undefined {
57
+ const record = records.get(recordKey(access.scope, key));
58
+ return live(record) ? record : undefined;
59
+ }
60
+ function prepare(
61
+ access: MemoryAccess,
62
+ raw: readonly MemoryInput[],
63
+ call: MemoryCall,
64
+ ): MemoryRecord[] {
65
+ const notes = readMemoryNotes(raw);
66
+ check(access, call);
67
+ const at = now();
68
+ return notes.map((note) => {
69
+ const before = current(access, note.key);
70
+ if ((before?.version ?? null) !== note.version) throw new MemoryConflictError();
71
+ return {
72
+ ...copyData(note),
73
+ scope: copyData(access.scope),
74
+ version: crypto.randomUUID(),
75
+ createdAt: before?.createdAt ?? at,
76
+ updatedAt: at,
77
+ };
78
+ });
79
+ }
80
+ function commit(notes: MemoryRecord[]): void {
81
+ for (const note of notes) records.set(recordKey(note.scope, note.key), note);
82
+ }
83
+ function keys(raw: readonly string[]): void {
84
+ if (
85
+ !Array.isArray(raw) ||
86
+ raw.length < 1 ||
87
+ raw.length > MEMORY_LIMITS.batch ||
88
+ !raw.every(memoryKey) ||
89
+ new Set(raw).size !== raw.length
90
+ )
91
+ throw new TypeError("Read 1 to 20 unique note keys.");
92
+ }
93
+ const words = (text: string) =>
94
+ new Set(
95
+ text
96
+ .normalize("NFD")
97
+ .replace(/\p{M}/gu, "")
98
+ .toLowerCase()
99
+ .match(/[\p{L}\p{N}]+/gu) ?? [],
100
+ );
101
+ return {
102
+ async access(scope, call) {
103
+ call.signal.throwIfAborted();
104
+ if (!isMemoryScope(scope))
105
+ throw new TypeError("Supply an explicit tenant and valid memory scope.");
106
+ return { scope: copyData(scope), revision: revision(scope) };
107
+ },
108
+ async get({ access, keys: names }, call) {
109
+ check(access, call);
110
+ keys(names);
111
+ return copyData(
112
+ names.flatMap((key) => {
113
+ const note = current(access, key);
114
+ return note ? [note] : [];
115
+ }),
116
+ );
117
+ },
118
+ async search({ scopes, query, limit }, call) {
119
+ if (
120
+ !Array.isArray(scopes) ||
121
+ !scopes.length ||
122
+ scopes.length > MEMORY_LIMITS.scopes ||
123
+ typeof query !== "string" ||
124
+ query.length > MEMORY_LIMITS.queryChars ||
125
+ !Number.isSafeInteger(limit) ||
126
+ limit < 1 ||
127
+ limit > MEMORY_LIMITS.matches
128
+ )
129
+ throw new TypeError("Search needs bounded scopes, query and limit.");
130
+ for (const access of scopes) check(access, call);
131
+ if (new Set(scopes.map((access) => memoryScopeKey(access.scope))).size !== scopes.length)
132
+ throw new TypeError("Search each scope once.");
133
+ const tokens = words(query);
134
+ // ponytail: linear scan for offline examples. Use a host database index for production.
135
+ return copyData(
136
+ [...records.values()]
137
+ .filter(
138
+ (note) =>
139
+ live(note) && scopes.some((access) => sameMemoryScope(access.scope, note.scope)),
140
+ )
141
+ .map((note) => {
142
+ const text = words(note.text);
143
+ const score =
144
+ [...tokens].filter((token) => text.has(token)).length / (tokens.size || 1);
145
+ return { note, score };
146
+ })
147
+ .filter(({ score }) => score > 0)
148
+ .sort(
149
+ (a, b) =>
150
+ b.score - a.score ||
151
+ b.note.updatedAt - a.note.updatedAt ||
152
+ a.note.key.localeCompare(b.note.key),
153
+ )
154
+ .slice(0, limit)
155
+ .map(({ note }) => note),
156
+ );
157
+ },
158
+ async save({ access, notes }, call) {
159
+ const prepared = prepare(access, notes, call);
160
+ commit(prepared);
161
+ return copyData(prepared);
162
+ },
163
+ async delete({ access, notes: raw }, call) {
164
+ const notes = readMemoryDeletions(raw);
165
+ check(access, call);
166
+ if (notes.some((note) => current(access, note.key)?.version !== note.version))
167
+ throw new MemoryConflictError();
168
+ for (const note of notes) records.delete(recordKey(access.scope, note.key));
169
+ return { deleted: notes.length };
170
+ },
171
+ async erase(person, call) {
172
+ call.signal.throwIfAborted();
173
+ if (
174
+ !isMemoryScope(person) ||
175
+ !person.userId ||
176
+ Object.keys(person).some((key) => key !== "tenantId" && key !== "userId")
177
+ )
178
+ throw new TypeError("Erasure needs exactly one tenant and one person.");
179
+ const key = personKey(person);
180
+ // Fence every namespace, including one with no records yet. No wall-clock race or skew.
181
+ revisions.set(key, crypto.randomUUID());
182
+ for (const [id, note] of records) if (personKey(note.scope) === key) records.delete(id);
183
+ for (const [id, entry] of receipts)
184
+ if (personKey(entry.access.scope) === key) receipts.delete(id);
185
+ },
186
+ async ingest(raw, call) {
187
+ const request = readMemoryIngest(raw);
188
+ check(request.access, call);
189
+ const fingerprint = await requestHash(request);
190
+ // Hashing yields. Recheck after it, in the same synchronous section as CAS and commit.
191
+ check(request.access, call);
192
+ const key = receiptKey(request.access, request.runId);
193
+ const prior = receipts.get(key);
194
+ if (prior) {
195
+ if (prior.receipt.fingerprint !== fingerprint) throw new MemoryConflictError();
196
+ return copyData(prior.receipt);
197
+ }
198
+ const notes = prepare(request.access, request.notes, call);
199
+ const receipt = {
200
+ runId: request.runId,
201
+ fingerprint,
202
+ saved: notes.map(({ key, version }) => ({ key, version })),
203
+ };
204
+ commit(notes);
205
+ receipts.set(key, { access: copyData(request.access), receipt });
206
+ return copyData(receipt);
207
+ },
208
+ async receipt({ access, runId }, call) {
209
+ check(access, call);
210
+ if (!isId(runId)) throw new TypeError("A receipt needs its run id.");
211
+ return copyData(receipts.get(receiptKey(access, runId))?.receipt ?? null);
212
+ },
213
+ };
214
+ }
215
+
216
+ /** DESTRUCTIVE check. The caller explicitly supplies a disposable store, never a live one.
217
+ * Adapted from TanStack's contract suite without depending on a test runner. */
218
+ export async function checkMemoryStore(options: { disposable: MemoryStore }): Promise<void> {
219
+ const store = options.disposable;
220
+ const call = { signal: new AbortController().signal };
221
+ const tenantId = `memory-check-${crypto.randomUUID()}`;
222
+ const scope = { tenantId, userId: "4", sessionId: "__proto__", namespace: "notes" };
223
+ function assert(ok: boolean, rule: string): asserts ok {
224
+ if (!ok) throw new Error(`MemoryStore failed: ${rule}.`);
225
+ }
226
+ async function conflict(work: Promise<unknown>, name: string) {
227
+ try {
228
+ await work;
229
+ } catch (error) {
230
+ assert(error instanceof Error && error.name === name, name);
231
+ return;
232
+ }
233
+ throw new Error(`MemoryStore failed: expected ${name}.`);
234
+ }
235
+ const access = await store.access(scope, call);
236
+ assert(equalData(access.scope, scope), "access keeps the exact scope");
237
+ assert(
238
+ (await store.search({ scopes: [access], query: "coffee", limit: 1 }, call)).length === 0,
239
+ "empty store",
240
+ );
241
+ const saved = await store.save(
242
+ { access, notes: [{ key: "preference", text: "coffee", version: null }] },
243
+ call,
244
+ );
245
+ const note = saved[0];
246
+ assert(!!note && note.text === "coffee" && isId(note.version), "save receipt");
247
+ const version = note.version;
248
+ note.text = "changed copy";
249
+ const found = await store.search({ scopes: [access], query: "coffee", limit: 1 }, call);
250
+ assert(found.length === 1 && found[0]?.text === "coffee", "round trip and write cloning");
251
+ if (found[0]) found[0].text = "changed read";
252
+ assert(
253
+ (await store.get({ access, keys: ["preference"] }, call))[0]?.text === "coffee",
254
+ "read cloning",
255
+ );
256
+ const others = [
257
+ { ...scope, tenantId: `${tenantId}-other` },
258
+ { ...scope, userId: "42" },
259
+ { ...scope, sessionId: "other" },
260
+ { ...scope, namespace: "other" },
261
+ { tenantId, userId: "4" },
262
+ { tenantId },
263
+ ];
264
+ for (const other of others) {
265
+ const otherAccess = await store.access(other, call);
266
+ assert(
267
+ (await store.get({ access: otherAccess, keys: ["preference"] }, call)).length === 0,
268
+ "exact get isolation",
269
+ );
270
+ assert(
271
+ (await store.search({ scopes: [otherAccess], query: "coffee", limit: 1 }, call)).length === 0,
272
+ "exact search isolation",
273
+ );
274
+ }
275
+ const results = await Promise.allSettled(
276
+ ["a", "b"].map((text) =>
277
+ store.save({ access, notes: [{ key: "preference", text, version }] }, call),
278
+ ),
279
+ );
280
+ assert(
281
+ results.filter((result) => result.status === "fulfilled").length === 1,
282
+ "one winner for a version race",
283
+ );
284
+ await conflict(
285
+ store.delete({ access, notes: [{ key: "preference", version }] }, call),
286
+ "MemoryConflictError",
287
+ );
288
+ const current = (await store.get({ access, keys: ["preference"] }, call))[0];
289
+ assert(!!current && current.version !== version, "versions change");
290
+ await store.delete({ access, notes: [{ key: "preference", version: current.version }] }, call);
291
+ assert(
292
+ (await store.get({ access, keys: ["preference"] }, call)).length === 0,
293
+ "delete by version",
294
+ );
295
+ await store.save(
296
+ {
297
+ access,
298
+ notes: [
299
+ { key: "extra1", text: "coffee", version: null },
300
+ { key: "extra2", text: "coffee", version: null },
301
+ ],
302
+ },
303
+ call,
304
+ );
305
+ assert(
306
+ (await store.search({ scopes: [access], query: "coffee", limit: 1 }, call)).length === 1,
307
+ "search limit",
308
+ );
309
+ await store.save(
310
+ { access, notes: [{ key: "expired", text: "coffee", version: null, expiresAt: 0 }] },
311
+ call,
312
+ );
313
+ assert((await store.get({ access, keys: ["expired"] }, call)).length === 0, "expiry");
314
+ const sibling = await store.access({ ...scope, userId: "42" }, call);
315
+ const tenant = await store.access({ ...scope, tenantId: `${tenantId}-other` }, call);
316
+ for (const other of [sibling, tenant])
317
+ await store.save(
318
+ { access: other, notes: [{ key: "kept", text: "coffee", version: null }] },
319
+ call,
320
+ );
321
+ if (store.ingest && store.receipt) {
322
+ const request = {
323
+ access,
324
+ runId: "run",
325
+ agent: { id: "agent", version: "1" },
326
+ messages: [],
327
+ notes: [{ key: "fact", text: "coffee", version: null }],
328
+ };
329
+ const first = await store.ingest(request, call);
330
+ assert(
331
+ equalData(first, await store.ingest(request, call)),
332
+ "atomic duplicate ingestion receipt",
333
+ );
334
+ assert(
335
+ equalData(first, await store.receipt({ access, runId: "run" }, call)),
336
+ "read-only ingestion reconciliation",
337
+ );
338
+ await conflict(
339
+ store.ingest({ ...request, notes: [{ key: "fact", text: "other", version: null }] }, call),
340
+ "MemoryConflictError",
341
+ );
342
+ }
343
+ await store.erase({ tenantId, userId: "4" }, call);
344
+ await conflict(
345
+ store.save({ access, notes: [{ key: "late", text: "coffee", version: null }] }, call),
346
+ "MemoryErasedError",
347
+ );
348
+ for (const other of [sibling, tenant])
349
+ assert(
350
+ (await store.get({ access: other, keys: ["kept"] }, call)).length === 1,
351
+ "erasure isolates tenant and person",
352
+ );
353
+ const fresh = await store.access(scope, call);
354
+ assert(
355
+ fresh.revision !== access.revision &&
356
+ (await store.get({ access: fresh, keys: ["fact"] }, call)).length === 0,
357
+ "erase removes data and rotates revision",
358
+ );
359
+ if (store.receipt)
360
+ assert(
361
+ (await store.receipt({ access: fresh, runId: "run" }, call)) === null,
362
+ "erase removes ingestion receipts",
363
+ );
364
+ await store.erase({ tenantId, userId: "42" }, call);
365
+ await store.erase({ tenantId: `${tenantId}-other`, userId: "4" }, call);
366
+ }