@crewhaus/tool-retrieve 0.6.0 → 0.8.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/LICENSE +201 -0
- package/NOTICE +9 -0
- package/README.md +11 -0
- package/dist/index.d.ts +51 -1
- package/dist/index.js +160 -13
- package/package.json +14 -9
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
CrewHaus Factory
|
|
2
|
+
Copyright 2026 Max Meier
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Max Meier
|
|
5
|
+
(operating as StudioMax — https://studiomax.io) and contributors.
|
|
6
|
+
|
|
7
|
+
The CrewHaus name and logo are trademarks of Max Meier. See
|
|
8
|
+
https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
|
|
9
|
+
use-of-marks policy.
|
package/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @crewhaus/tool-retrieve
|
|
2
|
+
|
|
3
|
+
Retrieve(query, k?, filter?) tool — composes embedder + vector-store
|
|
4
|
+
|
|
5
|
+
Part of [CrewHaus](https://github.com/crewhaus/factory). Most people install the CLI (`npm install -g crewhaus`) rather than this package.
|
|
6
|
+
|
|
7
|
+
Which tools a spec can turn on, and how: [tools reference](https://github.com/crewhaus/docs/blob/main/TOOLS-REFERENCE.md).
|
|
8
|
+
|
|
9
|
+
Requires [Bun](https://bun.sh) `>=1.3.14`; plain Node is not supported.
|
|
10
|
+
|
|
11
|
+
[Source](https://github.com/crewhaus/factory/tree/main/packages/tool-retrieve)
|
package/dist/index.d.ts
CHANGED
|
@@ -60,7 +60,19 @@ export declare function registerRetrieveConfig(input: RetrieveConfigInput): void
|
|
|
60
60
|
export declare function getRetrieveConfig(): RetrieveConfig | undefined;
|
|
61
61
|
/** Test-only — clear cached config. */
|
|
62
62
|
export declare function _resetRetrieveConfig(): void;
|
|
63
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Whether a Retrieve bound to this embedder and vector store stays inside the
|
|
65
|
+
* process: only `@crewhaus/embedder`'s `mock` provider over an `in-memory` or
|
|
66
|
+
* on-disk `lance` store does. Every other embedder POSTs the query to its
|
|
67
|
+
* provider, and qdrant, pinecone and weaviate are HTTP services.
|
|
68
|
+
*/
|
|
69
|
+
export declare function retrieveStaysLocal(embedder: Pick<Embedder, "provider">, vectorStore: Pick<VectorStore, "backend">): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* The pipeline shape's `Retrieve`: a live binding that
|
|
72
|
+
* {@link registerRetrieveConfig} replaces with a tool bound to the config it
|
|
73
|
+
* registers, flagged from those backends (see {@link retrieveStaysLocal}).
|
|
74
|
+
*/
|
|
75
|
+
export declare let retrieve: RegisteredTool;
|
|
64
76
|
/** The target's default embedder model when nothing else resolves (G76). A
|
|
65
77
|
* vector store needs embeddings, so knowledge RAG never degrades to BM25 —
|
|
66
78
|
* this is the floor {@link resolveKnowledgeEmbedder} lands on. Mirrors the
|
|
@@ -163,6 +175,44 @@ export type KnowledgeRetrieveConfig = {
|
|
|
163
175
|
/** Boot status-line sink (`[knowledge] …`). Compiled bundles stay silent. */
|
|
164
176
|
readonly log?: (line: string) => void;
|
|
165
177
|
};
|
|
178
|
+
/**
|
|
179
|
+
* How a `url` knowledge source is named wherever it can be seen: its
|
|
180
|
+
* document id and `docId` (so every chunk id, and every Retrieve hit the
|
|
181
|
+
* model reads), and boot errors. A private document is often reached with a
|
|
182
|
+
* credential in its URL (`?private_token=`, a presigned `X-Amz-Signature`,
|
|
183
|
+
* `user:token@`), and the URL is fetched as written; only its label is
|
|
184
|
+
* cleaned.
|
|
185
|
+
*
|
|
186
|
+
* - A URL with nothing credential-shaped in it is its own label, so the ids
|
|
187
|
+
* of existing clean sources do not move.
|
|
188
|
+
* - Otherwise the userinfo is replaced, credential-shaped query values are
|
|
189
|
+
* redacted, the fragment is dropped, and `#src-<12 hex>` of the full URL
|
|
190
|
+
* is appended, so two sources that differ only by a token stay distinct
|
|
191
|
+
* and the id is the same on every boot.
|
|
192
|
+
*
|
|
193
|
+
* Finding the userinfo cannot be left to the URL parser. A password may
|
|
194
|
+
* hold `/`, `?` or `#`, which end the authority before its `@`:
|
|
195
|
+
* `https://id:1234/rest@host` even parses, as host `id`, port 1234 and a
|
|
196
|
+
* path holding the rest of the secret. So when an `@` could be the end of a
|
|
197
|
+
* userinfo (the URL does not parse, the parser found a userinfo, or the
|
|
198
|
+
* authority it saw has a `:`), everything up to the LAST `@` is replaced;
|
|
199
|
+
* when a `?` or `#` comes before that `@`, nothing after the scheme can be
|
|
200
|
+
* told apart from the secret, and all of it is replaced. An `@` the parser
|
|
201
|
+
* places in the path or query of a URL with no userinfo and no port (npm's
|
|
202
|
+
* `/@scope/`) is left alone.
|
|
203
|
+
*
|
|
204
|
+
* With a port, an `@` later in the path hides the host too
|
|
205
|
+
* (`https://docs.example.com:8443/guides/@team/x.md` is labelled
|
|
206
|
+
* `https://<redacted>@team/x.md#src-…`): the parser's `host:port` there may
|
|
207
|
+
* be a username and the leading digits of a password that holds a `/`, and
|
|
208
|
+
* a username is often itself a token. Boot errors therefore also name the
|
|
209
|
+
* source's position in `knowledge.sources`.
|
|
210
|
+
*/
|
|
211
|
+
export declare function knowledgeSourceLabel(raw: string): string;
|
|
212
|
+
/** The error code or name of a failed fetch, never its message or `path`:
|
|
213
|
+
* Bun's fetch errors carry the full URL in both. Exported for the CLI's
|
|
214
|
+
* `crewhaus run` knowledge loader, which names its failures the same way. */
|
|
215
|
+
export declare function fetchFailureName(cause: unknown): string;
|
|
166
216
|
/**
|
|
167
217
|
* Read every declared source into a `chunker` {@link Document}. `path` reads
|
|
168
218
|
* one file; `glob` scans the cwd for matches (a zero-match glob contributes
|
package/dist/index.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
* Layer R12. Pairs with `embedder`, `vector-store`, `chunker`,
|
|
22
22
|
* `pipeline-engine`, `target-pipeline`, `target-cli`/`-channel-bot`/`-managed`.
|
|
23
23
|
*/
|
|
24
|
+
import { createHash } from "node:crypto";
|
|
24
25
|
import { existsSync } from "node:fs";
|
|
25
26
|
import { readFile } from "node:fs/promises";
|
|
26
27
|
import { isAbsolute, resolve as resolvePath } from "node:path";
|
|
@@ -28,6 +29,7 @@ import { chunk } from "@crewhaus/chunker";
|
|
|
28
29
|
import { createEmbedder } from "@crewhaus/embedder";
|
|
29
30
|
import { CrewhausError } from "@crewhaus/errors";
|
|
30
31
|
import { buildTool } from "@crewhaus/tool-builder";
|
|
32
|
+
import { redactUrlCredentials, redactUrlCredentialsInText } from "@crewhaus/tool-safety/env";
|
|
31
33
|
import { createVectorStore } from "@crewhaus/vector-store";
|
|
32
34
|
import { z } from "zod";
|
|
33
35
|
export class RetrieveConfigError extends CrewhausError {
|
|
@@ -57,13 +59,23 @@ export function registerRetrieveConfig(input) {
|
|
|
57
59
|
if (embedder === undefined) {
|
|
58
60
|
throw new RetrieveConfigError("registerRetrieveConfig requires either an `embedder` instance or `embedderModel` string");
|
|
59
61
|
}
|
|
60
|
-
|
|
62
|
+
const bound = {
|
|
61
63
|
embedder,
|
|
62
64
|
vectorStore,
|
|
63
65
|
...((input.defaultK ?? input.default_k !== undefined)
|
|
64
66
|
? { defaultK: input.defaultK ?? input.default_k }
|
|
65
67
|
: {}),
|
|
66
68
|
};
|
|
69
|
+
activeConfig = bound;
|
|
70
|
+
// The singleton is rebuilt for this config, so its flags say where THESE
|
|
71
|
+
// backends are: a mock embedder over an in-memory or lance store stays in
|
|
72
|
+
// the process (the RAG starter), anything else reaches the network. Both
|
|
73
|
+
// hosts register the config before they register `retrieve`, and read it
|
|
74
|
+
// through the live ESM binding. The rebuilt tool keeps this config, so a
|
|
75
|
+
// later registration cannot make a tool flagged local reach the network.
|
|
76
|
+
retrieve = makeRetrieveTool(() => bound, {
|
|
77
|
+
local: retrieveStaysLocal(embedder, vectorStore),
|
|
78
|
+
});
|
|
67
79
|
}
|
|
68
80
|
export function getRetrieveConfig() {
|
|
69
81
|
return activeConfig;
|
|
@@ -71,6 +83,7 @@ export function getRetrieveConfig() {
|
|
|
71
83
|
/** Test-only — clear cached config. */
|
|
72
84
|
export function _resetRetrieveConfig() {
|
|
73
85
|
activeConfig = undefined;
|
|
86
|
+
retrieve = unconfiguredRetrieve;
|
|
74
87
|
}
|
|
75
88
|
const retrieveSchema = z.object({
|
|
76
89
|
query: z.string().min(1),
|
|
@@ -83,26 +96,54 @@ function formatHits(hits) {
|
|
|
83
96
|
const lines = [];
|
|
84
97
|
hits.forEach((h, i) => {
|
|
85
98
|
const text = h.metadata?.["text"] ?? "";
|
|
86
|
-
|
|
99
|
+
// A persistent store indexed before 0.7.1 still holds ids built from
|
|
100
|
+
// the raw source URL; whatever it holds, no credential is shown.
|
|
101
|
+
const docId = redactUrlCredentialsInText(h.metadata?.["docId"] ?? "?");
|
|
102
|
+
const id = redactUrlCredentialsInText(h.id);
|
|
87
103
|
const preview = text.length > 280 ? `${text.slice(0, 280)}…` : text;
|
|
88
|
-
lines.push(`[${i + 1}] id=${
|
|
104
|
+
lines.push(`[${i + 1}] id=${id} doc=${docId} score=${h.score.toFixed(4)}\n${preview}`);
|
|
89
105
|
});
|
|
90
106
|
return lines.join("\n\n");
|
|
91
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Whether a Retrieve bound to this embedder and vector store stays inside the
|
|
110
|
+
* process: only `@crewhaus/embedder`'s `mock` provider over an `in-memory` or
|
|
111
|
+
* on-disk `lance` store does. Every other embedder POSTs the query to its
|
|
112
|
+
* provider, and qdrant, pinecone and weaviate are HTTP services.
|
|
113
|
+
*/
|
|
114
|
+
export function retrieveStaysLocal(embedder, vectorStore) {
|
|
115
|
+
return (embedder.provider === "mock" &&
|
|
116
|
+
(vectorStore.backend === "in-memory" || vectorStore.backend === "lance"));
|
|
117
|
+
}
|
|
92
118
|
/**
|
|
93
119
|
* Build a `Retrieve` tool whose backends come from `getConfig` at call time.
|
|
94
120
|
* Shared by the singleton `retrieve` export (pipeline shape — reads
|
|
95
121
|
* `activeConfig`) and every {@link knowledgeRetrieve} tool (agent shape —
|
|
96
|
-
* reads its own captured, already-ingested config), so the schema
|
|
97
|
-
* citation formatting
|
|
122
|
+
* reads its own captured, already-ingested config), so the schema and
|
|
123
|
+
* citation formatting never fork between the two paths.
|
|
124
|
+
*
|
|
125
|
+
* Retrieve sends the model's query to the configured embedding provider, and
|
|
126
|
+
* to the vector store when that is an HTTP service, so it is
|
|
127
|
+
* `scope: "external"` with `ioCapability: "network"`: the query goes through
|
|
128
|
+
* the egress classifier and `compile --strict` counts it. It stays
|
|
129
|
+
* `readOnly`, and the destination is the operator's configuration, never one
|
|
130
|
+
* the model picks. A tool whose backends are known to stay in the process
|
|
131
|
+
* (`local: true`, see {@link retrieveStaysLocal}) is internal: a knowledge
|
|
132
|
+
* tool, and the pipeline singleton once its config is registered.
|
|
98
133
|
*/
|
|
99
|
-
function makeRetrieveTool(getConfig) {
|
|
134
|
+
function makeRetrieveTool(getConfig, opts = {}) {
|
|
100
135
|
return buildTool({
|
|
101
136
|
name: "Retrieve",
|
|
102
137
|
description: "Retrieve top-k chunks from the configured vector store for a natural-language query. Pass `query` (required), optional `k` (default 5), and optional `filter` (metadata predicates). Returns a numbered list of hits with citations.",
|
|
103
138
|
inputSchema: retrieveSchema,
|
|
139
|
+
// No argument decides where it acts: the query goes to the configured
|
|
140
|
+
// embedder and vector store. (Matched exactly as if undeclared.)
|
|
141
|
+
operativeArgs: [],
|
|
104
142
|
readOnly: true,
|
|
105
143
|
concurrencySafe: true,
|
|
144
|
+
...(opts.local === true
|
|
145
|
+
? { scope: "internal" }
|
|
146
|
+
: { scope: "external", ioCapability: "network" }),
|
|
106
147
|
execute: async (input) => {
|
|
107
148
|
const cfg = getConfig();
|
|
108
149
|
if (cfg === undefined) {
|
|
@@ -119,7 +160,18 @@ function makeRetrieveTool(getConfig) {
|
|
|
119
160
|
},
|
|
120
161
|
});
|
|
121
162
|
}
|
|
122
|
-
|
|
163
|
+
/**
|
|
164
|
+
* The pipeline `Retrieve` before any config is registered. Its backends are
|
|
165
|
+
* not known yet, so it says it reaches the network; it reads whatever config
|
|
166
|
+
* is registered when it runs.
|
|
167
|
+
*/
|
|
168
|
+
const unconfiguredRetrieve = makeRetrieveTool(() => activeConfig);
|
|
169
|
+
/**
|
|
170
|
+
* The pipeline shape's `Retrieve`: a live binding that
|
|
171
|
+
* {@link registerRetrieveConfig} replaces with a tool bound to the config it
|
|
172
|
+
* registers, flagged from those backends (see {@link retrieveStaysLocal}).
|
|
173
|
+
*/
|
|
174
|
+
export let retrieve = unconfiguredRetrieve;
|
|
123
175
|
// ===========================================================================
|
|
124
176
|
// Agent-shape RAG — `knowledge:` on cli/channel/managed (Batch E item 3, G22)
|
|
125
177
|
// ===========================================================================
|
|
@@ -161,6 +213,93 @@ function firstNonEmpty(...values) {
|
|
|
161
213
|
export function resolveKnowledgeEmbedder(inputs) {
|
|
162
214
|
return (firstNonEmpty(inputs.knowledgeEmbedder, inputs.memoryEmbedder, inputs.wikiEmbedder, inputs.targetDefault) ?? DEFAULT_KNOWLEDGE_EMBEDDER_MODEL);
|
|
163
215
|
}
|
|
216
|
+
/**
|
|
217
|
+
* How a `url` knowledge source is named wherever it can be seen: its
|
|
218
|
+
* document id and `docId` (so every chunk id, and every Retrieve hit the
|
|
219
|
+
* model reads), and boot errors. A private document is often reached with a
|
|
220
|
+
* credential in its URL (`?private_token=`, a presigned `X-Amz-Signature`,
|
|
221
|
+
* `user:token@`), and the URL is fetched as written; only its label is
|
|
222
|
+
* cleaned.
|
|
223
|
+
*
|
|
224
|
+
* - A URL with nothing credential-shaped in it is its own label, so the ids
|
|
225
|
+
* of existing clean sources do not move.
|
|
226
|
+
* - Otherwise the userinfo is replaced, credential-shaped query values are
|
|
227
|
+
* redacted, the fragment is dropped, and `#src-<12 hex>` of the full URL
|
|
228
|
+
* is appended, so two sources that differ only by a token stay distinct
|
|
229
|
+
* and the id is the same on every boot.
|
|
230
|
+
*
|
|
231
|
+
* Finding the userinfo cannot be left to the URL parser. A password may
|
|
232
|
+
* hold `/`, `?` or `#`, which end the authority before its `@`:
|
|
233
|
+
* `https://id:1234/rest@host` even parses, as host `id`, port 1234 and a
|
|
234
|
+
* path holding the rest of the secret. So when an `@` could be the end of a
|
|
235
|
+
* userinfo (the URL does not parse, the parser found a userinfo, or the
|
|
236
|
+
* authority it saw has a `:`), everything up to the LAST `@` is replaced;
|
|
237
|
+
* when a `?` or `#` comes before that `@`, nothing after the scheme can be
|
|
238
|
+
* told apart from the secret, and all of it is replaced. An `@` the parser
|
|
239
|
+
* places in the path or query of a URL with no userinfo and no port (npm's
|
|
240
|
+
* `/@scope/`) is left alone.
|
|
241
|
+
*
|
|
242
|
+
* With a port, an `@` later in the path hides the host too
|
|
243
|
+
* (`https://docs.example.com:8443/guides/@team/x.md` is labelled
|
|
244
|
+
* `https://<redacted>@team/x.md#src-…`): the parser's `host:port` there may
|
|
245
|
+
* be a username and the leading digits of a password that holds a `/`, and
|
|
246
|
+
* a username is often itself a token. Boot errors therefore also name the
|
|
247
|
+
* source's position in `knowledge.sources`.
|
|
248
|
+
*/
|
|
249
|
+
export function knowledgeSourceLabel(raw) {
|
|
250
|
+
const fingerprint = () => createHash("sha256")
|
|
251
|
+
.update("crewhaus/knowledge-source\u0000")
|
|
252
|
+
.update(raw)
|
|
253
|
+
.digest("hex")
|
|
254
|
+
.slice(0, 12);
|
|
255
|
+
const withoutFragment = (text) => {
|
|
256
|
+
const hashAt = text.indexOf("#");
|
|
257
|
+
return hashAt === -1 ? text : text.slice(0, hashAt);
|
|
258
|
+
};
|
|
259
|
+
const schemeMatch = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.exec(raw);
|
|
260
|
+
const scheme = schemeMatch === null ? "" : schemeMatch[0];
|
|
261
|
+
const rest = raw.slice(scheme.length);
|
|
262
|
+
let parsed;
|
|
263
|
+
try {
|
|
264
|
+
parsed = new URL(raw);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
parsed = undefined;
|
|
268
|
+
}
|
|
269
|
+
const lastAt = rest.lastIndexOf("@");
|
|
270
|
+
if (lastAt !== -1) {
|
|
271
|
+
const authority = rest.split(/[/\\?#]/, 1)[0] ?? "";
|
|
272
|
+
const mayBeUserinfo = parsed === undefined ||
|
|
273
|
+
parsed.username !== "" ||
|
|
274
|
+
parsed.password !== "" ||
|
|
275
|
+
authority.includes(":") ||
|
|
276
|
+
authority.includes("@");
|
|
277
|
+
if (mayBeUserinfo) {
|
|
278
|
+
if (/[?#]/.test(rest.slice(0, lastAt)))
|
|
279
|
+
return `${scheme}<redacted>#src-${fingerprint()}`;
|
|
280
|
+
const tail = withoutFragment(redactUrlCredentials(`${scheme}${rest.slice(lastAt + 1)}`));
|
|
281
|
+
return `${scheme}<redacted>@${tail.slice(scheme.length)}#src-${fingerprint()}`;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
const shown = redactUrlCredentials(raw);
|
|
285
|
+
if (shown === raw || parsed === undefined)
|
|
286
|
+
return shown;
|
|
287
|
+
return `${withoutFragment(shown)}#src-${fingerprint()}`;
|
|
288
|
+
}
|
|
289
|
+
/** The error code or name of a failed fetch, never its message or `path`:
|
|
290
|
+
* Bun's fetch errors carry the full URL in both. Exported for the CLI's
|
|
291
|
+
* `crewhaus run` knowledge loader, which names its failures the same way. */
|
|
292
|
+
export function fetchFailureName(cause) {
|
|
293
|
+
if (typeof cause === "object" && cause !== null) {
|
|
294
|
+
const code = cause.code;
|
|
295
|
+
if (typeof code === "string" && /^[A-Za-z0-9_]{1,64}$/.test(code))
|
|
296
|
+
return code;
|
|
297
|
+
const name = cause.name;
|
|
298
|
+
if (typeof name === "string" && /^[A-Za-z0-9_]{1,64}$/.test(name))
|
|
299
|
+
return name;
|
|
300
|
+
}
|
|
301
|
+
return "fetch error";
|
|
302
|
+
}
|
|
164
303
|
/**
|
|
165
304
|
* Read every declared source into a `chunker` {@link Document}. `path` reads
|
|
166
305
|
* one file; `glob` scans the cwd for matches (a zero-match glob contributes
|
|
@@ -173,7 +312,7 @@ export async function loadKnowledgeSources(sources, opts = {}) {
|
|
|
173
312
|
const cwd = opts.cwd ?? process.cwd();
|
|
174
313
|
const fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
175
314
|
const docs = [];
|
|
176
|
-
for (const src of sources) {
|
|
315
|
+
for (const [position, src] of sources.entries()) {
|
|
177
316
|
if (src.kind === "path") {
|
|
178
317
|
const abs = isAbsolute(src.path) ? src.path : resolvePath(cwd, src.path);
|
|
179
318
|
if (!existsSync(abs)) {
|
|
@@ -208,21 +347,29 @@ export async function loadKnowledgeSources(sources, opts = {}) {
|
|
|
208
347
|
}
|
|
209
348
|
}
|
|
210
349
|
else {
|
|
350
|
+
// Fetched as written; named everywhere else by its cleaned label. A
|
|
351
|
+
// label can hide the host (see knowledgeSourceLabel), so a boot error
|
|
352
|
+
// also names the source's position, which always identifies it.
|
|
353
|
+
const label = knowledgeSourceLabel(src.url);
|
|
354
|
+
const where = `knowledge.sources[${position}]`;
|
|
211
355
|
if (fetchImpl === undefined) {
|
|
212
|
-
throw new RetrieveConfigError(`knowledge url source needs a fetch implementation: ${
|
|
356
|
+
throw new RetrieveConfigError(`knowledge url source needs a fetch implementation: ${where} ${label}`);
|
|
213
357
|
}
|
|
214
358
|
let res;
|
|
215
359
|
try {
|
|
216
360
|
res = await fetchImpl(src.url);
|
|
217
361
|
}
|
|
218
362
|
catch (cause) {
|
|
219
|
-
|
|
363
|
+
// The runtime's error quotes the URL (message and `path`), so only
|
|
364
|
+
// its code travels on.
|
|
365
|
+
const reason = fetchFailureName(cause);
|
|
366
|
+
throw new RetrieveConfigError(`knowledge url fetch failed (${reason}): ${where} ${label}`, new Error(reason));
|
|
220
367
|
}
|
|
221
368
|
if (!res.ok) {
|
|
222
|
-
throw new RetrieveConfigError(`knowledge url fetch failed (${res.status}): ${
|
|
369
|
+
throw new RetrieveConfigError(`knowledge url fetch failed (${res.status}): ${where} ${label}`);
|
|
223
370
|
}
|
|
224
371
|
const text = await res.text();
|
|
225
|
-
docs.push({ id:
|
|
372
|
+
docs.push({ id: label, text, metadata: { docId: label, source: label } });
|
|
226
373
|
}
|
|
227
374
|
}
|
|
228
375
|
return docs;
|
|
@@ -291,5 +438,5 @@ export async function knowledgeRetrieve(config) {
|
|
|
291
438
|
vectorStore,
|
|
292
439
|
defaultK: config.defaultK ?? DEFAULT_KNOWLEDGE_K,
|
|
293
440
|
};
|
|
294
|
-
return makeRetrieveTool(() => bound);
|
|
441
|
+
return makeRetrieveTool(() => bound, { local: retrieveStaysLocal(embedder, vectorStore) });
|
|
295
442
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/tool-retrieve",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Retrieve(query, k?, filter?) tool — composes embedder + vector-store",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -8,19 +8,21 @@
|
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
|
-
"import": "./dist/index.js"
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
12
13
|
}
|
|
13
14
|
},
|
|
14
15
|
"scripts": {
|
|
15
16
|
"test": "bun test src"
|
|
16
17
|
},
|
|
17
18
|
"dependencies": {
|
|
18
|
-
"@crewhaus/chunker": "0.
|
|
19
|
-
"@crewhaus/embedder": "0.
|
|
20
|
-
"@crewhaus/errors": "0.
|
|
21
|
-
"@crewhaus/tool-builder": "0.
|
|
22
|
-
"@crewhaus/tool-catalog": "0.
|
|
23
|
-
"@crewhaus/
|
|
19
|
+
"@crewhaus/chunker": "0.8.0",
|
|
20
|
+
"@crewhaus/embedder": "0.8.0",
|
|
21
|
+
"@crewhaus/errors": "0.8.0",
|
|
22
|
+
"@crewhaus/tool-builder": "0.8.0",
|
|
23
|
+
"@crewhaus/tool-catalog": "0.8.0",
|
|
24
|
+
"@crewhaus/tool-safety": "0.8.0",
|
|
25
|
+
"@crewhaus/vector-store": "0.8.0",
|
|
24
26
|
"zod": "^3.23.8"
|
|
25
27
|
},
|
|
26
28
|
"license": "Apache-2.0",
|
|
@@ -41,5 +43,8 @@
|
|
|
41
43
|
"publishConfig": {
|
|
42
44
|
"access": "public"
|
|
43
45
|
},
|
|
44
|
-
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
46
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"],
|
|
47
|
+
"engines": {
|
|
48
|
+
"bun": ">=1.3.14"
|
|
49
|
+
}
|
|
45
50
|
}
|