@qvac/harness 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +137 -1
  2. package/README.md +28 -0
  3. package/dist-lib/index.d.ts +32 -304
  4. package/dist-lib/index.js +16 -1147
  5. package/dist-lib/lib/agent/child-run.d.ts +29 -0
  6. package/dist-lib/lib/agent/child-run.js +32 -0
  7. package/dist-lib/lib/agent/delegate.d.ts +3 -19
  8. package/dist-lib/lib/agent/delegate.js +8 -31
  9. package/dist-lib/lib/agent/index.d.ts +4 -0
  10. package/dist-lib/lib/agent/index.js +3 -0
  11. package/dist-lib/lib/agent/read-parts.d.ts +45 -0
  12. package/dist-lib/lib/agent/read-parts.js +60 -0
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +6 -2
  14. package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -0
  15. package/dist-lib/lib/capabilities/completion-engine/engine.js +27 -18
  16. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -4
  17. package/dist-lib/lib/client/index.js +1 -3
  18. package/dist-lib/lib/connect/decode.d.ts +3 -2
  19. package/dist-lib/lib/connect/decode.js +14 -0
  20. package/dist-lib/lib/connect.d.ts +1 -0
  21. package/dist-lib/lib/connect.js +11 -5
  22. package/dist-lib/lib/context-window.d.ts +2 -0
  23. package/dist-lib/lib/context-window.js +17 -14
  24. package/dist-lib/lib/contract/models.d.ts +8 -1
  25. package/dist-lib/lib/contract-types.d.ts +9 -0
  26. package/dist-lib/lib/harness.d.ts +267 -0
  27. package/dist-lib/lib/harness.js +1154 -0
  28. package/dist-lib/lib/models/custom-model-cache.d.ts +2 -0
  29. package/dist-lib/lib/models/custom-model-cache.js +21 -0
  30. package/dist-lib/lib/models/memory-cap.d.ts +6 -0
  31. package/dist-lib/lib/models/memory-cap.js +20 -0
  32. package/dist-lib/lib/models/model-catalog.d.ts +2 -0
  33. package/dist-lib/lib/models/model-catalog.js +8 -2
  34. package/dist-lib/lib/models/model-fit.d.ts +39 -7
  35. package/dist-lib/lib/models/model-fit.js +133 -18
  36. package/dist-lib/lib/models/model-handle.d.ts +2 -1
  37. package/dist-lib/lib/models/model-pool.d.ts +3 -2
  38. package/dist-lib/lib/models/model-pool.js +30 -13
  39. package/dist-lib/lib/models/tts-model-default.d.ts +1 -1
  40. package/dist-lib/lib/models/tts-model-default.js +7 -6
  41. package/dist-lib/lib/residency/index.d.ts +21 -7
  42. package/dist-lib/lib/residency/index.js +187 -80
  43. package/dist-lib/lib/run-log/boundary.d.ts +4 -1
  44. package/dist-lib/lib/run-log/boundary.js +2 -1
  45. package/dist-lib/lib/run-log/index.d.ts +2 -1
  46. package/dist-lib/lib/run-log/index.js +2 -1
  47. package/dist-lib/lib/run-log/persisted-actor.d.ts +10 -0
  48. package/dist-lib/lib/run-log/persisted-actor.js +15 -0
  49. package/dist-lib/lib/run-log/run-journal.d.ts +3 -0
  50. package/dist-lib/lib/run-log/run-journal.js +19 -8
  51. package/dist-lib/lib/serve/requests.d.ts +3 -0
  52. package/dist-lib/lib/serve.js +3 -0
  53. package/dist-lib/lib/spawn.d.ts +4 -1
  54. package/dist-lib/lib/tools/exec/shell-guidance.d.ts +2 -0
  55. package/dist-lib/lib/tools/exec/shell-guidance.js +29 -0
  56. package/dist-lib/lib/tools/exec.js +2 -1
  57. package/dist-lib/lib/tools/files/list-dir.js +79 -32
  58. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  59. package/dist-lib/lib/tools/fs/walk.js +64 -30
  60. package/dist-lib/lib/tools/http-request.js +5 -0
  61. package/dist-lib/lib/tools/office.js +8 -5
  62. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  63. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  64. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  65. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  66. package/dist-lib/lib/tools/tls-failure.d.ts +1 -0
  67. package/dist-lib/lib/tools/tls-failure.js +8 -0
  68. package/dist-lib/lib/tools/web-fetch.js +5 -0
  69. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  70. package/dist-lib/plugins/image/generate-image.js +9 -1
  71. package/dist-lib/plugins/image/index.js +6 -2
  72. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  73. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  74. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  75. package/dist-lib/plugins/knowledge/index.js +1 -0
  76. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  77. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  78. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  79. package/dist-lib/plugins/knowledge/store.js +44 -16
  80. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  81. package/dist-lib/plugins/lsp/rpc.js +81 -17
  82. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  83. package/dist-lib/plugins/music/generate-music.js +14 -1
  84. package/dist-lib/plugins/music/index.js +4 -1
  85. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  86. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  87. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  88. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  89. package/dist-lib/schema/harness.js +28 -2
  90. package/dist-lib/spec/bind.js +3 -0
  91. package/dist-lib/spec/calls.js +1 -0
  92. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  93. package/dist-lib/spec/hrpc/index.js +15 -3
  94. package/dist-lib/spec/hrpc/messages.js +87 -6
  95. package/dist-lib/spec/hyperschema/index.js +87 -6
  96. package/dist-lib/spec/hyperschema/schema.json +70 -2
  97. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  98. package/package.json +29 -28
  99. package/scripts/addon-externals.cjs +1 -0
  100. package/worker/harness-sidecar.mjs +12 -1
@@ -8,20 +8,16 @@ const KEPT_DOCUMENTS = 8;
8
8
  const keptByService = new WeakMap();
9
9
  export async function recognizePages({ doc, bytes }, { ocr, signal, budget }) {
10
10
  const pages = new Map();
11
- let kept = null;
12
- let failed = false;
11
+ const recognize = pageRecognizer({ doc, bytes }, { ocr, signal });
13
12
  for await (const { page, text } of doc.textPagesAsync()) {
14
13
  signal?.throwIfAborted();
15
14
  if (budget && budget.chars <= 0) {
16
15
  return { pages, unreadFrom: page };
17
16
  }
18
17
  let read = cleanText(text);
19
- if (!read && !failed && doc.pageFlags(page).hasImage) {
20
- kept ??= keptPages(ocr, bytes);
21
- const found = kept.get(page) ?? (await readPage(doc, page, { ocr, signal }));
22
- failed = found === null;
18
+ if (!read && doc.pageFlags(page).hasImage) {
19
+ const found = await recognize(page);
23
20
  if (found !== null) {
24
- kept.set(page, found);
25
21
  pages.set(page, found);
26
22
  read = found;
27
23
  }
@@ -32,6 +28,48 @@ export async function recognizePages({ doc, bytes }, { ocr, signal, budget }) {
32
28
  }
33
29
  return { pages, unreadFrom: null };
34
30
  }
31
+ export function pageRecognizer({ doc, bytes }, { ocr, signal }) {
32
+ let kept = null;
33
+ let failed = false;
34
+ return async (page) => {
35
+ if (failed) {
36
+ return null;
37
+ }
38
+ kept ??= keptPages(ocr, bytes);
39
+ const cached = kept.get(page);
40
+ const found = cached === undefined ? await readPage(doc, page, { ocr, signal }) : cached;
41
+ failed = found === null;
42
+ if (found !== null) {
43
+ kept.set(page, found);
44
+ }
45
+ return found;
46
+ };
47
+ }
48
+ export async function readPdfPages(doc, bytes, { ocr, signal } = {}) {
49
+ const recognize = ocr ? pageRecognizer({ doc, bytes }, { ocr, signal }) : undefined;
50
+ const pages = [];
51
+ for await (const { page, text } of doc.textPagesAsync()) {
52
+ signal?.throwIfAborted();
53
+ const read = await pageText({ doc, page, text, recognize });
54
+ const unread = !read.text && !read.recognized && read.hasImage;
55
+ pages.push({ page: page + 1, text: read.text, unread });
56
+ }
57
+ return pages;
58
+ }
59
+ async function pageText({ doc, page, text, recognize }) {
60
+ const native = cleanText(text);
61
+ if (native) {
62
+ return { text: native, recognized: false, hasImage: false };
63
+ }
64
+ const hasImage = doc.pageFlags(page).hasImage;
65
+ if (!hasImage || !recognize) {
66
+ return { text: '', recognized: false, hasImage };
67
+ }
68
+ const found = await recognize(page);
69
+ return found === null
70
+ ? { text: '', recognized: false, hasImage }
71
+ : { text: found, recognized: true, hasImage };
72
+ }
35
73
  async function readPage(doc, page, { ocr, signal }) {
36
74
  try {
37
75
  const { text } = await ocr.read(await doc.renderAsync(page, { scale: OCR_SCALE }), signal);
@@ -0,0 +1 @@
1
+ export declare function tlsFailure(err: unknown, host: string): string | null;
@@ -0,0 +1,8 @@
1
+ import { errorCode } from '../guards.js';
2
+ const TLS_CODE = /^(UNABLE_TO_VERIFY_LEAF_SIGNATURE|CERT_HAS_EXPIRED|CERT_NOT_YET_VALID|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN|ERR_TLS_CERT_ALTNAME_INVALID|UNABLE_TO_GET_ISSUER_CERT(_LOCALLY)?|CERT_UNTRUSTED|HOSTNAME_MISMATCH|CERTIFICATE_VERIFY_FAILED)$/;
3
+ export function tlsFailure(err, host) {
4
+ const code = errorCode(err);
5
+ return code && TLS_CODE.test(code)
6
+ ? `The TLS certificate of ${host} could not be verified (${code}). Do not retry and do not bypass certificate checks; tell the user the site's certificate is invalid.`
7
+ : null;
8
+ }
@@ -8,6 +8,7 @@ import { extractEmbeddedState } from '../web-fetch/embedded-state.js';
8
8
  import { extractPageText, looksLikeHtml } from '../web-fetch/extract.js';
9
9
  import { imageFileName, pageImageUrls } from '../web-fetch/images.js';
10
10
  import { pageVideoRef } from '../web-fetch/video.js';
11
+ import { tlsFailure } from './tls-failure.js';
11
12
  import { isRedirectStatus } from './http-request/request.js';
12
13
  import { Policy } from '../policy/index.js';
13
14
  import { attachFetchedFile, attachTextFile, bareMime, fetchedFileName, isFileMime, MAX_FILE_BYTES } from './attachments/fetched-file.js';
@@ -193,6 +194,10 @@ export function createWebFetchTool({ fetch: fetchImpl, resolveHost = lookupHost
193
194
  if (err instanceof Error && err.name === 'TimeoutError') {
194
195
  return { error: `${url.hostname} sent nothing for ${IDLE_TIMEOUT_MS}ms`, code: 'timeout' };
195
196
  }
197
+ const tls = tlsFailure(err, url.hostname);
198
+ if (tls) {
199
+ return { error: tls, code: 'tls' };
200
+ }
196
201
  return { error: errorMessage(err), code: 'transport' };
197
202
  }
198
203
  finally {
@@ -2,7 +2,7 @@ import { type AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  import type { MediaRoundServer, MediaSourceRef, ToolDefinition, ToolExecuteContext } from '../../lib/contract/index.ts';
3
3
  import type { ModelSrc } from '../../lib/models/context.ts';
4
4
  import { type ImageClamps, type ImageModelSet } from '../../lib/models/model-catalog.ts';
5
- import type { LoadRequests, ModelHost, TrackedLoad } from '../../lib/contract/models.ts';
5
+ import type { LoadRequests, ModelHost, ReleaseRoom, TrackedLoad } from '../../lib/contract/models.ts';
6
6
  import type { HoldFn } from '../../lib/contract/models.ts';
7
7
  import { type ModelRegistrySdk } from '../../lib/models/model-source.ts';
8
8
  import { type FitDeps } from './fit.ts';
@@ -64,7 +64,7 @@ export interface DiffusionRuntimeOptions extends ImageModelSet {
64
64
  loadSdk: () => Promise<DiffusionSdk>;
65
65
  onProgress?: (model: string, progress: Record<string, unknown>) => void;
66
66
  onLoaded?: (model: string) => void;
67
- onBeforeLoad?: (signal: BareAbortSignal | undefined, srcs: ReadonlyArray<string>) => Promise<void>;
67
+ onBeforeLoad?: (signal: BareAbortSignal | undefined, srcs: ReadonlyArray<string>) => Promise<ReleaseRoom>;
68
68
  hold?: HoldFn;
69
69
  requests?: LoadRequests;
70
70
  loads?: Pick<ModelHost, 'track'>;
@@ -51,6 +51,11 @@ export function createDiffusionRuntime({ loadSdk, onProgress, onLoaded, onBefore
51
51
  let loading = null;
52
52
  let residentFingerprint = null;
53
53
  let busy = false;
54
+ let releaseRoom = noop;
55
+ const freeRoom = () => {
56
+ releaseRoom();
57
+ releaseRoom = noop;
58
+ };
54
59
  const lock = new ScopeLock();
55
60
  const doUnload = async () => {
56
61
  const pending = loading;
@@ -62,12 +67,14 @@ export function createDiffusionRuntime({ loadSdk, onProgress, onLoaded, onBefore
62
67
  if (!loaded) {
63
68
  loading = null;
64
69
  residentFingerprint = null;
70
+ freeRoom();
65
71
  return;
66
72
  }
67
73
  const sdk = await loadSdk();
68
74
  await sdk.unloadModel({ modelId: loaded.modelId });
69
75
  loading = null;
70
76
  residentFingerprint = null;
77
+ freeRoom();
71
78
  };
72
79
  const unload = async () => {
73
80
  await lock.lock();
@@ -123,6 +130,7 @@ export function createDiffusionRuntime({ loadSdk, onProgress, onLoaded, onBefore
123
130
  })().catch((err) => {
124
131
  loading = null;
125
132
  residentFingerprint = null;
133
+ freeRoom();
126
134
  requests.failed(name, err);
127
135
  throw err;
128
136
  });
@@ -135,7 +143,7 @@ export function createDiffusionRuntime({ loadSdk, onProgress, onLoaded, onBefore
135
143
  await doUnload();
136
144
  }
137
145
  if (!loading && onBeforeLoad) {
138
- await onBeforeLoad(signal, [set.model, set.llmModel, set.vaeModel].filter((src) => src !== undefined));
146
+ releaseRoom = await onBeforeLoad(signal, [set.model, set.llmModel, set.vaeModel].filter((src) => src !== undefined));
139
147
  }
140
148
  residentFingerprint = fingerprint;
141
149
  loading ??= loadSet(sdk, set);
@@ -21,7 +21,7 @@ function diffusionRuntime(models, model) {
21
21
  return sdk;
22
22
  });
23
23
  const transfers = new Map();
24
- return createDiffusionRuntime({
24
+ const runtime = createDiffusionRuntime({
25
25
  ...(typeof model === 'string' ? { model } : model),
26
26
  loads: models,
27
27
  loadSdk,
@@ -47,8 +47,12 @@ function diffusionRuntime(models, model) {
47
47
  models.statusChanged();
48
48
  models.emit({ ...transfer, status: 'downloaded' });
49
49
  },
50
- onBeforeLoad: (signal, srcs) => models.makeRoom(signal, new HarnessError('CHAT_MODEL_BUSY', ['image']), srcs)
50
+ onBeforeLoad: (signal, srcs) => models.makeRoom(signal, new HarnessError('CHAT_MODEL_BUSY', ['image']), {
51
+ srcs,
52
+ unloadIdle: () => runtime.unloadIdle()
53
+ })
51
54
  });
55
+ return runtime;
52
56
  }
53
57
  export class Image {
54
58
  name = 'image';
@@ -0,0 +1,4 @@
1
+ import { type StoredChunk } from './manifest.ts';
2
+ export declare function chunkIndexFile(ids: readonly string[]): string | null;
3
+ export declare function readChunksAt(dir: string, ids: readonly string[], positions: Iterable<number>): Promise<Map<number, StoredChunk>>;
4
+ export declare function writeChunks(dir: string, ids: readonly string[], chunks: StoredChunk[]): Promise<void>;
@@ -0,0 +1,191 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import b4a from 'b4a';
4
+ import { chunksFile, isStoredChunk } from './manifest.js';
5
+ export function chunkIndexFile(ids) {
6
+ const file = chunksFile(ids);
7
+ return file ? `${file}.idx` : null;
8
+ }
9
+ const INDEX_MAGIC = b4a.from([81, 86, 73, 49]);
10
+ const INDEX_HEADER_BYTES = 32;
11
+ const INDEX_ENTRY_BYTES = 16;
12
+ export async function readChunksAt(dir, ids, positions) {
13
+ const file = chunksFile(ids);
14
+ if (!file) {
15
+ return new Map();
16
+ }
17
+ const selected = [...new Set(positions)];
18
+ try {
19
+ return await readIndexedChunks({ dir, file, count: ids.length, positions: selected });
20
+ }
21
+ catch {
22
+ return readLegacyChunks({ dir, file, count: ids.length, positions: selected });
23
+ }
24
+ }
25
+ async function readLegacyChunks({ dir, file, count, positions }) {
26
+ const dataFile = path.join(dir, file);
27
+ const bytes = await fs.promises.readFile(dataFile);
28
+ const chunks = JSON.parse(b4a.toString(bytes, 'utf8'));
29
+ if (!Array.isArray(chunks) || chunks.length !== count || !chunks.every(isStoredChunk)) {
30
+ throw new Error(`${file} does not hold the artifact's ${count} chunks`);
31
+ }
32
+ const stat = await fs.promises.stat(dataFile);
33
+ if (bytes.byteLength !== stat.size) {
34
+ throw new Error(`${file} changed while it was read`);
35
+ }
36
+ const encoded = encodeChunks(chunks);
37
+ if (b4a.equals(encoded.bytes, bytes)) {
38
+ await writeChunkIndex(path.join(dir, `${file}.idx`), makeChunkIndex(encoded, stat)).catch(noop);
39
+ }
40
+ const found = new Map();
41
+ for (const at of positions) {
42
+ const chunk = chunks[at];
43
+ if (!chunk) {
44
+ throw new Error(`${file} has no chunk at ${at}`);
45
+ }
46
+ found.set(at, chunk);
47
+ }
48
+ return found;
49
+ }
50
+ async function readIndexedChunks({ dir, file, count, positions }) {
51
+ const dataFile = path.join(dir, file);
52
+ const indexFile = path.join(dir, `${file}.idx`);
53
+ const dataStat = await fs.promises.stat(dataFile);
54
+ const index = await fs.promises.open(indexFile, 'r');
55
+ let data = null;
56
+ try {
57
+ data = await fs.promises.open(dataFile, 'r');
58
+ await validateChunkIndex({ index, indexFile, dataStat, file, count });
59
+ return await readSelectedChunks({
60
+ index,
61
+ data,
62
+ file,
63
+ count,
64
+ positions,
65
+ fileSize: dataStat.size
66
+ });
67
+ }
68
+ finally {
69
+ await index.close();
70
+ await data?.close();
71
+ }
72
+ }
73
+ async function validateChunkIndex({ index, indexFile, dataStat, file, count }) {
74
+ const header = b4a.alloc(INDEX_HEADER_BYTES);
75
+ await readExact(index, header, 0);
76
+ if (!b4a.equals(header.subarray(0, INDEX_MAGIC.length), INDEX_MAGIC)) {
77
+ throw new Error(`${file} has an invalid chunk index`);
78
+ }
79
+ const indexedCount = readU32(header, 4);
80
+ const fileSize = readU64(header, 8);
81
+ const modified = readU64(header, 16);
82
+ const changed = readU64(header, 24);
83
+ const indexStat = await fs.promises.stat(indexFile);
84
+ if (indexedCount !== count ||
85
+ indexStat.size !== INDEX_HEADER_BYTES + count * INDEX_ENTRY_BYTES ||
86
+ fileSize !== dataStat.size ||
87
+ modified !== timestamp(dataStat.mtimeMs) ||
88
+ changed !== timestamp(dataStat.ctimeMs)) {
89
+ throw new Error(`${file} changed after its chunk index was written`);
90
+ }
91
+ }
92
+ async function readSelectedChunks({ index, data, file, count, positions, fileSize }) {
93
+ const chunks = new Map();
94
+ for (const at of positions) {
95
+ const chunk = await readIndexedChunk({ index, data, file, at, count, fileSize });
96
+ chunks.set(at, chunk);
97
+ }
98
+ return chunks;
99
+ }
100
+ async function readIndexedChunk({ index, data, file, at, count, fileSize }) {
101
+ if (!Number.isSafeInteger(at) || at < 0 || at >= count) {
102
+ throw new Error(`${file} has no chunk at ${at}`);
103
+ }
104
+ const entry = b4a.alloc(INDEX_ENTRY_BYTES);
105
+ await readExact(index, entry, INDEX_HEADER_BYTES + at * INDEX_ENTRY_BYTES);
106
+ const start = readU64(entry, 0);
107
+ const length = readU64(entry, 8);
108
+ if (!Number.isSafeInteger(start) ||
109
+ !Number.isSafeInteger(length) ||
110
+ length <= 0 ||
111
+ start + length > fileSize) {
112
+ throw new Error(`${file} has an invalid chunk range at ${at}`);
113
+ }
114
+ const bytes = b4a.alloc(length);
115
+ await readExact(data, bytes, start);
116
+ const chunk = JSON.parse(b4a.toString(bytes, 'utf8'));
117
+ if (!isStoredChunk(chunk)) {
118
+ throw new Error(`${file} has a corrupt chunk at ${at}`);
119
+ }
120
+ return chunk;
121
+ }
122
+ async function readExact(handle, bytes, position) {
123
+ let received = 0;
124
+ while (received < bytes.byteLength) {
125
+ const { bytesRead } = await handle.read(bytes, received, bytes.byteLength - received, position + received);
126
+ if (bytesRead <= 0) {
127
+ throw new Error('unexpected end of file');
128
+ }
129
+ received += bytesRead;
130
+ }
131
+ }
132
+ export async function writeChunks(dir, ids, chunks) {
133
+ const file = chunksFile(ids);
134
+ if (!file) {
135
+ return;
136
+ }
137
+ await fs.promises.mkdir(dir, { recursive: true });
138
+ const encoded = encodeChunks(chunks);
139
+ const dataFile = path.join(dir, file);
140
+ await fs.promises.writeFile(dataFile, encoded.bytes);
141
+ const index = makeChunkIndex(encoded, await fs.promises.stat(dataFile));
142
+ await writeChunkIndex(path.join(dir, `${file}.idx`), index).catch(noop);
143
+ }
144
+ function encodeChunks(chunks) {
145
+ const rows = chunks.map((chunk) => JSON.stringify(chunk));
146
+ const ranges = [];
147
+ let at = 1;
148
+ for (const row of rows) {
149
+ const length = b4a.byteLength(row);
150
+ ranges.push([at, length]);
151
+ at += length + 1;
152
+ }
153
+ return { bytes: b4a.from(`[${rows.join(',')}]`), ranges };
154
+ }
155
+ function makeChunkIndex({ bytes, ranges }, stat) {
156
+ const index = b4a.alloc(INDEX_HEADER_BYTES + ranges.length * INDEX_ENTRY_BYTES);
157
+ index.set(INDEX_MAGIC);
158
+ writeU32(index, 4, ranges.length);
159
+ writeU64(index, 8, bytes.byteLength);
160
+ writeU64(index, 16, timestamp(stat.mtimeMs));
161
+ writeU64(index, 24, timestamp(stat.ctimeMs));
162
+ ranges.forEach(([start, length], at) => {
163
+ const offset = INDEX_HEADER_BYTES + at * INDEX_ENTRY_BYTES;
164
+ writeU64(index, offset, start);
165
+ writeU64(index, offset + 8, length);
166
+ });
167
+ return index;
168
+ }
169
+ async function writeChunkIndex(file, index) {
170
+ const temporary = `${file}.tmp`;
171
+ await fs.promises.writeFile(temporary, index);
172
+ await fs.promises.rename(temporary, file);
173
+ }
174
+ function writeU32(bytes, at, value) {
175
+ b4a.writeUInt32LE(bytes, value, at);
176
+ }
177
+ function readU32(bytes, at) {
178
+ return b4a.readUInt32LE(bytes, at);
179
+ }
180
+ function writeU64(bytes, at, value) {
181
+ const high = Math.floor(value / 4_294_967_296);
182
+ writeU32(bytes, at, value - high * 4_294_967_296);
183
+ writeU32(bytes, at + 4, high);
184
+ }
185
+ function readU64(bytes, at) {
186
+ return readU32(bytes, at) + readU32(bytes, at + 4) * 4_294_967_296;
187
+ }
188
+ function timestamp(value) {
189
+ return Math.floor(value * 1000);
190
+ }
191
+ function noop() { }
@@ -5,6 +5,7 @@ export interface KnowledgeOptions {
5
5
  model: string;
6
6
  maxChunks?: number;
7
7
  minScore?: number;
8
+ hostVectors?: boolean;
8
9
  tool?: boolean;
9
10
  read?: readonly string[];
10
11
  }
@@ -40,6 +40,7 @@ export class Knowledge {
40
40
  model: config.model,
41
41
  maxChunks: config.maxChunks,
42
42
  minScore: config.minScore,
43
+ hostVectors: config.hostVectors,
43
44
  embed: ctx.service('embed')
44
45
  });
45
46
  store.start();
@@ -16,6 +16,7 @@ export interface StoredArtifact {
16
16
  export interface Manifest {
17
17
  format: typeof FORMAT;
18
18
  model: string;
19
+ weights?: string;
19
20
  dimensions: number;
20
21
  nextId: number;
21
22
  seq: number;
@@ -49,5 +50,5 @@ export declare function splitLegacy(legacy: LegacyManifest): Split;
49
50
  export declare function readManifest(file: string): Promise<Manifest | LegacyManifest | null>;
50
51
  export declare function writeManifest(file: string, manifest: Manifest): Promise<void>;
51
52
  export declare function readChunks(dir: string, ids: readonly string[]): Promise<StoredChunk[]>;
52
- export declare function writeChunks(dir: string, ids: readonly string[], chunks: StoredChunk[]): Promise<void>;
53
+ export declare function isStoredChunk(value: unknown): value is StoredChunk;
53
54
  export {};
@@ -60,15 +60,7 @@ export async function readChunks(dir, ids) {
60
60
  }
61
61
  return chunks;
62
62
  }
63
- export async function writeChunks(dir, ids, chunks) {
64
- const file = chunksFile(ids);
65
- if (!file) {
66
- return;
67
- }
68
- await fs.promises.mkdir(dir, { recursive: true });
69
- await fs.promises.writeFile(path.join(dir, file), JSON.stringify(chunks));
70
- }
71
- function isStoredChunk(value) {
63
+ export function isStoredChunk(value) {
72
64
  return (isRecord(value) &&
73
65
  typeof value.chunkId === 'string' &&
74
66
  typeof value.text === 'string' &&
@@ -82,5 +74,6 @@ function isManifest(value) {
82
74
  typeof value.nextId === 'number' &&
83
75
  typeof value.seq === 'number' &&
84
76
  (value.generation === undefined || typeof value.generation === 'number') &&
77
+ (value.weights === undefined || typeof value.weights === 'string') &&
85
78
  isRecord(value.artifacts));
86
79
  }
@@ -5,13 +5,16 @@ export interface KnowledgeStoreOptions {
5
5
  model: string;
6
6
  maxChunks?: number;
7
7
  minScore?: number;
8
+ hostVectors?: boolean;
8
9
  embed: EmbedHost;
9
10
  }
10
11
  export declare class KnowledgeStore implements KnowledgeService {
11
12
  private readonly _dir;
12
13
  private readonly _model;
14
+ private _weights;
13
15
  private readonly _maxChunks;
14
16
  private readonly _minScore;
17
+ private readonly _hostVectors;
15
18
  private readonly _embed;
16
19
  private _manifest;
17
20
  private readonly _located;
@@ -26,7 +29,7 @@ export declare class KnowledgeStore implements KnowledgeService {
26
29
  private _asking;
27
30
  private _answered;
28
31
  private _closed;
29
- constructor({ dir, model, maxChunks, minScore, embed }: KnowledgeStoreOptions);
32
+ constructor({ dir, model, maxChunks, minScore, hostVectors, embed }: KnowledgeStoreOptions);
30
33
  start(): void;
31
34
  upsert(artifact: KnowledgeArtifact): Promise<KnowledgeUpsertResult>;
32
35
  remove(artifactId: string): Promise<KnowledgeRemoved>;
@@ -40,6 +43,7 @@ export declare class KnowledgeStore implements KnowledgeService {
40
43
  private _locked;
41
44
  private _ready;
42
45
  private _recovering;
46
+ private _sameEmbedder;
43
47
  private _open;
44
48
  private _split;
45
49
  private _load;
@@ -1,9 +1,10 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { isRecord } from '../../lib/guards.js';
4
- import { CHUNKS_DIR, MANIFEST_FILE, chunksFile, emptyManifest, indexedChunks, isLegacy, isSnapshotFile, readChunks, readManifest, snapshotFile, splitLegacy, writeChunks, writeManifest } from './manifest.js';
4
+ import { CHUNKS_DIR, MANIFEST_FILE, chunksFile, emptyManifest, indexedChunks, isLegacy, isSnapshotFile, readChunks, readManifest, snapshotFile, splitLegacy, writeManifest } from './manifest.js';
5
+ import { chunkIndexFile, readChunksAt, writeChunks } from './chunk-index.js';
5
6
  const DEFAULT_K = 5;
6
- const DEFAULT_MIN_SCORE = 0.4;
7
+ const DEFAULT_MIN_SCORE = 0.33;
7
8
  const VECTOR_INDEX_NOT_FOUND = 52851;
8
9
  const PERSIST_DELAY_MS = 1000;
9
10
  const EMBED_BATCH = 32;
@@ -36,8 +37,10 @@ function isNotFound(error) {
36
37
  export class KnowledgeStore {
37
38
  _dir;
38
39
  _model;
40
+ _weights;
39
41
  _maxChunks;
40
42
  _minScore;
43
+ _hostVectors;
41
44
  _embed;
42
45
  _manifest;
43
46
  _located;
@@ -52,11 +55,13 @@ export class KnowledgeStore {
52
55
  _asking;
53
56
  _answered;
54
57
  _closed;
55
- constructor({ dir, model, maxChunks = Infinity, minScore = DEFAULT_MIN_SCORE, embed }) {
58
+ constructor({ dir, model, maxChunks = Infinity, minScore = DEFAULT_MIN_SCORE, hostVectors = false, embed }) {
56
59
  this._dir = path.resolve(dir);
57
60
  this._model = model;
61
+ this._weights = undefined;
58
62
  this._maxChunks = maxChunks;
59
63
  this._minScore = minScore;
64
+ this._hostVectors = hostVectors;
60
65
  this._embed = embed;
61
66
  this._manifest = emptyManifest(model);
62
67
  this._located = new Map();
@@ -201,7 +206,13 @@ export class KnowledgeStore {
201
206
  return run();
202
207
  }
203
208
  }
209
+ _sameEmbedder(saved) {
210
+ return (saved.model === this._model &&
211
+ (this._weights === undefined || saved.weights === this._weights));
212
+ }
204
213
  async _open() {
214
+ this._weights = await this._embed.weights(this._model);
215
+ this._manifest.weights = this._weights;
205
216
  const read = await readManifest(this._file(MANIFEST_FILE));
206
217
  await this._sweep(snapshotFile(read?.generation));
207
218
  const saved = read && isLegacy(read) ? await this._split(read) : read;
@@ -209,8 +220,15 @@ export class KnowledgeStore {
209
220
  if (!saved) {
210
221
  return;
211
222
  }
212
- if (saved.model !== this._model) {
213
- this._manifest = { ...saved, model: this._model, dimensions: 0 };
223
+ if (!this._sameEmbedder(saved) && this._hostVectors) {
224
+ await this._sweepChunks(null);
225
+ await this._sweep('');
226
+ this._manifest = { ...emptyManifest(this._model), weights: this._weights };
227
+ await writeManifest(this._file(MANIFEST_FILE), this._manifest);
228
+ return;
229
+ }
230
+ if (!this._sameEmbedder(saved)) {
231
+ this._manifest = { ...saved, model: this._model, weights: this._weights, dimensions: 0 };
214
232
  this._markPending();
215
233
  }
216
234
  else {
@@ -282,7 +300,7 @@ export class KnowledgeStore {
282
300
  this._refill();
283
301
  }
284
302
  async _loadCurrent(saved) {
285
- const index = saved?.model === this._model ? await this._load(saved) : null;
303
+ const index = saved && this._sameEmbedder(saved) ? await this._load(saved) : null;
286
304
  const { dimensions } = this._manifest;
287
305
  if (index && dimensions !== 0 && index.dim !== dimensions) {
288
306
  await index.dispose().catch(noop);
@@ -380,6 +398,10 @@ export class KnowledgeStore {
380
398
  const file = chunksFile(stored.ids);
381
399
  if (file) {
382
400
  this._freed.push(file);
401
+ const index = chunkIndexFile(stored.ids);
402
+ if (index) {
403
+ this._freed.push(index, `${index}.tmp`);
404
+ }
383
405
  }
384
406
  this._changed();
385
407
  return stored.ids.length;
@@ -496,19 +518,22 @@ export class KnowledgeStore {
496
518
  return new Map(Object.entries(this._manifest.artifacts).filter(([, stored]) => !stored.pending && stored.ids.length > 0 && scopes.has(stored.scope)));
497
519
  }
498
520
  async _withText(found) {
521
+ const positions = new Map();
522
+ for (const { artifactId, at } of found) {
523
+ positions.set(artifactId, (positions.get(artifactId) ?? new Set()).add(at));
524
+ }
499
525
  const files = new Map();
500
- const read = (artifactId, ids) => {
501
- const chunks = files.get(artifactId) ?? this._chunks(ids);
502
- files.set(artifactId, chunks);
503
- return chunks;
504
- };
526
+ for (const [artifactId, selected] of positions) {
527
+ const { ids } = this._manifest.artifacts[artifactId];
528
+ files.set(artifactId, readChunksAt(this._file(CHUNKS_DIR), ids, selected).catch(() => null));
529
+ }
505
530
  const hits = await Promise.all(found.map(async ({ artifactId, at, score }) => {
506
- const { scope, ids } = this._manifest.artifacts[artifactId];
507
- const chunks = await read(artifactId, ids);
508
- if (!chunks) {
531
+ const { scope } = this._manifest.artifacts[artifactId];
532
+ const chunk = (await files.get(artifactId))?.get(at);
533
+ if (!chunk) {
509
534
  return [];
510
535
  }
511
- const { chunkId, text, metadata } = chunks[at];
536
+ const { chunkId, text, metadata } = chunk;
512
537
  return [{ artifactId, chunkId, scope, text, metadata, score }];
513
538
  }));
514
539
  for (const [artifactId, chunks] of files) {
@@ -582,7 +607,10 @@ export class KnowledgeStore {
582
607
  await this._remove('.', files.filter((file) => isSnapshotFile(file) && file !== kept));
583
608
  }
584
609
  async _sweepChunks(saved) {
585
- const named = new Set(Object.values(saved?.artifacts ?? {}).map((stored) => chunksFile(stored.ids)));
610
+ const named = new Set(Object.values(saved?.artifacts ?? {}).flatMap((stored) => [
611
+ chunksFile(stored.ids),
612
+ chunkIndexFile(stored.ids)
613
+ ]));
586
614
  const files = await fs.promises.readdir(this._file(CHUNKS_DIR)).catch(() => []);
587
615
  await this._remove(CHUNKS_DIR, files.filter((file) => !named.has(file)));
588
616
  return new Set(files.filter((file) => named.has(file)));
@@ -16,8 +16,16 @@ export interface RequestOptions {
16
16
  export type NotificationHandler = (method: string, params: unknown) => void;
17
17
  export declare function encodeMessage(message: RpcMessage): Buffer;
18
18
  export declare class FrameDecoder {
19
- private _buffer;
19
+ private _header;
20
+ private _headerBytes;
21
+ private _headerEnd;
22
+ private _bodyLength;
23
+ private _body;
24
+ private _bodyBytes;
20
25
  push(chunk: Uint8Array): RpcMessage[];
26
+ private _readHeader;
27
+ private _startBody;
28
+ private _readBody;
21
29
  }
22
30
  export declare class RpcConnection {
23
31
  private readonly _write;