@qvac/harness 1.0.0-rc.11 → 1.0.0-rc.13
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/CHANGELOG.md +29 -0
- package/README.md +3 -1
- package/dist-lib/index.js +1 -2
- package/dist-lib/lib/agent/follow.js +9 -2
- package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +13 -3
- package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +11 -6
- package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.d.ts +2 -1
- package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +19 -11
- package/dist-lib/lib/capabilities/completion-engine/actors/stream.d.ts +3 -2
- package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +21 -3
- package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +11 -2
- package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +4 -0
- package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
- package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
- package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
- package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
- package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
- package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +4 -1
- package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
- package/dist-lib/lib/capabilities/completion-engine/round.d.ts +11 -0
- package/dist-lib/lib/capabilities/completion-engine/round.js +41 -22
- package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
- package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
- package/dist-lib/lib/capabilities/tool-failed-note.d.ts +1 -0
- package/dist-lib/lib/capabilities/tool-failed-note.js +1 -0
- package/dist-lib/lib/capabilities/tool-turns.d.ts +3 -1
- package/dist-lib/lib/capabilities/tool-turns.js +8 -1
- package/dist-lib/lib/connect.js +4 -2
- package/dist-lib/lib/contract/completion.d.ts +2 -1
- package/dist-lib/lib/contract/knowledge.d.ts +10 -0
- package/dist-lib/lib/fold/index.d.ts +3 -2
- package/dist-lib/lib/fold/index.js +7 -6
- package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
- package/dist-lib/lib/helpers/goal-check.js +89 -7
- package/dist-lib/lib/helpers/html-helpers.js +9 -6
- package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
- package/dist-lib/lib/helpers/input-budget.js +9 -0
- package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
- package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
- package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
- package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
- package/dist-lib/lib/machine/completion/rules.js +14 -5
- package/dist-lib/lib/machine/completion/types.d.ts +3 -0
- package/dist-lib/lib/plugins/registry.d.ts +1 -0
- package/dist-lib/lib/plugins/registry.js +49 -10
- package/dist-lib/lib/residency/index.d.ts +1 -1
- package/dist-lib/lib/residency/index.js +4 -2
- package/dist-lib/lib/serve.js +56 -15
- package/dist-lib/lib/tools/files/glob.js +2 -2
- package/dist-lib/lib/tools/files/read-file.js +134 -15
- package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
- package/dist-lib/lib/tools/fs/walk.js +2 -1
- package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
- package/dist-lib/lib/tools/http-request.js +28 -11
- package/dist-lib/lib/tools/office.d.ts +1 -1
- package/dist-lib/lib/tools/office.js +34 -12
- package/dist-lib/lib/wire.js +23 -3
- package/dist-lib/plugins/knowledge/index.js +1 -0
- package/dist-lib/plugins/knowledge/manifest.d.ts +29 -0
- package/dist-lib/plugins/knowledge/manifest.js +41 -0
- package/dist-lib/plugins/knowledge/search-tool.js +8 -8
- package/dist-lib/plugins/knowledge/store.d.ts +35 -7
- package/dist-lib/plugins/knowledge/store.js +335 -143
- package/dist-lib/plugins/mcp/call.js +10 -3
- package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
- package/dist-lib/plugins/mcp/protocol.js +11 -10
- package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
- package/dist-lib/plugins/mcp/tool-listing.js +97 -0
- package/dist-lib/plugins/music/generate-music.js +2 -2
- package/dist-lib/plugins/python/language.js +2 -2
- package/dist-lib/plugins/run-report/story.js +4 -1
- package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
- package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
- package/dist-lib/schema/harness.js +4 -2
- package/dist-lib/spec/hrpc/messages.js +19 -4
- package/dist-lib/spec/hyperschema/index.js +19 -4
- package/dist-lib/spec/hyperschema/schema.json +12 -1
- package/dist-lib/spec/hyperschema/types.d.ts +2 -0
- package/package.json +9 -1
|
@@ -1,22 +1,12 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
3
|
import { isRecord } from '../../lib/guards.js';
|
|
4
|
-
|
|
5
|
-
const MANIFEST_FILE = 'knowledge.json';
|
|
4
|
+
import { MANIFEST_FILE, chunkIds, emptyManifest, indexedChunks, isSnapshotFile, readManifest, snapshotFile, writeManifest } from './manifest.js';
|
|
6
5
|
const DEFAULT_K = 5;
|
|
7
6
|
const DEFAULT_MIN_SCORE = 0.4;
|
|
8
7
|
const VECTOR_INDEX_NOT_FOUND = 52851;
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
function isManifest(value) {
|
|
13
|
-
return (isRecord(value) &&
|
|
14
|
-
typeof value.model === 'string' &&
|
|
15
|
-
typeof value.dimensions === 'number' &&
|
|
16
|
-
typeof value.nextId === 'number' &&
|
|
17
|
-
typeof value.seq === 'number' &&
|
|
18
|
-
isRecord(value.artifacts));
|
|
19
|
-
}
|
|
8
|
+
const PERSIST_DELAY_MS = 1000;
|
|
9
|
+
const EMBED_BATCH = 32;
|
|
20
10
|
function unit(vector) {
|
|
21
11
|
const norm = Math.hypot(...vector);
|
|
22
12
|
return norm > 0 ? vector.map((value) => value / norm) : vector;
|
|
@@ -31,6 +21,13 @@ function matches(embedding, want) {
|
|
|
31
21
|
embedding.vectors.length === want.chunks &&
|
|
32
22
|
embedding.vectors.every((row) => row.length === embedding.dimensions));
|
|
33
23
|
}
|
|
24
|
+
function sameChunks(a, b) {
|
|
25
|
+
return (a.chunks.length === b.chunks.length &&
|
|
26
|
+
a.chunks.every((chunk, at) => chunk.id === b.chunks[at]?.id));
|
|
27
|
+
}
|
|
28
|
+
function turn() {
|
|
29
|
+
return new Promise((resolve) => setImmediate(resolve));
|
|
30
|
+
}
|
|
34
31
|
function isNotFound(error) {
|
|
35
32
|
return isRecord(error) && error.code === VECTOR_INDEX_NOT_FOUND;
|
|
36
33
|
}
|
|
@@ -43,9 +40,16 @@ export class KnowledgeStore {
|
|
|
43
40
|
_manifest;
|
|
44
41
|
_index;
|
|
45
42
|
_opened;
|
|
46
|
-
|
|
43
|
+
_writes;
|
|
44
|
+
_lock;
|
|
45
|
+
_dirty;
|
|
46
|
+
_persisting;
|
|
47
|
+
_refilling;
|
|
48
|
+
_asking;
|
|
49
|
+
_answered;
|
|
50
|
+
_closed;
|
|
47
51
|
constructor({ dir, model, maxChunks = Infinity, minScore = DEFAULT_MIN_SCORE, embed }) {
|
|
48
|
-
this._dir = dir;
|
|
52
|
+
this._dir = path.resolve(dir);
|
|
49
53
|
this._model = model;
|
|
50
54
|
this._maxChunks = maxChunks;
|
|
51
55
|
this._minScore = minScore;
|
|
@@ -53,23 +57,65 @@ export class KnowledgeStore {
|
|
|
53
57
|
this._manifest = emptyManifest(model);
|
|
54
58
|
this._index = null;
|
|
55
59
|
this._opened = null;
|
|
56
|
-
this.
|
|
60
|
+
this._writes = Promise.resolve();
|
|
61
|
+
this._lock = Promise.resolve();
|
|
62
|
+
this._dirty = false;
|
|
63
|
+
this._persisting = null;
|
|
64
|
+
this._refilling = null;
|
|
65
|
+
this._closed = false;
|
|
66
|
+
this._asking = 0;
|
|
67
|
+
this._answered = null;
|
|
68
|
+
}
|
|
69
|
+
start() {
|
|
70
|
+
this._ready()
|
|
71
|
+
.then(() => this._exclusive(() => this._warm()))
|
|
72
|
+
.catch(noop);
|
|
57
73
|
}
|
|
58
74
|
upsert(artifact) {
|
|
59
|
-
return this.
|
|
75
|
+
return this._ordered(async () => {
|
|
76
|
+
await this._ready();
|
|
77
|
+
const embedded = await this._prepare(artifact);
|
|
78
|
+
return this._locked(() => this._apply(artifact, embedded));
|
|
79
|
+
});
|
|
60
80
|
}
|
|
61
81
|
remove(artifactId) {
|
|
62
|
-
return this.
|
|
82
|
+
return this._ordered(() => this._locked(async () => {
|
|
63
83
|
const removed = await this._drop(artifactId);
|
|
64
|
-
await this.
|
|
84
|
+
await this._release();
|
|
85
|
+
if (removed > 0) {
|
|
86
|
+
await this._writeOut();
|
|
87
|
+
}
|
|
65
88
|
return { removed };
|
|
66
|
-
});
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
async search(query) {
|
|
92
|
+
this._asking++;
|
|
93
|
+
try {
|
|
94
|
+
return await this._answer(query);
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
if (--this._asking === 0) {
|
|
98
|
+
this._answered?.resolve();
|
|
99
|
+
this._answered = null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
67
102
|
}
|
|
68
|
-
|
|
69
|
-
|
|
103
|
+
async _answer(query) {
|
|
104
|
+
await this._ready();
|
|
105
|
+
this._refill();
|
|
106
|
+
if ((query.k ?? DEFAULT_K) <= 0 || !this._searchable(new Set(query.scopes))) {
|
|
107
|
+
return [];
|
|
108
|
+
}
|
|
109
|
+
const [vector = []] = await this._embed.embed({
|
|
110
|
+
model: this._model,
|
|
111
|
+
texts: [query.text],
|
|
112
|
+
signal: query.signal
|
|
113
|
+
});
|
|
114
|
+
return this._locked(() => this._search(query, vector));
|
|
70
115
|
}
|
|
71
116
|
status() {
|
|
72
|
-
return this.
|
|
117
|
+
return this._locked(async () => {
|
|
118
|
+
this._refill();
|
|
73
119
|
const { model, dimensions, artifacts } = this._manifest;
|
|
74
120
|
const entries = Object.entries(artifacts).map(([artifactId, stored]) => ({
|
|
75
121
|
artifactId,
|
|
@@ -78,26 +124,65 @@ export class KnowledgeStore {
|
|
|
78
124
|
chunks: stored.chunks.length
|
|
79
125
|
}));
|
|
80
126
|
const chunks = entries.reduce((sum, entry) => sum + entry.chunks, 0);
|
|
81
|
-
return {
|
|
127
|
+
return {
|
|
128
|
+
model,
|
|
129
|
+
dimensions,
|
|
130
|
+
chunks,
|
|
131
|
+
pending: chunks - indexedChunks(this._manifest),
|
|
132
|
+
artifacts: entries
|
|
133
|
+
};
|
|
82
134
|
});
|
|
83
135
|
}
|
|
84
136
|
async close() {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
137
|
+
this._closed = true;
|
|
138
|
+
if (this._persisting) {
|
|
139
|
+
clearTimeout(this._persisting);
|
|
140
|
+
this._persisting = null;
|
|
141
|
+
}
|
|
142
|
+
await this._refilling;
|
|
143
|
+
await this._writes;
|
|
144
|
+
await this._lock;
|
|
145
|
+
try {
|
|
146
|
+
if (this._dirty) {
|
|
147
|
+
await this._exclusive(() => this._recovering(() => this._writeOut()));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
await this._index?.dispose().catch(noop);
|
|
152
|
+
this._index = null;
|
|
153
|
+
}
|
|
88
154
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
155
|
+
_quiet() {
|
|
156
|
+
if (this._asking === 0) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
this._answered ??= Promise.withResolvers();
|
|
160
|
+
return this._answered.promise;
|
|
161
|
+
}
|
|
162
|
+
_ordered(run) {
|
|
163
|
+
const job = this._writes
|
|
164
|
+
.then(turn)
|
|
165
|
+
.then(() => this._quiet())
|
|
166
|
+
.then(run);
|
|
167
|
+
this._writes = job.catch(noop);
|
|
168
|
+
return job;
|
|
169
|
+
}
|
|
170
|
+
_exclusive(run) {
|
|
171
|
+
const job = this._lock.then(run);
|
|
172
|
+
this._lock = job.catch(noop);
|
|
99
173
|
return job;
|
|
100
174
|
}
|
|
175
|
+
async _locked(run) {
|
|
176
|
+
await this._ready();
|
|
177
|
+
return this._exclusive(() => this._recovering(run));
|
|
178
|
+
}
|
|
179
|
+
_ready() {
|
|
180
|
+
this._opened ??= this._exclusive(() => this._open()).catch((error) => {
|
|
181
|
+
this._opened = null;
|
|
182
|
+
throw error;
|
|
183
|
+
});
|
|
184
|
+
return this._opened;
|
|
185
|
+
}
|
|
101
186
|
async _recovering(run) {
|
|
102
187
|
try {
|
|
103
188
|
return await run();
|
|
@@ -106,116 +191,146 @@ export class KnowledgeStore {
|
|
|
106
191
|
if (!isNotFound(error)) {
|
|
107
192
|
throw error;
|
|
108
193
|
}
|
|
109
|
-
this.
|
|
110
|
-
await this._open();
|
|
194
|
+
await this._reload();
|
|
111
195
|
return run();
|
|
112
196
|
}
|
|
113
197
|
}
|
|
114
198
|
async _open() {
|
|
115
199
|
const saved = await readManifest(this._file(MANIFEST_FILE));
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
await this._rebuild();
|
|
200
|
+
await this._sweep(snapshotFile(saved?.generation));
|
|
201
|
+
if (!saved) {
|
|
119
202
|
return;
|
|
120
203
|
}
|
|
121
|
-
this.
|
|
122
|
-
|
|
204
|
+
if (saved.model !== this._model) {
|
|
205
|
+
this._manifest = { ...saved, model: this._model, dimensions: 0 };
|
|
206
|
+
this._markPending();
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
this._manifest = saved;
|
|
210
|
+
this._index = await this._load(saved);
|
|
211
|
+
if (!this._index) {
|
|
212
|
+
this._markPending();
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
this._refill();
|
|
216
|
+
}
|
|
217
|
+
async _load(saved) {
|
|
218
|
+
const chunks = indexedChunks(saved);
|
|
123
219
|
if (chunks === 0) {
|
|
124
|
-
return;
|
|
220
|
+
return null;
|
|
125
221
|
}
|
|
222
|
+
const { loadVectorIndex } = await this._embed.sdk();
|
|
126
223
|
try {
|
|
127
|
-
const
|
|
128
|
-
const index = await loadVectorIndex({ path: this._file(INDEX_FILE) });
|
|
224
|
+
const index = await loadVectorIndex({ path: this._file(snapshotFile(saved.generation)) });
|
|
129
225
|
if (index.dim === saved.dimensions && index.length === chunks) {
|
|
130
|
-
|
|
131
|
-
return;
|
|
226
|
+
return index;
|
|
132
227
|
}
|
|
133
228
|
await index.dispose();
|
|
134
229
|
}
|
|
135
230
|
catch {
|
|
136
231
|
}
|
|
137
|
-
|
|
232
|
+
return null;
|
|
138
233
|
}
|
|
139
|
-
async
|
|
140
|
-
const kept = Object.entries(this._manifest.artifacts).sort(([, a], [, b]) => a.seq - b.seq);
|
|
141
|
-
const stale = this._index;
|
|
142
|
-
this._manifest = { ...emptyManifest(this._model), seq: this._manifest.seq };
|
|
234
|
+
async _reload() {
|
|
143
235
|
this._index = null;
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
236
|
+
const saved = await readManifest(this._file(MANIFEST_FILE));
|
|
237
|
+
const index = await this._loadCurrent(saved);
|
|
238
|
+
const written = new Map(Object.entries(index && saved ? saved.artifacts : {}).filter(([, stored]) => !stored.pending));
|
|
239
|
+
const stale = [];
|
|
240
|
+
for (const [artifactId, stored] of Object.entries(this._manifest.artifacts)) {
|
|
241
|
+
const before = written.get(artifactId);
|
|
242
|
+
written.delete(artifactId);
|
|
243
|
+
if (before && !stored.pending && sameChunks(before, stored)) {
|
|
244
|
+
continue;
|
|
153
245
|
}
|
|
246
|
+
stale.push(...(before ? chunkIds(before) : []));
|
|
247
|
+
stored.pending = stored.chunks.length > 0 || undefined;
|
|
154
248
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
throw error;
|
|
249
|
+
for (const before of written.values()) {
|
|
250
|
+
stale.push(...chunkIds(before));
|
|
158
251
|
}
|
|
159
|
-
|
|
160
|
-
await
|
|
252
|
+
if (index && stale.length) {
|
|
253
|
+
await index.remove({ ids: stale });
|
|
254
|
+
}
|
|
255
|
+
this._index = index;
|
|
256
|
+
this._refill();
|
|
257
|
+
}
|
|
258
|
+
async _loadCurrent(saved) {
|
|
259
|
+
const index = saved?.model === this._model ? await this._load(saved) : null;
|
|
260
|
+
const { dimensions } = this._manifest;
|
|
261
|
+
if (index && dimensions !== 0 && index.dim !== dimensions) {
|
|
262
|
+
await index.dispose().catch(noop);
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
return index;
|
|
266
|
+
}
|
|
267
|
+
_markPending() {
|
|
268
|
+
for (const stored of Object.values(this._manifest.artifacts)) {
|
|
269
|
+
stored.pending = stored.chunks.length > 0 || undefined;
|
|
161
270
|
}
|
|
162
|
-
await this._persist();
|
|
163
271
|
}
|
|
164
|
-
async
|
|
272
|
+
async _reset(dimensions) {
|
|
165
273
|
await this._index?.dispose().catch(noop);
|
|
166
274
|
this._index = null;
|
|
167
|
-
this.
|
|
275
|
+
this._manifest.dimensions = dimensions;
|
|
276
|
+
this._markPending();
|
|
277
|
+
this._changed();
|
|
278
|
+
this._refill();
|
|
168
279
|
}
|
|
169
|
-
async
|
|
170
|
-
await this._drop(artifact.artifactId);
|
|
171
|
-
const result = await this._add(artifact);
|
|
172
|
-
await this._evict(artifact.artifactId);
|
|
173
|
-
await this._persist();
|
|
174
|
-
return result;
|
|
175
|
-
}
|
|
176
|
-
async _add(artifact, { heal = true } = {}) {
|
|
177
|
-
const { artifactId, version, scope, chunks, embedding } = artifact;
|
|
178
|
-
if (chunks.length === 0) {
|
|
179
|
-
return { added: 0, embedded: null };
|
|
180
|
-
}
|
|
280
|
+
async _prepare({ chunks, embedding }) {
|
|
181
281
|
const want = {
|
|
182
282
|
model: this._model,
|
|
183
283
|
dimensions: this._manifest.dimensions,
|
|
184
284
|
chunks: chunks.length
|
|
185
285
|
};
|
|
186
|
-
|
|
286
|
+
if (chunks.length === 0 || matches(embedding, want)) {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
return this._embedTexts(chunks.map((chunk) => chunk.text));
|
|
290
|
+
}
|
|
291
|
+
async _embedTexts(texts, { stopped } = {}) {
|
|
292
|
+
const vectors = [];
|
|
293
|
+
for (let at = 0; at < texts.length; at += EMBED_BATCH) {
|
|
294
|
+
if (stopped?.()) {
|
|
295
|
+
throw new Error('the knowledge store closed');
|
|
296
|
+
}
|
|
297
|
+
const batch = texts.slice(at, at + EMBED_BATCH);
|
|
298
|
+
vectors.push(...(await this._embed.embed({ model: this._model, texts: batch })));
|
|
299
|
+
}
|
|
300
|
+
if (vectors.length !== texts.length) {
|
|
301
|
+
throw new Error(`embed returned ${vectors.length} vectors for ${texts.length} chunks`);
|
|
302
|
+
}
|
|
303
|
+
return { model: this._model, dimensions: vectors[0]?.length ?? 0, vectors };
|
|
304
|
+
}
|
|
305
|
+
async _apply({ artifactId, version, scope, chunks, embedding }, embedded) {
|
|
187
306
|
const vectors = embedded?.vectors ?? embedding?.vectors ?? [];
|
|
188
307
|
const dim = vectors[0]?.length ?? 0;
|
|
189
|
-
if (heal && this._index && this._index.dim !== dim) {
|
|
190
|
-
await this._rebuild();
|
|
191
|
-
}
|
|
192
|
-
const index = await this._indexFor(dim);
|
|
193
308
|
const manifest = this._manifest;
|
|
309
|
+
if (embedded && manifest.dimensions !== 0 && dim !== manifest.dimensions) {
|
|
310
|
+
await this._reset(dim);
|
|
311
|
+
}
|
|
312
|
+
const fits = vectors.length > 0 && (manifest.dimensions === 0 || dim === manifest.dimensions);
|
|
194
313
|
const stored = chunks.map((chunk) => ({
|
|
195
314
|
id: String(manifest.nextId++),
|
|
196
315
|
chunkId: chunk.id,
|
|
197
316
|
text: chunk.text,
|
|
198
317
|
metadata: chunk.metadata
|
|
199
318
|
}));
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
version,
|
|
204
|
-
scope,
|
|
205
|
-
seq: manifest.seq,
|
|
206
|
-
chunks: stored
|
|
207
|
-
};
|
|
208
|
-
return { added: stored.length, embedded };
|
|
209
|
-
}
|
|
210
|
-
async _embedChunks({ chunks }) {
|
|
211
|
-
const vectors = await this._embed.embed({
|
|
212
|
-
model: this._model,
|
|
213
|
-
texts: chunks.map((chunk) => chunk.text)
|
|
214
|
-
});
|
|
215
|
-
if (vectors.length !== chunks.length) {
|
|
216
|
-
throw new Error(`embed returned ${vectors.length} vectors for ${chunks.length} chunks`);
|
|
319
|
+
if (fits) {
|
|
320
|
+
const index = await this._indexFor(dim);
|
|
321
|
+
await index.add({ ids: stored.map((chunk) => chunk.id), vectors: vectors.map(unit) });
|
|
217
322
|
}
|
|
218
|
-
|
|
323
|
+
await this._drop(artifactId);
|
|
324
|
+
const pending = stored.length > 0 && !fits;
|
|
325
|
+
manifest.artifacts[artifactId] = { version, scope, seq: ++manifest.seq, chunks: stored };
|
|
326
|
+
if (pending) {
|
|
327
|
+
manifest.artifacts[artifactId].pending = true;
|
|
328
|
+
}
|
|
329
|
+
await this._evict(artifactId);
|
|
330
|
+
await this._release();
|
|
331
|
+
this._changed();
|
|
332
|
+
this._refill();
|
|
333
|
+
return { added: stored.length, embedded };
|
|
219
334
|
}
|
|
220
335
|
async _indexFor(dim) {
|
|
221
336
|
if (this._index) {
|
|
@@ -234,10 +349,11 @@ export class KnowledgeStore {
|
|
|
234
349
|
if (!stored) {
|
|
235
350
|
return 0;
|
|
236
351
|
}
|
|
237
|
-
if (this._index && stored.chunks.length) {
|
|
238
|
-
await this._index.remove({ ids: stored
|
|
352
|
+
if (this._index && !stored.pending && stored.chunks.length) {
|
|
353
|
+
await this._index.remove({ ids: chunkIds(stored) });
|
|
239
354
|
}
|
|
240
355
|
delete this._manifest.artifacts[artifactId];
|
|
356
|
+
this._changed();
|
|
241
357
|
return stored.chunks.length;
|
|
242
358
|
}
|
|
243
359
|
async _evict(keep) {
|
|
@@ -251,29 +367,83 @@ export class KnowledgeStore {
|
|
|
251
367
|
total -= await this._drop(artifactId);
|
|
252
368
|
}
|
|
253
369
|
}
|
|
254
|
-
async
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
370
|
+
async _release() {
|
|
371
|
+
if (this._chunkCount() > 0) {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
await this._index?.dispose().catch(noop);
|
|
375
|
+
this._index = null;
|
|
376
|
+
this._manifest.dimensions = 0;
|
|
377
|
+
}
|
|
378
|
+
_refill() {
|
|
379
|
+
if (this._refilling || this._closed || !this._nextPending()) {
|
|
380
|
+
return;
|
|
261
381
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
382
|
+
this._refilling = this._refillAll().then(() => {
|
|
383
|
+
this._refilling = null;
|
|
384
|
+
this._refill();
|
|
385
|
+
}, () => {
|
|
386
|
+
this._refilling = null;
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
async _refillAll() {
|
|
390
|
+
for (let next = this._nextPending(); next && !this._closed; next = this._nextPending()) {
|
|
391
|
+
const [artifactId, stored] = next;
|
|
392
|
+
await this._ordered(() => this._refillOne(artifactId, stored));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async _refillOne(artifactId, stored) {
|
|
396
|
+
if (this._manifest.artifacts[artifactId] !== stored || !stored.pending) {
|
|
397
|
+
return;
|
|
265
398
|
}
|
|
399
|
+
const embedded = await this._embedTexts(stored.chunks.map((chunk) => chunk.text), { stopped: () => this._closed });
|
|
400
|
+
await this._locked(() => this._fill(artifactId, stored, embedded));
|
|
401
|
+
}
|
|
402
|
+
_nextPending() {
|
|
403
|
+
const pending = Object.entries(this._manifest.artifacts).filter(([, stored]) => stored.pending);
|
|
404
|
+
return pending.sort(([, a], [, b]) => a.seq - b.seq)[0] ?? null;
|
|
405
|
+
}
|
|
406
|
+
async _fill(artifactId, stored, embedded) {
|
|
407
|
+
if (this._manifest.artifacts[artifactId] !== stored || !stored.pending) {
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const { dimensions, vectors } = embedded;
|
|
411
|
+
if (this._manifest.dimensions !== 0 && dimensions !== this._manifest.dimensions) {
|
|
412
|
+
await this._reset(dimensions);
|
|
413
|
+
}
|
|
414
|
+
const index = await this._indexFor(dimensions);
|
|
415
|
+
await index.add({ ids: chunkIds(stored), vectors: vectors.map(unit) });
|
|
416
|
+
delete stored.pending;
|
|
417
|
+
this._changed();
|
|
418
|
+
}
|
|
419
|
+
_searchable(granted) {
|
|
420
|
+
return Object.values(this._manifest.artifacts).some((stored) => !stored.pending && stored.chunks.length > 0 && granted.has(stored.scope));
|
|
421
|
+
}
|
|
422
|
+
async _search({ scopes, focus, k = DEFAULT_K }, query) {
|
|
423
|
+
const byId = this._chunksById(new Set(scopes));
|
|
266
424
|
const index = this._index;
|
|
267
|
-
|
|
268
|
-
|
|
425
|
+
if (!index || byId.size === 0) {
|
|
426
|
+
return [];
|
|
427
|
+
}
|
|
428
|
+
if (query.length !== index.dim) {
|
|
429
|
+
await this._reset(query.length);
|
|
430
|
+
return [];
|
|
431
|
+
}
|
|
432
|
+
const named = new Set(focus);
|
|
433
|
+
const focused = new Map([...byId].filter(([, entry]) => named.has(entry.artifactId)));
|
|
434
|
+
const hits = focused.size ? await this._ranked(index, { query, byId: focused, k }) : [];
|
|
435
|
+
return hits.length ? hits : this._ranked(index, { query, byId, k, floor: this._minScore });
|
|
436
|
+
}
|
|
437
|
+
async _ranked(index, { query, byId, k, floor = -Infinity }) {
|
|
438
|
+
const want = Math.min(k, byId.size);
|
|
269
439
|
let fetch = Math.min(index.length, want * 4);
|
|
270
440
|
for (;;) {
|
|
271
441
|
const hits = await index.search({ query: unit(query), k: fetch });
|
|
272
442
|
const found = hits.flatMap((hit) => {
|
|
273
443
|
const entry = byId.get(hit.id);
|
|
274
|
-
return entry && hit.score >=
|
|
444
|
+
return entry && hit.score >= floor ? [{ ...entry, score: hit.score }] : [];
|
|
275
445
|
});
|
|
276
|
-
const floored = (hits.at(-1)?.score ?? -Infinity) <
|
|
446
|
+
const floored = (hits.at(-1)?.score ?? -Infinity) < floor;
|
|
277
447
|
if (found.length >= want || floored || fetch >= index.length) {
|
|
278
448
|
return found.slice(0, k);
|
|
279
449
|
}
|
|
@@ -283,7 +453,7 @@ export class KnowledgeStore {
|
|
|
283
453
|
_chunksById(granted) {
|
|
284
454
|
const byId = new Map();
|
|
285
455
|
for (const [artifactId, stored] of Object.entries(this._manifest.artifacts)) {
|
|
286
|
-
if (!granted.has(stored.scope))
|
|
456
|
+
if (stored.pending || !granted.has(stored.scope))
|
|
287
457
|
continue;
|
|
288
458
|
for (const chunk of stored.chunks) {
|
|
289
459
|
byId.set(chunk.id, {
|
|
@@ -297,36 +467,58 @@ export class KnowledgeStore {
|
|
|
297
467
|
}
|
|
298
468
|
return byId;
|
|
299
469
|
}
|
|
470
|
+
async _warm() {
|
|
471
|
+
const index = this._index;
|
|
472
|
+
if (!index || index.length === 0) {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const probe = Array.from({ length: index.dim }, (_, at) => (at === 0 ? 1 : 0));
|
|
476
|
+
await index.search({ query: probe, k: 1 });
|
|
477
|
+
}
|
|
300
478
|
_chunkCount() {
|
|
301
479
|
return Object.values(this._manifest.artifacts).reduce((sum, stored) => sum + stored.chunks.length, 0);
|
|
302
480
|
}
|
|
303
481
|
_file(name) {
|
|
304
482
|
return path.join(this._dir, name);
|
|
305
483
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
await this._index.write({ path: snapshot });
|
|
484
|
+
_changed() {
|
|
485
|
+
this._dirty = true;
|
|
486
|
+
if (this._persisting || this._closed) {
|
|
487
|
+
return;
|
|
311
488
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
this.
|
|
315
|
-
|
|
316
|
-
|
|
489
|
+
this._persisting = setTimeout(() => {
|
|
490
|
+
this._persisting = null;
|
|
491
|
+
this._exclusive(() => this._recovering(() => this._writeOut())).catch(noop);
|
|
492
|
+
}, PERSIST_DELAY_MS);
|
|
493
|
+
}
|
|
494
|
+
async _writeOut() {
|
|
495
|
+
if (!this._dirty) {
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
this._dirty = false;
|
|
499
|
+
try {
|
|
500
|
+
await this._persist();
|
|
501
|
+
}
|
|
502
|
+
catch (error) {
|
|
503
|
+
this._dirty = true;
|
|
504
|
+
throw error;
|
|
317
505
|
}
|
|
318
|
-
const manifest = this._file(MANIFEST_FILE);
|
|
319
|
-
await fs.promises.writeFile(`${manifest}.tmp`, JSON.stringify(this._manifest));
|
|
320
|
-
await fs.promises.rename(`${manifest}.tmp`, manifest);
|
|
321
506
|
}
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
const
|
|
326
|
-
|
|
507
|
+
async _persist() {
|
|
508
|
+
await fs.promises.mkdir(this._dir, { recursive: true });
|
|
509
|
+
const replaced = this._manifest.generation;
|
|
510
|
+
const generation = (replaced ?? 0) + 1;
|
|
511
|
+
if (this._index && indexedChunks(this._manifest) > 0) {
|
|
512
|
+
await this._index.write({ path: this._file(snapshotFile(generation)) });
|
|
513
|
+
}
|
|
514
|
+
await writeManifest(this._file(MANIFEST_FILE), { ...this._manifest, generation });
|
|
515
|
+
this._manifest.generation = generation;
|
|
516
|
+
await fs.promises.rm(this._file(snapshotFile(replaced)), { force: true });
|
|
327
517
|
}
|
|
328
|
-
|
|
329
|
-
|
|
518
|
+
async _sweep(kept) {
|
|
519
|
+
const files = await fs.promises.readdir(this._dir).catch(() => []);
|
|
520
|
+
const stray = files.filter((file) => isSnapshotFile(file) && file !== kept);
|
|
521
|
+
await Promise.all(stray.map((file) => fs.promises.rm(this._file(file), { force: true })));
|
|
330
522
|
}
|
|
331
523
|
}
|
|
332
524
|
function noop() { }
|
|
@@ -6,6 +6,7 @@ import { isRedirectStatus, parseObjectArg } from '../../lib/tools/http-request/r
|
|
|
6
6
|
import { parseAuth, resolveBearerHeader } from '../../lib/tools/skills/index.js';
|
|
7
7
|
import { recordCredentialHealth } from '../../lib/tools/skills/credential-health.js';
|
|
8
8
|
import { cacheSession, deleteSession, establishSession, flattenMcpResponse, getSession, isNotification, needsSession, normalizeMethod, post, readBody, sessionKey, TIMEOUT_MS } from './protocol.js';
|
|
9
|
+
import { toolListing } from './tool-listing.js';
|
|
9
10
|
const MCP_CALL_TOOL_NAME = 'mcp_call';
|
|
10
11
|
function nestedUrl(params) {
|
|
11
12
|
return typeof params?.url === 'string' && params.url.length > 0 ? params.url : undefined;
|
|
@@ -36,7 +37,10 @@ export async function sendMcp(request, ctx) {
|
|
|
36
37
|
return { error: 'request failed: no fetch for this call', code: 'transport' };
|
|
37
38
|
}
|
|
38
39
|
const { url, auth, credentialStore, credentialAllowList } = request;
|
|
39
|
-
const
|
|
40
|
+
const normalized = normalizeMethod(request.method, request.params);
|
|
41
|
+
const { method } = normalized;
|
|
42
|
+
const listing = method === 'tools/list' ? toolListing(normalized.params) : undefined;
|
|
43
|
+
const params = listing ? listing.params : normalized.params;
|
|
40
44
|
const controller = new AbortController();
|
|
41
45
|
const timeout = setTimeout(() => controller.abort(undefined), TIMEOUT_MS);
|
|
42
46
|
try {
|
|
@@ -89,7 +93,10 @@ export async function sendMcp(request, ctx) {
|
|
|
89
93
|
if (isNotification(method)) {
|
|
90
94
|
return { status: response.status, body: '' };
|
|
91
95
|
}
|
|
92
|
-
return {
|
|
96
|
+
return {
|
|
97
|
+
status: response.status,
|
|
98
|
+
...flattenMcpResponse(await readBody(response), ctx, listing)
|
|
99
|
+
};
|
|
93
100
|
}
|
|
94
101
|
catch (err) {
|
|
95
102
|
const error = err instanceof Error ? err : new Error(String(err));
|
|
@@ -107,7 +114,7 @@ export function createMcpCallTool({ credentialStore, credentialAllowList, readMe
|
|
|
107
114
|
return {
|
|
108
115
|
name: MCP_CALL_TOOL_NAME,
|
|
109
116
|
toolset: 'mcp-call',
|
|
110
|
-
description: 'Make a JSON-RPC 2.0 call to a Model Context Protocol (MCP) server. Load the matching skill first — it documents the server tool names and their args. Pass a server tool name as `method` and its args as `params`; the JSON-RPC envelope, session handshake, and bearer auth are handled for you (the stored credential for the host is attached automatically, so no `auth` is needed).',
|
|
117
|
+
description: 'Make a JSON-RPC 2.0 call to a Model Context Protocol (MCP) server. Load the matching skill first — it documents the server tool names and their args. Pass a server tool name as `method` and its args as `params`; the JSON-RPC envelope, session handshake, and bearer auth are handled for you (the stored credential for the host is attached automatically, so no `auth` is needed). A response too large for the context window is cut, and `truncated` then says what share of it was read.',
|
|
111
118
|
parameters: {
|
|
112
119
|
type: 'object',
|
|
113
120
|
properties: {
|