@qvac/harness 1.0.1 → 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 (93) hide show
  1. package/CHANGELOG.md +137 -6
  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/files/list-dir.js +79 -32
  55. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  56. package/dist-lib/lib/tools/fs/walk.js +64 -30
  57. package/dist-lib/lib/tools/office.js +8 -5
  58. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  59. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  60. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  61. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  62. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  63. package/dist-lib/plugins/image/generate-image.js +9 -1
  64. package/dist-lib/plugins/image/index.js +6 -2
  65. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  66. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  67. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  68. package/dist-lib/plugins/knowledge/index.js +1 -0
  69. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  70. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  71. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  72. package/dist-lib/plugins/knowledge/store.js +44 -16
  73. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  74. package/dist-lib/plugins/lsp/rpc.js +81 -17
  75. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  76. package/dist-lib/plugins/music/generate-music.js +14 -1
  77. package/dist-lib/plugins/music/index.js +4 -1
  78. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  79. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  80. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  81. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  82. package/dist-lib/schema/harness.js +28 -2
  83. package/dist-lib/spec/bind.js +3 -0
  84. package/dist-lib/spec/calls.js +1 -0
  85. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  86. package/dist-lib/spec/hrpc/index.js +15 -3
  87. package/dist-lib/spec/hrpc/messages.js +87 -6
  88. package/dist-lib/spec/hyperschema/index.js +87 -6
  89. package/dist-lib/spec/hyperschema/schema.json +70 -2
  90. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  91. package/package.json +29 -28
  92. package/scripts/addon-externals.cjs +1 -0
  93. package/worker/harness-sidecar.mjs +12 -1
@@ -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;
@@ -1,38 +1,102 @@
1
1
  import b4a from 'b4a';
2
2
  import { isRecord } from '../../lib/guards.js';
3
3
  const HEADER_END = b4a.from('\r\n\r\n');
4
+ const HEADER_END_BYTES = [13, 10, 13, 10];
4
5
  const CONTENT_LENGTH = /^content-length:\s*(\d+)\s*$/im;
5
6
  export function encodeMessage(message) {
6
7
  const body = JSON.stringify({ jsonrpc: '2.0', ...message });
7
8
  return b4a.from(`Content-Length: ${b4a.byteLength(body)}\r\n\r\n${body}`);
8
9
  }
9
10
  export class FrameDecoder {
10
- _buffer = b4a.alloc(0);
11
+ _header = [];
12
+ _headerBytes = 0;
13
+ _headerEnd = 0;
14
+ _bodyLength = null;
15
+ _body = [];
16
+ _bodyBytes = 0;
11
17
  push(chunk) {
12
- this._buffer = this._buffer.byteLength ? b4a.concat([this._buffer, chunk]) : chunk;
13
18
  const messages = [];
14
- while (true) {
15
- const end = b4a.indexOf(this._buffer, HEADER_END);
16
- if (end === -1) {
17
- break;
19
+ let at = 0;
20
+ while (at < chunk.byteLength || this._bodyLength === 0) {
21
+ if (this._bodyLength === null) {
22
+ const next = this._readHeader(chunk, at);
23
+ if (next === null) {
24
+ break;
25
+ }
26
+ at = next;
27
+ continue;
18
28
  }
19
- const length = CONTENT_LENGTH.exec(b4a.toString(this._buffer, 'ascii', 0, end));
20
- if (!length) {
21
- throw new Error('language server sent a frame with no Content-Length');
29
+ const frame = this._readBody(chunk, at);
30
+ at = frame.at;
31
+ if (frame.message) {
32
+ messages.push(frame.message);
22
33
  }
23
- const start = end + HEADER_END.byteLength;
24
- const stop = start + Number(length[1]);
25
- if (this._buffer.byteLength < stop) {
34
+ if (!frame.complete) {
26
35
  break;
27
36
  }
28
- const message = JSON.parse(b4a.toString(this._buffer, 'utf8', start, stop));
29
- if (isRecord(message)) {
30
- messages.push(toMessage(message));
31
- }
32
- this._buffer = this._buffer.subarray(stop);
33
37
  }
34
38
  return messages;
35
39
  }
40
+ _readHeader(chunk, from) {
41
+ let at = from;
42
+ let ended = false;
43
+ while (at < chunk.byteLength) {
44
+ const byte = chunk[at++];
45
+ if (byte === HEADER_END_BYTES[this._headerEnd]) {
46
+ this._headerEnd++;
47
+ if (this._headerEnd === HEADER_END_BYTES.length) {
48
+ ended = true;
49
+ break;
50
+ }
51
+ }
52
+ else {
53
+ this._headerEnd = byte === HEADER_END_BYTES[0] ? 1 : 0;
54
+ }
55
+ }
56
+ const part = chunk.subarray(from, at);
57
+ if (part.byteLength > 0) {
58
+ this._header.push(part);
59
+ this._headerBytes += part.byteLength;
60
+ }
61
+ if (!ended) {
62
+ return null;
63
+ }
64
+ this._startBody();
65
+ return at;
66
+ }
67
+ _startBody() {
68
+ const header = this._header.length > 1 ? b4a.concat(this._header) : this._header[0];
69
+ const length = CONTENT_LENGTH.exec(b4a.toString(header, 'ascii', 0, this._headerBytes - HEADER_END.byteLength));
70
+ if (!length) {
71
+ throw new Error('language server sent a frame with no Content-Length');
72
+ }
73
+ this._bodyLength = Number(length[1]);
74
+ this._header = [];
75
+ this._headerBytes = 0;
76
+ this._headerEnd = 0;
77
+ }
78
+ _readBody(chunk, from) {
79
+ const expected = this._bodyLength;
80
+ if (expected === null) {
81
+ return { at: from, complete: false };
82
+ }
83
+ const length = Math.min(expected - this._bodyBytes, chunk.byteLength - from);
84
+ const part = chunk.subarray(from, from + length);
85
+ if (part.byteLength > 0) {
86
+ this._body.push(part);
87
+ this._bodyBytes += part.byteLength;
88
+ }
89
+ if (this._bodyBytes < expected) {
90
+ return { at: from + part.byteLength, complete: false };
91
+ }
92
+ const bytes = this._body.length > 1 ? b4a.concat(this._body) : (this._body[0] ?? b4a.alloc(0));
93
+ const value = JSON.parse(b4a.toString(bytes, 'utf8'));
94
+ const message = isRecord(value) ? toMessage(value) : undefined;
95
+ this._bodyLength = null;
96
+ this._body = [];
97
+ this._bodyBytes = 0;
98
+ return { at: from + part.byteLength, complete: true, message };
99
+ }
36
100
  }
37
101
  function toMessage(value) {
38
102
  const { id, method, params, result, error } = value;
@@ -2,7 +2,7 @@ import { type AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  import type { MediaRoundServer, MusicSettings, ToolDefinition, ToolExecuteContext } from '../../lib/contract/index.ts';
3
3
  import type { ModelSrc } from '../../lib/models/context.ts';
4
4
  import { type MusicClamps, type MusicModelStages } 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
  export declare const MAX_DURATION_SECONDS = 300;
@@ -71,7 +71,7 @@ export interface MusicRuntimeOptions extends MusicModelStages {
71
71
  inferenceSteps?: number;
72
72
  useGpu?: boolean;
73
73
  onProgress?: (model: string, progress: Record<string, unknown>) => void;
74
- onBeforeLoad?: (signal: BareAbortSignal | undefined, srcs: ReadonlyArray<string>) => Promise<void>;
74
+ onBeforeLoad?: (signal: BareAbortSignal | undefined, srcs: ReadonlyArray<string>) => Promise<ReleaseRoom>;
75
75
  hold?: HoldFn;
76
76
  requests?: LoadRequests;
77
77
  loads?: Pick<ModelHost, 'track'>;
@@ -61,6 +61,11 @@ export function createMusicRuntime({ loadSdk, onProgress, onBeforeLoad, hold, re
61
61
  let loading = null;
62
62
  let residentFingerprint = null;
63
63
  let busy = false;
64
+ let releaseRoom = noop;
65
+ const freeRoom = () => {
66
+ releaseRoom();
67
+ releaseRoom = noop;
68
+ };
64
69
  const lock = new ScopeLock();
65
70
  const defaultSteps = baseSteps ?? musicDefaultSteps(musicChoiceForDit(base.dit));
66
71
  const doUnload = async () => {
@@ -73,12 +78,14 @@ export function createMusicRuntime({ loadSdk, onProgress, onBeforeLoad, hold, re
73
78
  if (!loaded) {
74
79
  loading = null;
75
80
  residentFingerprint = null;
81
+ freeRoom();
76
82
  return;
77
83
  }
78
84
  const sdk = await loadSdk();
79
85
  await sdk.unloadModel({ modelId: loaded.modelId });
80
86
  loading = null;
81
87
  residentFingerprint = null;
88
+ freeRoom();
82
89
  };
83
90
  const unload = async () => {
84
91
  await lock.lock();
@@ -118,6 +125,7 @@ export function createMusicRuntime({ loadSdk, onProgress, onBeforeLoad, hold, re
118
125
  })().catch((err) => {
119
126
  loading = null;
120
127
  residentFingerprint = null;
128
+ freeRoom();
121
129
  requests.failed(name, err);
122
130
  throw err;
123
131
  });
@@ -130,7 +138,12 @@ export function createMusicRuntime({ loadSdk, onProgress, onBeforeLoad, hold, re
130
138
  await doUnload();
131
139
  }
132
140
  if (!loading && onBeforeLoad) {
133
- await onBeforeLoad(signal, [stages.dit, stages.textEnc, stages.lm, stages.vae]);
141
+ releaseRoom = await onBeforeLoad(signal, [
142
+ stages.dit,
143
+ stages.textEnc,
144
+ stages.lm,
145
+ stages.vae
146
+ ]);
134
147
  }
135
148
  residentFingerprint = fingerprint;
136
149
  loading ??= loadStages(sdk, stages, steps);
@@ -46,7 +46,10 @@ export class Music {
46
46
  hold: models.hold,
47
47
  requests: models.requests,
48
48
  onProgress: (name, progress) => models.emit(models.progressState(name, progress)),
49
- onBeforeLoad: (signal, srcs) => models.makeRoom(signal, new HarnessError('CHAT_MODEL_BUSY', ['music']), srcs)
49
+ onBeforeLoad: (signal, srcs) => models.makeRoom(signal, new HarnessError('CHAT_MODEL_BUSY', ['music']), {
50
+ srcs,
51
+ unloadIdle: () => runtime.unloadIdle()
52
+ })
50
53
  });
51
54
  return {
52
55
  tools: [createGenerateMusicTool(runtime, clamps)],