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