agentfootprint 9.2.0 → 9.4.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 (183) hide show
  1. package/CLAUDE.md +3 -1
  2. package/dist/adapters/identity/agentcore.js +94 -26
  3. package/dist/adapters/identity/agentcore.js.map +1 -1
  4. package/dist/adapters/llm/BedrockProvider.js +34 -9
  5. package/dist/adapters/llm/BedrockProvider.js.map +1 -1
  6. package/dist/adapters/memory/pgVector.js +731 -0
  7. package/dist/adapters/memory/pgVector.js.map +1 -0
  8. package/dist/adapters/memory/s3Vectors.js +780 -0
  9. package/dist/adapters/memory/s3Vectors.js.map +1 -0
  10. package/dist/adapters/memory/sqliteVector.js +16 -79
  11. package/dist/adapters/memory/sqliteVector.js.map +1 -1
  12. package/dist/adapters/observability/cloudwatch.js +13 -8
  13. package/dist/adapters/observability/cloudwatch.js.map +1 -1
  14. package/dist/adapters/observability/xray.js +13 -8
  15. package/dist/adapters/observability/xray.js.map +1 -1
  16. package/dist/adapters/security/agentcore.js +0 -0
  17. package/dist/adapters/security/agentcore.js.map +1 -1
  18. package/dist/bridge/eventMeta.js +3 -0
  19. package/dist/bridge/eventMeta.js.map +1 -1
  20. package/dist/core/Agent.js +11 -0
  21. package/dist/core/Agent.js.map +1 -1
  22. package/dist/core/agent/stages/toolCalls.js +80 -7
  23. package/dist/core/agent/stages/toolCalls.js.map +1 -1
  24. package/dist/doors/security.js +3 -2
  25. package/dist/doors/security.js.map +1 -1
  26. package/dist/embedders/index.js +240 -76
  27. package/dist/embedders/index.js.map +1 -1
  28. package/dist/esm/adapters/identity/agentcore.d.ts +39 -9
  29. package/dist/esm/adapters/identity/agentcore.js +94 -26
  30. package/dist/esm/adapters/identity/agentcore.js.map +1 -1
  31. package/dist/esm/adapters/llm/BedrockProvider.d.ts +24 -0
  32. package/dist/esm/adapters/llm/BedrockProvider.js +34 -9
  33. package/dist/esm/adapters/llm/BedrockProvider.js.map +1 -1
  34. package/dist/esm/adapters/memory/pgVector.d.ts +243 -0
  35. package/dist/esm/adapters/memory/pgVector.js +726 -0
  36. package/dist/esm/adapters/memory/pgVector.js.map +1 -0
  37. package/dist/esm/adapters/memory/s3Vectors.d.ts +240 -0
  38. package/dist/esm/adapters/memory/s3Vectors.js +776 -0
  39. package/dist/esm/adapters/memory/s3Vectors.js.map +1 -0
  40. package/dist/esm/adapters/memory/sqliteVector.d.ts +5 -27
  41. package/dist/esm/adapters/memory/sqliteVector.js +10 -73
  42. package/dist/esm/adapters/memory/sqliteVector.js.map +1 -1
  43. package/dist/esm/adapters/observability/cloudwatch.d.ts +20 -0
  44. package/dist/esm/adapters/observability/cloudwatch.js +13 -8
  45. package/dist/esm/adapters/observability/cloudwatch.js.map +1 -1
  46. package/dist/esm/adapters/observability/xray.d.ts +18 -0
  47. package/dist/esm/adapters/observability/xray.js +13 -8
  48. package/dist/esm/adapters/observability/xray.js.map +1 -1
  49. package/dist/esm/adapters/security/agentcore.d.ts +81 -107
  50. package/dist/esm/adapters/security/agentcore.js +0 -0
  51. package/dist/esm/adapters/security/agentcore.js.map +1 -1
  52. package/dist/esm/bridge/eventMeta.d.ts +3 -0
  53. package/dist/esm/bridge/eventMeta.js +3 -0
  54. package/dist/esm/bridge/eventMeta.js.map +1 -1
  55. package/dist/esm/core/Agent.d.ts +16 -0
  56. package/dist/esm/core/Agent.js +11 -0
  57. package/dist/esm/core/Agent.js.map +1 -1
  58. package/dist/esm/core/agent/stages/toolCalls.js +80 -7
  59. package/dist/esm/core/agent/stages/toolCalls.js.map +1 -1
  60. package/dist/esm/doors/security.d.ts +3 -2
  61. package/dist/esm/doors/security.js +3 -2
  62. package/dist/esm/doors/security.js.map +1 -1
  63. package/dist/esm/embedders/index.d.ts +99 -19
  64. package/dist/esm/embedders/index.js +240 -76
  65. package/dist/esm/embedders/index.js.map +1 -1
  66. package/dist/esm/events/dispatcher.d.ts +1 -1
  67. package/dist/esm/events/dispatcher.js.map +1 -1
  68. package/dist/esm/events/payloads.d.ts +23 -1
  69. package/dist/esm/events/types.d.ts +17 -0
  70. package/dist/esm/hosting/standingAgent.js +14 -1
  71. package/dist/esm/hosting/standingAgent.js.map +1 -1
  72. package/dist/esm/lib/embedderMismatch.d.ts +67 -0
  73. package/dist/esm/lib/embedderMismatch.js +96 -0
  74. package/dist/esm/lib/embedderMismatch.js.map +1 -0
  75. package/dist/esm/lib/rag/defineRAG.d.ts +28 -6
  76. package/dist/esm/lib/rag/defineRAG.js +39 -5
  77. package/dist/esm/lib/rag/defineRAG.js.map +1 -1
  78. package/dist/esm/memory/define.js +31 -1
  79. package/dist/esm/memory/define.js.map +1 -1
  80. package/dist/esm/memory/define.types.d.ts +13 -2
  81. package/dist/esm/memory/define.types.js.map +1 -1
  82. package/dist/esm/memory/embedding/loadRelevant.d.ts +10 -2
  83. package/dist/esm/memory/embedding/loadRelevant.js +36 -18
  84. package/dist/esm/memory/embedding/loadRelevant.js.map +1 -1
  85. package/dist/esm/memory/pipeline/semantic.d.ts +13 -2
  86. package/dist/esm/memory/pipeline/semantic.js +11 -5
  87. package/dist/esm/memory/pipeline/semantic.js.map +1 -1
  88. package/dist/esm/memory/store/capability.d.ts +25 -6
  89. package/dist/esm/memory/store/capability.js +68 -3
  90. package/dist/esm/memory/store/capability.js.map +1 -1
  91. package/dist/esm/memory/store/index.d.ts +1 -0
  92. package/dist/esm/memory/store/index.js +4 -0
  93. package/dist/esm/memory/store/index.js.map +1 -1
  94. package/dist/esm/memory/store/types.d.ts +40 -0
  95. package/dist/esm/memory-providers.d.ts +7 -4
  96. package/dist/esm/memory-providers.js +18 -4
  97. package/dist/esm/memory-providers.js.map +1 -1
  98. package/dist/esm/recorders/core/CredentialRecorder.d.ts +30 -0
  99. package/dist/esm/recorders/core/CredentialRecorder.js +35 -0
  100. package/dist/esm/recorders/core/CredentialRecorder.js.map +1 -0
  101. package/dist/esm/security/index.d.ts +7 -3
  102. package/dist/esm/security/index.js +12 -7
  103. package/dist/esm/security/index.js.map +1 -1
  104. package/dist/events/dispatcher.js.map +1 -1
  105. package/dist/hosting/standingAgent.js +14 -1
  106. package/dist/hosting/standingAgent.js.map +1 -1
  107. package/dist/lib/embedderMismatch.js +103 -0
  108. package/dist/lib/embedderMismatch.js.map +1 -0
  109. package/dist/lib/rag/defineRAG.js +39 -5
  110. package/dist/lib/rag/defineRAG.js.map +1 -1
  111. package/dist/memory/define.js +31 -1
  112. package/dist/memory/define.js.map +1 -1
  113. package/dist/memory/define.types.js.map +1 -1
  114. package/dist/memory/embedding/loadRelevant.js +36 -18
  115. package/dist/memory/embedding/loadRelevant.js.map +1 -1
  116. package/dist/memory/pipeline/semantic.js +11 -5
  117. package/dist/memory/pipeline/semantic.js.map +1 -1
  118. package/dist/memory/store/capability.js +70 -4
  119. package/dist/memory/store/capability.js.map +1 -1
  120. package/dist/memory/store/index.js +7 -1
  121. package/dist/memory/store/index.js.map +1 -1
  122. package/dist/memory-providers.js +22 -5
  123. package/dist/memory-providers.js.map +1 -1
  124. package/dist/recorders/core/CredentialRecorder.js +39 -0
  125. package/dist/recorders/core/CredentialRecorder.js.map +1 -0
  126. package/dist/security/index.js +13 -7
  127. package/dist/security/index.js.map +1 -1
  128. package/dist/types/adapters/identity/agentcore.d.ts +39 -9
  129. package/dist/types/adapters/identity/agentcore.d.ts.map +1 -1
  130. package/dist/types/adapters/llm/BedrockProvider.d.ts +24 -0
  131. package/dist/types/adapters/llm/BedrockProvider.d.ts.map +1 -1
  132. package/dist/types/adapters/memory/pgVector.d.ts +244 -0
  133. package/dist/types/adapters/memory/pgVector.d.ts.map +1 -0
  134. package/dist/types/adapters/memory/s3Vectors.d.ts +241 -0
  135. package/dist/types/adapters/memory/s3Vectors.d.ts.map +1 -0
  136. package/dist/types/adapters/memory/sqliteVector.d.ts +5 -27
  137. package/dist/types/adapters/memory/sqliteVector.d.ts.map +1 -1
  138. package/dist/types/adapters/observability/cloudwatch.d.ts +20 -0
  139. package/dist/types/adapters/observability/cloudwatch.d.ts.map +1 -1
  140. package/dist/types/adapters/observability/xray.d.ts +18 -0
  141. package/dist/types/adapters/observability/xray.d.ts.map +1 -1
  142. package/dist/types/adapters/security/agentcore.d.ts +81 -107
  143. package/dist/types/adapters/security/agentcore.d.ts.map +1 -1
  144. package/dist/types/bridge/eventMeta.d.ts +3 -0
  145. package/dist/types/bridge/eventMeta.d.ts.map +1 -1
  146. package/dist/types/core/Agent.d.ts +16 -0
  147. package/dist/types/core/Agent.d.ts.map +1 -1
  148. package/dist/types/core/agent/stages/toolCalls.d.ts.map +1 -1
  149. package/dist/types/doors/security.d.ts +3 -2
  150. package/dist/types/doors/security.d.ts.map +1 -1
  151. package/dist/types/embedders/index.d.ts +99 -19
  152. package/dist/types/embedders/index.d.ts.map +1 -1
  153. package/dist/types/events/dispatcher.d.ts +1 -1
  154. package/dist/types/events/dispatcher.d.ts.map +1 -1
  155. package/dist/types/events/payloads.d.ts +23 -1
  156. package/dist/types/events/payloads.d.ts.map +1 -1
  157. package/dist/types/events/types.d.ts +17 -0
  158. package/dist/types/events/types.d.ts.map +1 -1
  159. package/dist/types/hosting/standingAgent.d.ts.map +1 -1
  160. package/dist/types/lib/embedderMismatch.d.ts +68 -0
  161. package/dist/types/lib/embedderMismatch.d.ts.map +1 -0
  162. package/dist/types/lib/rag/defineRAG.d.ts +28 -6
  163. package/dist/types/lib/rag/defineRAG.d.ts.map +1 -1
  164. package/dist/types/memory/define.d.ts.map +1 -1
  165. package/dist/types/memory/define.types.d.ts +13 -2
  166. package/dist/types/memory/define.types.d.ts.map +1 -1
  167. package/dist/types/memory/embedding/loadRelevant.d.ts +10 -2
  168. package/dist/types/memory/embedding/loadRelevant.d.ts.map +1 -1
  169. package/dist/types/memory/pipeline/semantic.d.ts +13 -2
  170. package/dist/types/memory/pipeline/semantic.d.ts.map +1 -1
  171. package/dist/types/memory/store/capability.d.ts +25 -6
  172. package/dist/types/memory/store/capability.d.ts.map +1 -1
  173. package/dist/types/memory/store/index.d.ts +1 -0
  174. package/dist/types/memory/store/index.d.ts.map +1 -1
  175. package/dist/types/memory/store/types.d.ts +40 -0
  176. package/dist/types/memory/store/types.d.ts.map +1 -1
  177. package/dist/types/memory-providers.d.ts +7 -4
  178. package/dist/types/memory-providers.d.ts.map +1 -1
  179. package/dist/types/recorders/core/CredentialRecorder.d.ts +31 -0
  180. package/dist/types/recorders/core/CredentialRecorder.d.ts.map +1 -0
  181. package/dist/types/security/index.d.ts +7 -3
  182. package/dist/types/security/index.d.ts.map +1 -1
  183. package/package.json +9 -1
@@ -0,0 +1,776 @@
1
+ /**
2
+ * adapters/memory/s3Vectors — the corpus outlives the runtime, and can still
3
+ * be updated without one.
4
+ *
5
+ * `sqliteVectorStore` (8.9.0) made a corpus survive a restart by putting it in
6
+ * a file, and `staticVectorStore` (8.20.0) made it survive a runtime with no
7
+ * disk at all by shipping it as a build artifact. Both leave the same gap, and
8
+ * a production field report named it: **a bundle can only change when you
9
+ * redeploy.** Add three documents on a Tuesday and the answer arrives with the
10
+ * next release train. That is a fine trade for product documentation and a bad
11
+ * one for anything a human edits during the day.
12
+ *
13
+ * Amazon S3 Vectors closes it. It is object storage with a native vector index
14
+ * and a query API: durable, serverless, nothing to run, priced like storage
15
+ * rather than like a database cluster. This adapter is the `MemoryStore` port
16
+ * over it, and the two halves that matter are:
17
+ *
18
+ * - `search()` maps 1:1 onto **QueryVectors** — the vector goes as
19
+ * `queryVector.float32`, `k` becomes `topK`, tiers become a metadata
20
+ * `filter`, and the returned `distance` becomes the port's score.
21
+ * - `put()` / `putMany()` map onto **PutVectors** — so `indexCorpus`,
22
+ * `indexFolder` and `indexDocuments` run against it unchanged. **That is
23
+ * the point of writing it rather than only reading it:** a corpus you can
24
+ * add to from a cron job at 14:00 is a different product from one you can
25
+ * add to at the next deploy.
26
+ *
27
+ * ── What it is NOT ──────────────────────────────────────────────────────────
28
+ * A vector index is not a key-value store, and this adapter refuses the
29
+ * operations that would need one rather than faking them:
30
+ *
31
+ * - `putIfVersion` — PutVectors is last-write-wins; there is no
32
+ * compare-and-set. A read-then-write here would be a compare-and-set that
33
+ * another writer can walk through the middle of, which is worse than none.
34
+ * - `recordSignature` / `feedback` — a set of strings and a running average
35
+ * are not vectors. `seen()` answers `false` and `getFeedback()` `null`,
36
+ * which are both TRUE (nothing can be recorded, so nothing has been); the
37
+ * WRITE halves refuse by name.
38
+ *
39
+ * Pair it with a second store for conversation memory — `defineRAG` for the
40
+ * corpus, `defineMemory` for the chat, each with the backend it suits. That is
41
+ * the same shape `staticVectorStore` documents.
42
+ *
43
+ * ── The index you must create first, and why this does not create it ────────
44
+ * A vector index has a DIMENSION and a DISTANCE METRIC fixed at creation, and
45
+ * both are decisions about your embedder that this library must not make on
46
+ * your behalf — creating one silently would pick a size and a metric your
47
+ * corpus then lives with. Create it once, with your infrastructure:
48
+ *
49
+ * ```bash
50
+ * aws s3vectors create-vector-bucket --vector-bucket-name my-corpus
51
+ * aws s3vectors create-index \
52
+ * --vector-bucket-name my-corpus \
53
+ * --index-name docs \
54
+ * --data-type float32 \
55
+ * --dimension 1024 \
56
+ * --distance-metric cosine \
57
+ * --metadata-configuration '{"nonFilterableMetadataKeys":["af"]}'
58
+ * ```
59
+ *
60
+ * `nonFilterableMetadataKeys: ["af"]` is load-bearing, not decoration. This
61
+ * adapter stores the whole entry — the passage the model will read, its
62
+ * provenance, its timestamps — as JSON under the metadata key `af`. Filterable
63
+ * metadata has a small per-vector budget; non-filterable metadata has the large
64
+ * one. Declare `af` non-filterable and a full passage fits; leave it filterable
65
+ * and PutVectors starts refusing your longer chunks partway through an
66
+ * indexing run.
67
+ *
68
+ * Only `ns` (the identity namespace) and `tier` are ever filtered on, and both
69
+ * are short strings.
70
+ *
71
+ * ── The preflight: this store now READS the index before trusting it (9.4.0) ─
72
+ * One `GetIndex`, lazily on first use and memoized for the life of the store.
73
+ * It checks the three things this adapter used to assume — and that a
74
+ * production deployment got wrong in all three ways at once:
75
+ *
76
+ * 1. the distance metric really is cosine (a euclidean index scored a
77
+ * self-query at 0.999…, where a true cosine is exactly 1.0);
78
+ * 2. `af` really is non-filterable, checked BEFORE the first write, so a
79
+ * misconfigured index fails at document 1 rather than at document 400
80
+ * with an AWS "Filterable metadata must have at most 2048 bytes";
81
+ * 3. the index dimension matches the vectors being written or searched.
82
+ *
83
+ * This is the discipline every sibling store already had at open —
84
+ * `sqliteVectorStore`'s schema identity, `pgVectorStore`'s schema check,
85
+ * `staticVectorStore`'s load-time fingerprint. This store had nothing to open,
86
+ * so it opened nothing.
87
+ *
88
+ * **IAM:** the caller now needs `s3vectors:GetIndex` alongside `PutVectors` /
89
+ * `QueryVectors` / `GetVectors` / `ListVectors` / `DeleteVectors`. A GetIndex
90
+ * that fails is refused by name, never passed through — an index this store
91
+ * cannot read is an index whose metric, layout and dimension it would be
92
+ * guessing at.
93
+ *
94
+ * ── Cosine only, said out loud ──────────────────────────────────────────────
95
+ * The port's score is a cosine similarity, and every threshold in this library
96
+ * — starting with `defineRAG`'s 0.7 default — is calibrated on that range. A
97
+ * cosine distance converts exactly (`score = 1 - distance`). A EUCLIDEAN
98
+ * distance does not: any mapping into [-1, 1] produces a number that READS like
99
+ * a cosine and is not one, which is the same class of confident-and-meaningless
100
+ * value the embedder-mismatch refusal exists to stop. So a euclidean index is
101
+ * refused at construction, by name.
102
+ *
103
+ * ── The fingerprint guarantee, stated exactly ───────────────────────────────
104
+ * `sqliteVectorStore` owns its file and can keep a fingerprint row in it. This
105
+ * store owns nothing but vectors, so the guarantee is assembled from what the
106
+ * service actually provides, and it is smaller — so it is spelled out rather
107
+ * than implied:
108
+ *
109
+ * - **Dimensions** are enforced by S3 Vectors itself. The index declares one;
110
+ * a vector of another length is rejected by the service, loudly, at the
111
+ * call. Nothing here can be sloppier than that.
112
+ * - **The model id** is stamped into every vector's metadata (`fp`) and
113
+ * checked in two places: against the fingerprint this process has already
114
+ * seen for the namespace (at write and at search), and against the
115
+ * fingerprint carried by the HITS that come back (at search). The second
116
+ * one is what survives a restart: the first query after an embedder swap
117
+ * sees documents stamped by the old embedder and refuses by name, instead
118
+ * of returning a confident ranking of two incompatible spaces.
119
+ * - Since 9.4.0 the index's OWN dimension is checked too, at the preflight —
120
+ * so a wrong-size embedder is caught on the first write and the first
121
+ * search of a fresh process, which the per-process fingerprint could not do
122
+ * (it has nothing to disagree with at boot).
123
+ * - What is still NOT caught: the first write of a fresh process into a
124
+ * namespace built by a different embedder OF THE SAME SIZE. Only the model
125
+ * id separates those, and it lives in the vectors rather than on the index.
126
+ * There is no cheap read that would catch it, and a full index scan on
127
+ * every boot is not one either. It is caught at the next search, before a
128
+ * single wrong answer is returned.
129
+ *
130
+ * ── Lazy peer dependency ────────────────────────────────────────────────────
131
+ * `@aws-sdk/client-s3vectors` is an OPTIONAL peer dependency, required at
132
+ * construction time. Importing `agentfootprint/memory` costs nothing for
133
+ * consumers who never build one of these. Pass `client` to share the SDK
134
+ * configuration your app already has.
135
+ */
136
+ import { identityNamespace } from '../../memory/identity/index.js';
137
+ import { lazyRequire } from '../../lib/lazyRequire.js';
138
+ import { EmbedderMismatchError, fingerprintConflict, fingerprintText, parseFingerprint, } from '../../lib/embedderMismatch.js';
139
+ // ─── Metadata layout ─────────────────────────────────────────────────
140
+ /** The identity namespace, filtered on at query time. Short, so filterable. */
141
+ const NS_KEY = 'ns';
142
+ /** The tier, filtered on when the caller asks for one. Short, so filterable. */
143
+ const TIER_KEY = 'tier';
144
+ /** The embedder fingerprint, `'<id>@<dims>'`. Short, so filterable. */
145
+ const FP_KEY = 'fp';
146
+ /**
147
+ * Everything else — the passage, provenance, versions, timestamps — as one
148
+ * JSON string. Declared NON-filterable at index creation so it gets the large
149
+ * metadata budget; see the header.
150
+ */
151
+ const PAYLOAD_KEY = 'af';
152
+ /**
153
+ * Open a `MemoryStore` over an existing S3 Vectors index.
154
+ *
155
+ * @throws when `@aws-sdk/client-s3vectors` is absent and no `client` was passed.
156
+ * @throws when `distanceMetric` is anything but `'cosine'`.
157
+ * @throws EmbedderMismatchError from `put`/`putMany`/`search` when a vector
158
+ * meets a namespace built by a different embedder.
159
+ *
160
+ * @example A corpus you can add to without a redeploy
161
+ * ```ts
162
+ * import { defineRAG, indexDocuments } from 'agentfootprint';
163
+ * import { s3VectorsStore } from 'agentfootprint/memory';
164
+ * import { bedrockEmbedder } from 'agentfootprint/providers';
165
+ *
166
+ * const store = s3VectorsStore({ bucket: 'my-corpus', index: 'docs', region: 'us-east-1' });
167
+ * const embedder = bedrockEmbedder({ region: 'us-east-1' });
168
+ *
169
+ * // Run this from a cron job. No deploy, no restart — the agent sees it next turn.
170
+ * await indexDocuments(store, embedder, newDocs, { embedderId: embedder.id });
171
+ *
172
+ * const agent = Agent.create({ provider })
173
+ * .rag(defineRAG({ id: 'docs', store, embedder, embedderId: embedder.id }))
174
+ * .build();
175
+ * ```
176
+ */
177
+ export function s3VectorsStore(options) {
178
+ const { bucket, index } = options;
179
+ if (!bucket || bucket.trim() === '' || !index || index.trim() === '') {
180
+ throw new TypeError(`s3VectorsStore: both \`bucket\` and \`index\` are required and must be non-empty — ` +
181
+ `received bucket='${String(bucket)}', index='${String(index)}'. This store never ` +
182
+ `creates either: an index's dimension and distance metric are decisions about your ` +
183
+ `embedder, and picking them for you would be picking them forever.`);
184
+ }
185
+ const metric = options.distanceMetric ?? 'cosine';
186
+ if (metric !== 'cosine') {
187
+ throw new TypeError(`s3VectorsStore: distanceMetric '${String(metric)}' is not supported — this store ` +
188
+ `reports COSINE similarity, and every threshold in this library (starting with ` +
189
+ `defineRAG's 0.7 default) is calibrated on that range.\n` +
190
+ ` A cosine distance converts exactly (score = 1 - distance). A euclidean one does ` +
191
+ `not: mapping it into [-1, 1] would produce a number that reads like a cosine and ` +
192
+ `is not one, which no threshold can separate from a real score.\n` +
193
+ ` Fix: create the index with --distance-metric cosine, or rank euclidean results ` +
194
+ `in your own adapter where the units are yours to interpret.`);
195
+ }
196
+ const batchSize = Math.max(1, Math.floor(options.batchSize ?? 100));
197
+ let connection;
198
+ /**
199
+ * Resolve the client + command constructors, once, on first call.
200
+ *
201
+ * Three ways in, and the first is what keeps the tests free of AWS:
202
+ * `_client` — test injection. The SDK is never required, and each command
203
+ * is a plain object stamped with its own name, so a double
204
+ * sees exactly which call was made and with what.
205
+ * `client` — your own pre-built client; config and credentials stay yours.
206
+ * neither — this factory builds one from `region`.
207
+ */
208
+ const connect = () => {
209
+ if (connection)
210
+ return connection;
211
+ if (options._client) {
212
+ const sdk = options._sdk;
213
+ connection = {
214
+ client: options._client,
215
+ GetIndex: sdk?.GetIndexCommand ?? shimCommand('GetIndex'),
216
+ Put: sdk?.PutVectorsCommand ?? shimCommand('PutVectors'),
217
+ Query: sdk?.QueryVectorsCommand ?? shimCommand('QueryVectors'),
218
+ Get: sdk?.GetVectorsCommand ?? shimCommand('GetVectors'),
219
+ List: sdk?.ListVectorsCommand ?? shimCommand('ListVectors'),
220
+ Delete: sdk?.DeleteVectorsCommand ?? shimCommand('DeleteVectors'),
221
+ owned: false,
222
+ };
223
+ return connection;
224
+ }
225
+ const sdk = options._sdk ?? loadS3VectorsSdk();
226
+ const missing = [
227
+ 'GetIndexCommand',
228
+ 'PutVectorsCommand',
229
+ 'QueryVectorsCommand',
230
+ 'GetVectorsCommand',
231
+ 'ListVectorsCommand',
232
+ 'DeleteVectorsCommand',
233
+ ].filter((name) => typeof sdk[name] !== 'function');
234
+ if (missing.length > 0) {
235
+ throw new Error(`s3VectorsStore: \`@aws-sdk/client-s3vectors\` is installed but ${missing.join(', ')} ` +
236
+ `${missing.length === 1 ? 'was' : 'were'} not found. Update the SDK.`);
237
+ }
238
+ if (!options.client && typeof sdk.S3VectorsClient !== 'function') {
239
+ throw new Error('s3VectorsStore: `@aws-sdk/client-s3vectors` is installed but `S3VectorsClient` was ' +
240
+ 'not found. Update the SDK, or pass `client` with a pre-built one.');
241
+ }
242
+ const owned = !options.client;
243
+ connection = {
244
+ client: options.client ??
245
+ // Checked directly above.
246
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
247
+ new sdk.S3VectorsClient({ ...(options.region && { region: options.region }) }),
248
+ // All six checked directly above.
249
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
250
+ GetIndex: sdk.GetIndexCommand,
251
+ Put: sdk.PutVectorsCommand,
252
+ Query: sdk.QueryVectorsCommand,
253
+ Get: sdk.GetVectorsCommand,
254
+ List: sdk.ListVectorsCommand,
255
+ Delete: sdk.DeleteVectorsCommand,
256
+ /* eslint-enable @typescript-eslint/no-non-null-assertion */
257
+ owned,
258
+ };
259
+ return connection;
260
+ };
261
+ /** Send one command. Used by the preflight itself, so it does NOT preflight. */
262
+ const rawCall = async (build, signal) => {
263
+ const conn = connect();
264
+ const command = build(conn);
265
+ return signal ? conn.client.send(command, { abortSignal: signal }) : conn.client.send(command);
266
+ };
267
+ /** Send one command, after the index has been verified once. */
268
+ const call = async (build, signal) => {
269
+ await verifyIndex(signal);
270
+ return rawCall(build, signal);
271
+ };
272
+ const scope = { vectorBucketName: bucket, indexName: index };
273
+ let verification;
274
+ const readIndex = async (signal) => {
275
+ let raw;
276
+ try {
277
+ raw = await rawCall((c) => new c.GetIndex({ ...scope }), signal);
278
+ }
279
+ catch (err) {
280
+ // Never a silent pass-through: an index this store cannot READ is an
281
+ // index whose metric, layout and dimension it is guessing at, and it
282
+ // guessed wrong three times in the field.
283
+ throw new Error(`s3VectorsStore: could not read the index '${bucket}/${index}' to verify it.\n` +
284
+ ` ${err instanceof Error ? err.message : String(err)}\n` +
285
+ ` This store reads the index ONCE before its first call, to check the distance ` +
286
+ `metric, the metadata layout and the dimension — three things it used to assume, ` +
287
+ `and that a production deployment got wrong in all three ways at once.\n` +
288
+ ` Check: the index exists in this region; the caller has the \`s3vectors:GetIndex\` ` +
289
+ `permission (PutVectors/QueryVectors alone are not enough since 9.4.0); the bucket ` +
290
+ `and index names are right.`);
291
+ }
292
+ const info = raw?.index ?? {};
293
+ const metadata = info['metadataConfiguration'];
294
+ const keys = Array.isArray(metadata?.nonFilterableMetadataKeys)
295
+ ? (metadata?.nonFilterableMetadataKeys).map(String)
296
+ : [];
297
+ return {
298
+ ...(typeof info['distanceMetric'] === 'string' && {
299
+ distanceMetric: info['distanceMetric'],
300
+ }),
301
+ ...(typeof info['dimension'] === 'number' && { dimension: info['dimension'] }),
302
+ nonFilterableMetadataKeys: keys,
303
+ };
304
+ };
305
+ /**
306
+ * Read the index once and refuse anything this store cannot serve honestly.
307
+ *
308
+ * Memoized on the PROMISE, so concurrent first calls share one GetIndex and
309
+ * one verdict. A refusal is memoized too — re-asking a broken index on every
310
+ * operation would turn one clear failure into a storm of them.
311
+ */
312
+ const verifyIndex = async (signal) => {
313
+ verification ??= readIndex(signal).then((found) => {
314
+ // (1) The metric. `options.distanceMetric` was a declaration; this is the
315
+ // index. A declaration that disagrees with the index is worse than none,
316
+ // so the message says which said what.
317
+ if (found.distanceMetric !== undefined && found.distanceMetric.toLowerCase() !== 'cosine') {
318
+ throw new TypeError(`s3VectorsStore: the index '${bucket}/${index}' was created with distance metric ` +
319
+ `'${found.distanceMetric}', and this store reports COSINE similarity.\n` +
320
+ (options.distanceMetric !== undefined
321
+ ? ` You declared '${options.distanceMetric}'. The index disagrees, and the index ` +
322
+ `is the one that ranks.\n`
323
+ : '') +
324
+ ` A cosine distance converts exactly (score = 1 - distance). A euclidean one does ` +
325
+ `not: mapped into [-1, 1] it produces a number that READS like a cosine and is ` +
326
+ `not one — a self-query scores 0.999… where a real cosine is exactly 1.0, which ` +
327
+ `no threshold (starting with defineRAG's 0.7 default) can separate from a real ` +
328
+ `score.\n` +
329
+ ` Fix: recreate the index with --distance-metric cosine, or rank euclidean ` +
330
+ `results in your own adapter where the units are yours to interpret.`);
331
+ }
332
+ return found;
333
+ });
334
+ return verification;
335
+ };
336
+ /**
337
+ * (2) The metadata layout, checked before the first byte is written.
338
+ *
339
+ * Separate from the metric because the failure it prevents is a WRITE
340
+ * failure: with `af` filterable, short entries go in and longer ones are
341
+ * refused by the service partway through an import — a corpus that is 60%
342
+ * indexed and reports success for the part that fit.
343
+ */
344
+ const assertWritableLayout = (found) => {
345
+ if (found.nonFilterableMetadataKeys.includes(PAYLOAD_KEY))
346
+ return;
347
+ throw new TypeError(`s3VectorsStore: the index '${bucket}/${index}' does not declare '${PAYLOAD_KEY}' as ` +
348
+ `non-filterable metadata, so this store cannot write to it.\n` +
349
+ ` It stores each entry — the passage the model will read, its provenance, its ` +
350
+ `timestamps — as JSON under the metadata key '${PAYLOAD_KEY}'. Filterable metadata ` +
351
+ `has a small per-vector budget (2048 bytes); non-filterable has the large one. ` +
352
+ `Without this, an import writes the short chunks, then fails on a longer one with ` +
353
+ `"Filterable metadata must have at most 2048 bytes" — partway through, having ` +
354
+ `already reported success for everything before it.\n` +
355
+ ` The index declares: ${found.nonFilterableMetadataKeys.length === 0
356
+ ? '(no non-filterable keys)'
357
+ : found.nonFilterableMetadataKeys.join(', ')}\n` +
358
+ ` Fix: recreate the index with\n` +
359
+ ` --metadata-configuration '{"nonFilterableMetadataKeys":["${PAYLOAD_KEY}"]}'\n` +
360
+ ` This cannot be changed after creation, so the index has to be rebuilt.`);
361
+ };
362
+ /**
363
+ * (3) The dimension, against the embedder that is actually being used.
364
+ *
365
+ * Same rule `sqliteVectorStore` applies and for the same reason: DIMENSIONS
366
+ * ALWAYS DECIDE. The service would reject the vector anyway — one write at a
367
+ * time, saying nothing about which embedder is wrong — where this names both
368
+ * numbers and the two ways out.
369
+ */
370
+ const assertDimension = (found, dims, operation) => {
371
+ if (found.dimension === undefined || found.dimension === dims)
372
+ return;
373
+ throw new EmbedderMismatchError(`${bucket}/${index}`, `the index@${found.dimension}`, `this embedder@${dims}`, 'dimensions', operation, 'point this store at an index whose dimension matches this embedder');
374
+ };
375
+ /** Fingerprints this process has seen, one per namespace. */
376
+ const fingerprints = new Map();
377
+ let closed = false;
378
+ const open = (verb) => {
379
+ if (closed) {
380
+ throw new Error(`[memory] the s3VectorsStore for '${bucket}/${index}' is closed, so it cannot ` +
381
+ `${verb}. close() is final by design — reopening the client behind you would hide ` +
382
+ `a shutdown-ordering bug rather than surface it. Build a new store if you need one ` +
383
+ `after closing this.`);
384
+ }
385
+ };
386
+ /**
387
+ * Compare an arriving fingerprint against the one this process holds, refuse
388
+ * a real conflict, and adopt the arriving one when it is the first or the
389
+ * more specific of the two. The same rule `sqliteVectorStore` applies — over
390
+ * a smaller record, which the header states precisely.
391
+ */
392
+ const reconcile = (ns, incoming, operation) => {
393
+ const storedText = fingerprints.get(ns);
394
+ if (storedText === undefined) {
395
+ fingerprints.set(ns, fingerprintText(incoming));
396
+ return;
397
+ }
398
+ const conflict = fingerprintConflict(parseFingerprint(storedText), incoming);
399
+ if (conflict !== null) {
400
+ throw new EmbedderMismatchError(ns, storedText, fingerprintText(incoming), conflict, operation, 'point this store at a different index');
401
+ }
402
+ if (parseFingerprint(storedText).id === undefined && incoming.id !== undefined) {
403
+ fingerprints.set(ns, fingerprintText(incoming));
404
+ }
405
+ };
406
+ const store = {
407
+ bucket,
408
+ index,
409
+ // Vectors in, ranked vectors out — QueryVectors ranks the embeddings this
410
+ // store was handed, so the corpus builders may write into it.
411
+ supportsVectorSearch: true,
412
+ ranksBy: 'vector',
413
+ fingerprintOf(identity) {
414
+ return fingerprints.get(identityNamespace(identity));
415
+ },
416
+ async get(identity, id) {
417
+ open('read an entry');
418
+ const ns = identityNamespace(identity);
419
+ const out = (await call((c) => new c.Get({ ...scope, keys: [vectorKey(ns, id)] })));
420
+ const row = out?.vectors?.[0];
421
+ if (!row)
422
+ return null;
423
+ const entry = vectorToEntry(row);
424
+ // Expired reads as absent, the same as every other store. No access
425
+ // counters: S3 Vectors has no in-place metadata update, so bumping one
426
+ // would mean rewriting the vector on every read.
427
+ if (!entry || isExpired(entry.ttl))
428
+ return null;
429
+ return entry;
430
+ },
431
+ async put(identity, entry) {
432
+ await this.putMany(identity, [entry]);
433
+ },
434
+ async putMany(identity, entries) {
435
+ open('write entries');
436
+ // The port requires an empty batch to be a no-op — callers rely on it to
437
+ // skip a round-trip on a turn that produced nothing.
438
+ if (entries.length === 0)
439
+ return;
440
+ const ns = identityNamespace(identity);
441
+ // Before a byte: the index really is cosine, and it really has room for a
442
+ // passage. Memoized, so this is one GetIndex for the life of the store —
443
+ // and it happens HERE rather than inside `call` below, because a layout
444
+ // that cannot hold an entry must stop the import at document 1, not at
445
+ // document 400 with 399 already written.
446
+ const found = await verifyIndex();
447
+ assertWritableLayout(found);
448
+ const vectors = entries.map((entry) => {
449
+ const embedding = entry.embedding;
450
+ if (!embedding || embedding.length === 0) {
451
+ throw new Error(`s3VectorsStore.putMany: entry '${entry.id}' carries no \`embedding\`, and a vector ` +
452
+ `index has nowhere to put an entry without one.\n` +
453
+ ` Every write here must arrive already embedded — which is what indexDocuments, ` +
454
+ `indexCorpus and indexFolder do. A conversation-memory pipeline over an ` +
455
+ `un-embedded turn belongs in a store built for key-value writes (RedisStore, ` +
456
+ `AgentCoreStore), registered separately with defineMemory.`);
457
+ }
458
+ const fp = {
459
+ ...(entry.embeddingModel !== undefined && { id: entry.embeddingModel }),
460
+ dims: embedding.length,
461
+ };
462
+ assertDimension(found, embedding.length, 'write to');
463
+ reconcile(ns, fp, 'write to');
464
+ return {
465
+ key: vectorKey(ns, entry.id),
466
+ data: { float32: [...embedding] },
467
+ metadata: {
468
+ [NS_KEY]: ns,
469
+ ...(entry.tier !== undefined && { [TIER_KEY]: entry.tier }),
470
+ [FP_KEY]: fingerprintText(fp),
471
+ [PAYLOAD_KEY]: JSON.stringify(payloadOf(entry)),
472
+ },
473
+ };
474
+ });
475
+ // Chunked well under the service limit. PutVectors is not transactional
476
+ // across chunks and this does not pretend otherwise: a failure part-way
477
+ // throws with the chunks before it already written, which is exactly what
478
+ // the port says about batches. The corpus builders are id-deterministic,
479
+ // so re-running the same index call converges.
480
+ for (let i = 0; i < vectors.length; i += batchSize) {
481
+ const chunk = vectors.slice(i, i + batchSize);
482
+ await call((c) => new c.Put({ ...scope, vectors: chunk }));
483
+ }
484
+ },
485
+ async putIfVersion() {
486
+ return refuse('putIfVersion', 'PutVectors is last-write-wins; S3 Vectors has no compare-and-set', 'a read-then-write here would be a compare-and-set another writer can walk through ' +
487
+ 'the middle of, which is worse than not offering one', 'use put()/putMany() when you are the only writer, or keep the version-critical ' +
488
+ 'entries in a store with real conditional writes (RedisStore) and the corpus here');
489
+ },
490
+ async list(identity, listOptions) {
491
+ open('list entries');
492
+ const ns = identityNamespace(identity);
493
+ const prefix = `${ns}#`;
494
+ const limit = Math.max(1, Math.floor(listOptions?.limit ?? 100));
495
+ const tierFilter = listOptions?.tiers ? new Set(listOptions.tiers) : undefined;
496
+ const page = [];
497
+ // ListVectors has no key-prefix filter, so a namespace is selected HERE,
498
+ // over pages of the whole index. That is honest but not free: on an index
499
+ // holding many namespaces this reads more than it returns. One index per
500
+ // corpus is the shape this store is for, and `search()` — the hot path —
501
+ // filters server-side on `ns` and never does this.
502
+ let token = listOptions?.cursor;
503
+ do {
504
+ const out = (await call((c) => new c.List({
505
+ ...scope,
506
+ maxResults: Math.min(500, Math.max(limit, 100)),
507
+ returnMetadata: true,
508
+ returnData: true,
509
+ ...(token !== undefined && { nextToken: token }),
510
+ })));
511
+ token = out?.nextToken;
512
+ for (const row of out?.vectors ?? []) {
513
+ if (typeof row.key !== 'string' || !row.key.startsWith(prefix))
514
+ continue;
515
+ const entry = vectorToEntry(row);
516
+ if (!entry || isExpired(entry.ttl))
517
+ continue;
518
+ if (tierFilter && (entry.tier === undefined || !tierFilter.has(entry.tier)))
519
+ continue;
520
+ page.push(entry);
521
+ if (page.length === limit)
522
+ break;
523
+ }
524
+ } while (page.length < limit && token !== undefined);
525
+ // The cursor is the service's own continuation token, so a caller pages
526
+ // through the INDEX rather than through our filtered view — which is why
527
+ // it is only returned when the service says there is more.
528
+ return { entries: page, ...(token !== undefined && { cursor: token }) };
529
+ },
530
+ async delete(identity, id) {
531
+ open('delete an entry');
532
+ const ns = identityNamespace(identity);
533
+ await call((c) => new c.Delete({ ...scope, keys: [vectorKey(ns, id)] }));
534
+ },
535
+ async seen() {
536
+ // TRUE, not a stub: nothing can be recorded here (see `recordSignature`),
537
+ // so nothing has been.
538
+ return false;
539
+ },
540
+ async recordSignature() {
541
+ return refuse('recordSignature', 'a recognition set is a set of strings, and this index stores vectors', 'accepting the signature and dropping it would make seen() answer false forever ' +
542
+ 'while looking like a working dedup', 'give the write pipeline a store with a set primitive (RedisStore) and keep the ' +
543
+ 'corpus here — a corpus registered through defineRAG is read-only and never ' +
544
+ 'records signatures at all');
545
+ },
546
+ async feedback() {
547
+ return refuse('feedback', 'a running usefulness average needs a read-modify-write this index cannot do', 'silently dropping the signal would leave getFeedback() answering null forever ' +
548
+ 'while the calls that fed it looked successful', 'record usefulness in a store built for counters (RedisStore), or collect it in ' +
549
+ 'your own telemetry from the agentfootprint.memory.retrieved events');
550
+ },
551
+ async getFeedback() {
552
+ // TRUE, not a stub: no feedback can be recorded here, so none has been.
553
+ return null;
554
+ },
555
+ async forget(identity) {
556
+ open('forget a namespace');
557
+ const ns = identityNamespace(identity);
558
+ const prefix = `${ns}#`;
559
+ let token;
560
+ do {
561
+ const out = (await call((c) => new c.List({
562
+ ...scope,
563
+ maxResults: 500,
564
+ ...(token !== undefined && { nextToken: token }),
565
+ })));
566
+ token = out?.nextToken;
567
+ const keys = (out?.vectors ?? [])
568
+ .map((v) => v.key)
569
+ .filter((k) => typeof k === 'string' && k.startsWith(prefix));
570
+ // Deleted page by page rather than collected and deleted at the end: a
571
+ // GDPR erasure that fails half way should have erased half, not
572
+ // nothing.
573
+ for (let i = 0; i < keys.length; i += batchSize) {
574
+ await call((c) => new c.Delete({ ...scope, keys: keys.slice(i, i + batchSize) }));
575
+ }
576
+ } while (token !== undefined);
577
+ fingerprints.delete(ns);
578
+ },
579
+ async search(identity, query, searchOptions) {
580
+ open('search');
581
+ const ns = identityNamespace(identity);
582
+ const k = Math.max(1, Math.floor(searchOptions?.k ?? 10));
583
+ if (query.length === 0)
584
+ return [];
585
+ // The index's own dimension, which outranks anything this process has
586
+ // merely SEEN: a fresh process searching an index built for another
587
+ // embedder has no stored fingerprint to disagree with.
588
+ assertDimension(await verifyIndex(), query.length, 'search');
589
+ // Refused BEFORE the call, against what this process has seen — and
590
+ // again below, against what actually comes back.
591
+ reconcile(ns, {
592
+ ...(searchOptions?.embedderId !== undefined && { id: searchOptions.embedderId }),
593
+ dims: query.length,
594
+ }, 'search');
595
+ const tiers = searchOptions?.tiers;
596
+ const nsClause = { [NS_KEY]: { $eq: ns } };
597
+ const filter = tiers && tiers.length > 0
598
+ ? { $and: [nsClause, { [TIER_KEY]: { $in: [...tiers] } }] }
599
+ : nsClause;
600
+ const out = (await call((c) => new c.Query({
601
+ ...scope,
602
+ queryVector: { float32: [...query] },
603
+ topK: k,
604
+ filter,
605
+ returnMetadata: true,
606
+ returnDistance: true,
607
+ })));
608
+ const incoming = {
609
+ ...(searchOptions?.embedderId !== undefined && { id: searchOptions.embedderId }),
610
+ dims: query.length,
611
+ };
612
+ const now = Date.now();
613
+ const minScore = searchOptions?.minScore;
614
+ const scored = [];
615
+ for (const row of out?.vectors ?? []) {
616
+ // The restart-surviving half of the fingerprint check: these documents
617
+ // carry the fingerprint they were written with, and a swap shows up
618
+ // here, on the first query, before a single ranking is returned.
619
+ const storedFp = readMetaString(row, FP_KEY);
620
+ if (storedFp !== undefined) {
621
+ const conflict = fingerprintConflict(parseFingerprint(storedFp), incoming);
622
+ if (conflict !== null) {
623
+ throw new EmbedderMismatchError(ns, storedFp, fingerprintText(incoming), conflict, 'search', 'point this store at a different index');
624
+ }
625
+ }
626
+ const entry = vectorToEntry(row);
627
+ if (!entry)
628
+ continue;
629
+ if (entry.ttl !== undefined && entry.ttl <= now)
630
+ continue;
631
+ // Cosine distance to cosine similarity. Exact, not a rescaling — which
632
+ // is why a euclidean index is refused at construction rather than
633
+ // approximated here.
634
+ const distance = typeof row.distance === 'number' ? row.distance : undefined;
635
+ if (distance === undefined)
636
+ continue;
637
+ const score = 1 - distance;
638
+ if (minScore !== undefined && score < minScore)
639
+ continue;
640
+ scored.push({ entry, score });
641
+ }
642
+ // S3 Vectors returns its own ranking; re-sort anyway so the port's
643
+ // "descending by score" holds even if a future API version reorders.
644
+ scored.sort((a, b) => {
645
+ if (b.score !== a.score)
646
+ return b.score - a.score;
647
+ return a.entry.id < b.entry.id ? -1 : a.entry.id > b.entry.id ? 1 : 0;
648
+ });
649
+ return scored.slice(0, k);
650
+ },
651
+ close() {
652
+ if (closed)
653
+ return;
654
+ closed = true;
655
+ if (connection?.owned)
656
+ connection.client.destroy?.();
657
+ },
658
+ };
659
+ return store;
660
+ }
661
+ // ─── Refusals ────────────────────────────────────────────────────────
662
+ /** One shape for every "a vector index cannot do this" refusal. */
663
+ function refuse(method, because, why, fix) {
664
+ throw new Error(`s3VectorsStore.${method}: not supported — ${because}.\n` +
665
+ ` This refuses rather than accepting the call: ${why}.\n` +
666
+ ` Fix: ${fix}.`);
667
+ }
668
+ // ─── Keys, payloads, rows ────────────────────────────────────────────
669
+ /**
670
+ * `'<namespace>#<id>'`.
671
+ *
672
+ * The namespace is in the KEY as well as in the metadata, and the redundancy is
673
+ * deliberate: `search` filters server-side on the metadata, while `list` and
674
+ * `forget` need to select a namespace out of a page of keys, which ListVectors
675
+ * gives no filter for.
676
+ */
677
+ function vectorKey(namespace, id) {
678
+ return `${namespace}#${id}`;
679
+ }
680
+ /** The entry id back out of a key. Ids may contain `#` (`'refunds.md#3'`); namespaces may not. */
681
+ function idFromKey(key, prefixLength) {
682
+ return key.slice(prefixLength);
683
+ }
684
+ function payloadOf(entry) {
685
+ // The embedding is deliberately NOT in here: it is the vector itself, and
686
+ // storing it twice would double the metadata budget for nothing.
687
+ return {
688
+ id: entry.id,
689
+ value: entry.value ?? null,
690
+ ...(entry.metadata !== undefined && { metadata: { ...entry.metadata } }),
691
+ version: entry.version,
692
+ createdAt: entry.createdAt,
693
+ updatedAt: entry.updatedAt,
694
+ lastAccessedAt: entry.lastAccessedAt,
695
+ accessCount: entry.accessCount,
696
+ ...(entry.ttl !== undefined && { ttl: entry.ttl }),
697
+ ...(entry.tier !== undefined && { tier: entry.tier }),
698
+ ...(entry.source !== undefined && { source: entry.source }),
699
+ ...(entry.embeddingModel !== undefined && { embeddingModel: entry.embeddingModel }),
700
+ };
701
+ }
702
+ function readMetaString(row, key) {
703
+ const value = row.metadata?.[key];
704
+ return typeof value === 'string' ? value : undefined;
705
+ }
706
+ /**
707
+ * A returned vector back into a `MemoryEntry`, or `undefined` when the row
708
+ * carries no payload this store wrote.
709
+ *
710
+ * A row without `af` is not corruption to shout about — it is somebody else's
711
+ * vector in a shared index — so it is skipped rather than thrown on. A row
712
+ * whose `af` will not parse is the same fact one level down.
713
+ */
714
+ function vectorToEntry(row) {
715
+ const raw = readMetaString(row, PAYLOAD_KEY);
716
+ if (raw === undefined)
717
+ return undefined;
718
+ let payload;
719
+ try {
720
+ payload = JSON.parse(raw);
721
+ }
722
+ catch {
723
+ return undefined;
724
+ }
725
+ const ns = readMetaString(row, NS_KEY);
726
+ const id = typeof payload.id === 'string' && payload.id.length > 0
727
+ ? payload.id
728
+ : typeof row.key === 'string' && ns !== undefined
729
+ ? idFromKey(row.key, ns.length + 1)
730
+ : undefined;
731
+ if (id === undefined)
732
+ return undefined;
733
+ const vector = Array.isArray(row.data) ? row.data : row.data?.float32;
734
+ return {
735
+ id,
736
+ value: payload.value,
737
+ ...(payload.metadata !== undefined && { metadata: payload.metadata }),
738
+ version: payload.version ?? 1,
739
+ createdAt: payload.createdAt ?? 0,
740
+ updatedAt: payload.updatedAt ?? 0,
741
+ lastAccessedAt: payload.lastAccessedAt ?? 0,
742
+ accessCount: payload.accessCount ?? 0,
743
+ ...(payload.ttl !== undefined && { ttl: payload.ttl }),
744
+ ...(payload.tier !== undefined && { tier: payload.tier }),
745
+ ...(payload.source !== undefined && { source: payload.source }),
746
+ ...(payload.embeddingModel !== undefined && { embeddingModel: payload.embeddingModel }),
747
+ ...(Array.isArray(vector) && vector.length > 0 && { embedding: [...vector] }),
748
+ };
749
+ }
750
+ function isExpired(ttl) {
751
+ return ttl !== undefined && ttl <= Date.now();
752
+ }
753
+ // ─── SDK loading ─────────────────────────────────────────────────────
754
+ /** A no-op command shim: an injected `_client` receives the input, stamped with its name. */
755
+ function shimCommand(name) {
756
+ return class {
757
+ __command = name;
758
+ constructor(input) {
759
+ Object.assign(this, input);
760
+ }
761
+ };
762
+ }
763
+ function loadS3VectorsSdk() {
764
+ try {
765
+ return lazyRequire('@aws-sdk/client-s3vectors');
766
+ }
767
+ catch {
768
+ throw new Error('s3VectorsStore requires the `@aws-sdk/client-s3vectors` peer dependency.\n' +
769
+ ' Install: npm install @aws-sdk/client-s3vectors\n' +
770
+ ' Or pass `client` with a pre-built S3 Vectors client.\n' +
771
+ ' There is deliberately no fallback to an in-memory index: a corpus that forgot ' +
772
+ 'every document on restart looks, from the outside, exactly like one that was ' +
773
+ 'never built.');
774
+ }
775
+ }
776
+ //# sourceMappingURL=s3Vectors.js.map