@qvac/harness 1.0.0-rc.13 → 1.0.0-rc.15

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 (79) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +36 -6
  3. package/dist-lib/index.d.ts +1 -0
  4. package/dist-lib/index.js +2 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +20 -1
  6. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +1 -1
  7. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +10 -6
  8. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +2 -2
  9. package/dist-lib/lib/capabilities/completion-engine/actors/stream.d.ts +1 -1
  10. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +8 -0
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +6 -2
  12. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +10 -4
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +15 -0
  14. package/dist-lib/lib/capabilities/completion-engine/loop.js +2 -1
  15. package/dist-lib/lib/capabilities/completion-engine/operations.js +1 -0
  16. package/dist-lib/lib/capabilities/completion-engine/ports.js +1 -1
  17. package/dist-lib/lib/capabilities/completion-engine/round.js +16 -7
  18. package/dist-lib/lib/capabilities/completion-engine/session.d.ts +3 -3
  19. package/dist-lib/lib/capabilities/prompt-prefix.d.ts +2 -0
  20. package/dist-lib/lib/capabilities/prompt-prefix.js +8 -0
  21. package/dist-lib/lib/capabilities/sdk-tool.d.ts +1 -1
  22. package/dist-lib/lib/capabilities/sdk-tool.js +17 -2
  23. package/dist-lib/lib/capabilities/usage-breakdown.d.ts +1 -0
  24. package/dist-lib/lib/capabilities/usage-breakdown.js +4 -1
  25. package/dist-lib/lib/contract/completion.d.ts +3 -0
  26. package/dist-lib/lib/contract/run.d.ts +2 -0
  27. package/dist-lib/lib/helpers/goal-check.d.ts +26 -0
  28. package/dist-lib/lib/helpers/goal-check.js +248 -22
  29. package/dist-lib/lib/helpers/spawn-path.d.ts +1 -0
  30. package/dist-lib/lib/helpers/spawn-path.js +2 -1
  31. package/dist-lib/lib/machine/completion/actions/completion.d.ts +3 -2
  32. package/dist-lib/lib/machine/completion/actions/completion.js +65 -15
  33. package/dist-lib/lib/machine/completion/actions/tools.js +47 -6
  34. package/dist-lib/lib/machine/completion/context.js +5 -1
  35. package/dist-lib/lib/machine/completion/implementations.d.ts +1 -0
  36. package/dist-lib/lib/machine/completion/implementations.js +7 -0
  37. package/dist-lib/lib/machine/completion/machine.d.ts +4 -1
  38. package/dist-lib/lib/machine/completion/machine.js +10 -1
  39. package/dist-lib/lib/machine/completion/rules.d.ts +3 -1
  40. package/dist-lib/lib/machine/completion/rules.js +25 -4
  41. package/dist-lib/lib/machine/completion/types.d.ts +16 -0
  42. package/dist-lib/lib/machine/index.d.ts +6 -1
  43. package/dist-lib/lib/machine/index.js +2 -0
  44. package/dist-lib/lib/models/model-pool.js +1 -2
  45. package/dist-lib/lib/office/engine/pptx/presentation.js +10 -5
  46. package/dist-lib/lib/sidecar/index.js +1 -1
  47. package/dist-lib/lib/skills-host/index.d.ts +1 -1
  48. package/dist-lib/lib/skills-host/index.js +3 -2
  49. package/dist-lib/lib/tools/exec/runner.d.ts +4 -0
  50. package/dist-lib/lib/tools/exec/runner.js +20 -3
  51. package/dist-lib/lib/tools/office.js +1 -0
  52. package/dist-lib/lib/tools/skills/overlay-watch.d.ts +2 -2
  53. package/dist-lib/lib/tools/skills/overlay-watch.js +4 -3
  54. package/dist-lib/lib/wire.js +9 -3
  55. package/dist-lib/plugins/image/index.js +5 -5
  56. package/dist-lib/plugins/knowledge/index.d.ts +3 -0
  57. package/dist-lib/plugins/knowledge/index.js +4 -0
  58. package/dist-lib/plugins/knowledge/manifest.d.ts +28 -4
  59. package/dist-lib/plugins/knowledge/manifest.js +49 -4
  60. package/dist-lib/plugins/knowledge/store.d.ts +10 -1
  61. package/dist-lib/plugins/knowledge/store.js +127 -57
  62. package/dist-lib/plugins/music/index.js +4 -4
  63. package/dist-lib/plugins/obsidian/index.js +14 -4
  64. package/dist-lib/plugins/python/index.d.ts +3 -1
  65. package/dist-lib/plugins/python/index.js +4 -1
  66. package/dist-lib/plugins/python/python-adapter.d.ts +2 -1
  67. package/dist-lib/plugins/python/python-adapter.js +8 -1
  68. package/dist-lib/plugins/sandbox-linux/index.js +2 -2
  69. package/dist-lib/plugins/sandbox-macos/index.js +2 -2
  70. package/dist-lib/plugins/sandbox-vm/index.d.ts +2 -1
  71. package/dist-lib/plugins/sandbox-vm/index.js +2 -2
  72. package/dist-lib/plugins/sandbox-vm/vm-shell.d.ts +3 -1
  73. package/dist-lib/plugins/sandbox-vm/vm-shell.js +45 -16
  74. package/dist-lib/plugins/sandbox-windows/index.js +2 -2
  75. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  76. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  77. package/package.json +27 -22
  78. package/scripts/addon-externals.cjs +4 -1
  79. package/patches/localwatch@1.4.3.patch +0 -13
@@ -1,6 +1,7 @@
1
1
  export declare const MANIFEST_FILE = "knowledge.json";
2
+ export declare const CHUNKS_DIR = "chunks";
3
+ declare const FORMAT = 2;
2
4
  export interface StoredChunk {
3
- id: string;
4
5
  chunkId: string;
5
6
  text: string;
6
7
  metadata?: Record<string, unknown>;
@@ -10,9 +11,10 @@ export interface StoredArtifact {
10
11
  scope: string;
11
12
  seq: number;
12
13
  pending?: boolean;
13
- chunks: StoredChunk[];
14
+ ids: string[];
14
15
  }
15
16
  export interface Manifest {
17
+ format: typeof FORMAT;
16
18
  model: string;
17
19
  dimensions: number;
18
20
  nextId: number;
@@ -20,10 +22,32 @@ export interface Manifest {
20
22
  generation?: number;
21
23
  artifacts: Record<string, StoredArtifact>;
22
24
  }
25
+ interface LegacyChunk extends StoredChunk {
26
+ id: string;
27
+ }
28
+ interface LegacyArtifact extends Omit<StoredArtifact, 'ids'> {
29
+ chunks: LegacyChunk[];
30
+ }
31
+ export interface LegacyManifest extends Omit<Manifest, 'format' | 'artifacts'> {
32
+ artifacts: Record<string, LegacyArtifact>;
33
+ }
23
34
  export declare function emptyManifest(model: string): Manifest;
24
35
  export declare function snapshotFile(generation: number | undefined): string;
25
36
  export declare function isSnapshotFile(file: string): boolean;
26
- export declare function chunkIds(stored: StoredArtifact): string[];
37
+ export declare function chunksFile(ids: readonly string[]): string | null;
27
38
  export declare function indexedChunks(manifest: Manifest): number;
28
- export declare function readManifest(file: string): Promise<Manifest | null>;
39
+ export declare function isLegacy(manifest: Manifest | LegacyManifest): manifest is LegacyManifest;
40
+ export interface ChunkFile {
41
+ ids: string[];
42
+ chunks: StoredChunk[];
43
+ }
44
+ export interface Split {
45
+ manifest: Manifest;
46
+ files: ChunkFile[];
47
+ }
48
+ export declare function splitLegacy(legacy: LegacyManifest): Split;
49
+ export declare function readManifest(file: string): Promise<Manifest | LegacyManifest | null>;
29
50
  export declare function writeManifest(file: string, manifest: Manifest): Promise<void>;
51
+ 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 {};
@@ -1,9 +1,12 @@
1
1
  import fs from 'fs';
2
+ import path from 'path';
2
3
  import { isRecord } from '../../lib/guards.js';
3
4
  export const MANIFEST_FILE = 'knowledge.json';
5
+ export const CHUNKS_DIR = 'chunks';
4
6
  const SNAPSHOT = /^knowledge(\.\d+)?\.qvi$/;
7
+ const FORMAT = 2;
5
8
  export function emptyManifest(model) {
6
- return { model, dimensions: 0, nextId: 1, seq: 0, artifacts: {} };
9
+ return { format: FORMAT, model, dimensions: 0, nextId: 1, seq: 0, artifacts: {} };
7
10
  }
8
11
  export function snapshotFile(generation) {
9
12
  return generation === undefined ? 'knowledge.qvi' : `knowledge.${generation}.qvi`;
@@ -11,11 +14,27 @@ export function snapshotFile(generation) {
11
14
  export function isSnapshotFile(file) {
12
15
  return SNAPSHOT.test(file);
13
16
  }
14
- export function chunkIds(stored) {
15
- return stored.chunks.map((chunk) => chunk.id);
17
+ export function chunksFile(ids) {
18
+ return ids.length ? `${ids[0]}.json` : null;
16
19
  }
17
20
  export function indexedChunks(manifest) {
18
- return Object.values(manifest.artifacts).reduce((sum, stored) => sum + (stored.pending ? 0 : stored.chunks.length), 0);
21
+ return Object.values(manifest.artifacts).reduce((sum, stored) => sum + (stored.pending ? 0 : stored.ids.length), 0);
22
+ }
23
+ export function isLegacy(manifest) {
24
+ return !('format' in manifest);
25
+ }
26
+ export function splitLegacy(legacy) {
27
+ const files = [];
28
+ const artifacts = {};
29
+ for (const [artifactId, { chunks, ...header }] of Object.entries(legacy.artifacts)) {
30
+ const ids = chunks.map((chunk) => chunk.id);
31
+ files.push({
32
+ ids,
33
+ chunks: chunks.map(({ chunkId, text, metadata }) => ({ chunkId, text, metadata }))
34
+ });
35
+ artifacts[artifactId] = { ...header, ids };
36
+ }
37
+ return { manifest: { ...legacy, format: FORMAT, artifacts }, files };
19
38
  }
20
39
  export async function readManifest(file) {
21
40
  try {
@@ -30,8 +49,34 @@ export async function writeManifest(file, manifest) {
30
49
  await fs.promises.writeFile(`${file}.tmp`, JSON.stringify(manifest));
31
50
  await fs.promises.rename(`${file}.tmp`, file);
32
51
  }
52
+ export async function readChunks(dir, ids) {
53
+ const file = chunksFile(ids);
54
+ if (!file) {
55
+ return [];
56
+ }
57
+ const chunks = JSON.parse(await fs.promises.readFile(path.join(dir, file), 'utf8'));
58
+ if (!Array.isArray(chunks) || chunks.length !== ids.length || !chunks.every(isStoredChunk)) {
59
+ throw new Error(`${file} does not hold the artifact's ${ids.length} chunks`);
60
+ }
61
+ return chunks;
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) {
72
+ return (isRecord(value) &&
73
+ typeof value.chunkId === 'string' &&
74
+ typeof value.text === 'string' &&
75
+ (value.metadata === undefined || isRecord(value.metadata)));
76
+ }
33
77
  function isManifest(value) {
34
78
  return (isRecord(value) &&
79
+ (value.format === undefined || value.format === FORMAT) &&
35
80
  typeof value.model === 'string' &&
36
81
  typeof value.dimensions === 'number' &&
37
82
  typeof value.nextId === 'number' &&
@@ -14,6 +14,8 @@ export declare class KnowledgeStore implements KnowledgeService {
14
14
  private readonly _minScore;
15
15
  private readonly _embed;
16
16
  private _manifest;
17
+ private readonly _located;
18
+ private _freed;
17
19
  private _index;
18
20
  private _opened;
19
21
  private _writes;
@@ -39,6 +41,7 @@ export declare class KnowledgeStore implements KnowledgeService {
39
41
  private _ready;
40
42
  private _recovering;
41
43
  private _open;
44
+ private _split;
42
45
  private _load;
43
46
  private _reload;
44
47
  private _loadCurrent;
@@ -49,6 +52,7 @@ export declare class KnowledgeStore implements KnowledgeService {
49
52
  private _apply;
50
53
  private _indexFor;
51
54
  private _drop;
55
+ private _locate;
52
56
  private _evict;
53
57
  private _release;
54
58
  private _refill;
@@ -59,7 +63,10 @@ export declare class KnowledgeStore implements KnowledgeService {
59
63
  private _searchable;
60
64
  private _search;
61
65
  private _ranked;
62
- private _chunksById;
66
+ private _granted;
67
+ private _withText;
68
+ private _chunks;
69
+ private _lose;
63
70
  private _warm;
64
71
  private _chunkCount;
65
72
  private _file;
@@ -67,4 +74,6 @@ export declare class KnowledgeStore implements KnowledgeService {
67
74
  private _writeOut;
68
75
  private _persist;
69
76
  private _sweep;
77
+ private _sweepChunks;
78
+ private _remove;
70
79
  }
@@ -1,7 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { isRecord } from '../../lib/guards.js';
4
- import { MANIFEST_FILE, chunkIds, emptyManifest, indexedChunks, isSnapshotFile, readManifest, snapshotFile, writeManifest } from './manifest.js';
4
+ import { CHUNKS_DIR, MANIFEST_FILE, chunksFile, emptyManifest, indexedChunks, isLegacy, isSnapshotFile, readChunks, readManifest, snapshotFile, splitLegacy, writeChunks, writeManifest } from './manifest.js';
5
5
  const DEFAULT_K = 5;
6
6
  const DEFAULT_MIN_SCORE = 0.4;
7
7
  const VECTOR_INDEX_NOT_FOUND = 52851;
@@ -21,9 +21,11 @@ function matches(embedding, want) {
21
21
  embedding.vectors.length === want.chunks &&
22
22
  embedding.vectors.every((row) => row.length === embedding.dimensions));
23
23
  }
24
+ function storedChunk({ id, text, metadata }) {
25
+ return { chunkId: id, text, metadata };
26
+ }
24
27
  function sameChunks(a, b) {
25
- return (a.chunks.length === b.chunks.length &&
26
- a.chunks.every((chunk, at) => chunk.id === b.chunks[at]?.id));
28
+ return a.ids.length === b.ids.length && a.ids.every((id, at) => id === b.ids[at]);
27
29
  }
28
30
  function turn() {
29
31
  return new Promise((resolve) => setImmediate(resolve));
@@ -38,6 +40,8 @@ export class KnowledgeStore {
38
40
  _minScore;
39
41
  _embed;
40
42
  _manifest;
43
+ _located;
44
+ _freed;
41
45
  _index;
42
46
  _opened;
43
47
  _writes;
@@ -55,6 +59,8 @@ export class KnowledgeStore {
55
59
  this._minScore = minScore;
56
60
  this._embed = embed;
57
61
  this._manifest = emptyManifest(model);
62
+ this._located = new Map();
63
+ this._freed = [];
58
64
  this._index = null;
59
65
  this._opened = null;
60
66
  this._writes = Promise.resolve();
@@ -121,7 +127,7 @@ export class KnowledgeStore {
121
127
  artifactId,
122
128
  version: stored.version,
123
129
  scope: stored.scope,
124
- chunks: stored.chunks.length
130
+ chunks: stored.ids.length
125
131
  }));
126
132
  const chunks = entries.reduce((sum, entry) => sum + entry.chunks, 0);
127
133
  return {
@@ -196,8 +202,10 @@ export class KnowledgeStore {
196
202
  }
197
203
  }
198
204
  async _open() {
199
- const saved = await readManifest(this._file(MANIFEST_FILE));
200
- await this._sweep(snapshotFile(saved?.generation));
205
+ const read = await readManifest(this._file(MANIFEST_FILE));
206
+ await this._sweep(snapshotFile(read?.generation));
207
+ const saved = read && isLegacy(read) ? await this._split(read) : read;
208
+ const written = await this._sweepChunks(saved);
201
209
  if (!saved) {
202
210
  return;
203
211
  }
@@ -212,8 +220,25 @@ export class KnowledgeStore {
212
220
  this._markPending();
213
221
  }
214
222
  }
223
+ for (const [artifactId, stored] of Object.entries(this._manifest.artifacts)) {
224
+ const file = chunksFile(stored.ids);
225
+ if (file && !written.has(file)) {
226
+ await this._lose(artifactId, stored);
227
+ }
228
+ else {
229
+ this._locate(artifactId, stored);
230
+ }
231
+ }
215
232
  this._refill();
216
233
  }
234
+ async _split(legacy) {
235
+ const { manifest, files } = splitLegacy(legacy);
236
+ for (const { ids, chunks } of files) {
237
+ await writeChunks(this._file(CHUNKS_DIR), ids, chunks);
238
+ }
239
+ await writeManifest(this._file(MANIFEST_FILE), manifest);
240
+ return manifest;
241
+ }
217
242
  async _load(saved) {
218
243
  const chunks = indexedChunks(saved);
219
244
  if (chunks === 0) {
@@ -233,7 +258,8 @@ export class KnowledgeStore {
233
258
  }
234
259
  async _reload() {
235
260
  this._index = null;
236
- const saved = await readManifest(this._file(MANIFEST_FILE));
261
+ const read = await readManifest(this._file(MANIFEST_FILE));
262
+ const saved = read && !isLegacy(read) ? read : null;
237
263
  const index = await this._loadCurrent(saved);
238
264
  const written = new Map(Object.entries(index && saved ? saved.artifacts : {}).filter(([, stored]) => !stored.pending));
239
265
  const stale = [];
@@ -243,11 +269,11 @@ export class KnowledgeStore {
243
269
  if (before && !stored.pending && sameChunks(before, stored)) {
244
270
  continue;
245
271
  }
246
- stale.push(...(before ? chunkIds(before) : []));
247
- stored.pending = stored.chunks.length > 0 || undefined;
272
+ stale.push(...(before?.ids ?? []));
273
+ stored.pending = stored.ids.length > 0 || undefined;
248
274
  }
249
275
  for (const before of written.values()) {
250
- stale.push(...chunkIds(before));
276
+ stale.push(...before.ids);
251
277
  }
252
278
  if (index && stale.length) {
253
279
  await index.remove({ ids: stale });
@@ -266,7 +292,7 @@ export class KnowledgeStore {
266
292
  }
267
293
  _markPending() {
268
294
  for (const stored of Object.values(this._manifest.artifacts)) {
269
- stored.pending = stored.chunks.length > 0 || undefined;
295
+ stored.pending = stored.ids.length > 0 || undefined;
270
296
  }
271
297
  }
272
298
  async _reset(dimensions) {
@@ -310,27 +336,22 @@ export class KnowledgeStore {
310
336
  await this._reset(dim);
311
337
  }
312
338
  const fits = vectors.length > 0 && (manifest.dimensions === 0 || dim === manifest.dimensions);
313
- const stored = chunks.map((chunk) => ({
314
- id: String(manifest.nextId++),
315
- chunkId: chunk.id,
316
- text: chunk.text,
317
- metadata: chunk.metadata
318
- }));
339
+ const ids = chunks.map(() => String(manifest.nextId++));
340
+ await writeChunks(this._file(CHUNKS_DIR), ids, chunks.map(storedChunk));
319
341
  if (fits) {
320
342
  const index = await this._indexFor(dim);
321
- await index.add({ ids: stored.map((chunk) => chunk.id), vectors: vectors.map(unit) });
343
+ await index.add({ ids, vectors: vectors.map(unit) });
322
344
  }
323
345
  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
- }
346
+ const pending = (ids.length > 0 && !fits) || undefined;
347
+ const stored = { version, scope, seq: ++manifest.seq, pending, ids };
348
+ manifest.artifacts[artifactId] = stored;
349
+ this._locate(artifactId, stored);
329
350
  await this._evict(artifactId);
330
351
  await this._release();
331
352
  this._changed();
332
353
  this._refill();
333
- return { added: stored.length, embedded };
354
+ return { added: ids.length, embedded };
334
355
  }
335
356
  async _indexFor(dim) {
336
357
  if (this._index) {
@@ -349,12 +370,22 @@ export class KnowledgeStore {
349
370
  if (!stored) {
350
371
  return 0;
351
372
  }
352
- if (this._index && !stored.pending && stored.chunks.length) {
353
- await this._index.remove({ ids: chunkIds(stored) });
373
+ if (this._index && !stored.pending && stored.ids.length) {
374
+ await this._index.remove({ ids: stored.ids });
354
375
  }
355
376
  delete this._manifest.artifacts[artifactId];
377
+ for (const id of stored.ids) {
378
+ this._located.delete(id);
379
+ }
380
+ const file = chunksFile(stored.ids);
381
+ if (file) {
382
+ this._freed.push(file);
383
+ }
356
384
  this._changed();
357
- return stored.chunks.length;
385
+ return stored.ids.length;
386
+ }
387
+ _locate(artifactId, stored) {
388
+ stored.ids.forEach((id, at) => this._located.set(id, { artifactId, at }));
358
389
  }
359
390
  async _evict(keep) {
360
391
  const oldest = Object.entries(this._manifest.artifacts)
@@ -396,7 +427,12 @@ export class KnowledgeStore {
396
427
  if (this._manifest.artifacts[artifactId] !== stored || !stored.pending) {
397
428
  return;
398
429
  }
399
- const embedded = await this._embedTexts(stored.chunks.map((chunk) => chunk.text), { stopped: () => this._closed });
430
+ const chunks = await this._chunks(stored.ids);
431
+ if (!chunks) {
432
+ await this._locked(() => this._lose(artifactId, stored));
433
+ return;
434
+ }
435
+ const embedded = await this._embedTexts(chunks.map((chunk) => chunk.text), { stopped: () => this._closed });
400
436
  await this._locked(() => this._fill(artifactId, stored, embedded));
401
437
  }
402
438
  _nextPending() {
@@ -412,17 +448,17 @@ export class KnowledgeStore {
412
448
  await this._reset(dimensions);
413
449
  }
414
450
  const index = await this._indexFor(dimensions);
415
- await index.add({ ids: chunkIds(stored), vectors: vectors.map(unit) });
451
+ await index.add({ ids: stored.ids, vectors: vectors.map(unit) });
416
452
  delete stored.pending;
417
453
  this._changed();
418
454
  }
419
455
  _searchable(granted) {
420
- return Object.values(this._manifest.artifacts).some((stored) => !stored.pending && stored.chunks.length > 0 && granted.has(stored.scope));
456
+ return this._granted(granted).size > 0;
421
457
  }
422
458
  async _search({ scopes, focus, k = DEFAULT_K }, query) {
423
- const byId = this._chunksById(new Set(scopes));
459
+ const granted = this._granted(new Set(scopes));
424
460
  const index = this._index;
425
- if (!index || byId.size === 0) {
461
+ if (!index || granted.size === 0) {
426
462
  return [];
427
463
  }
428
464
  if (query.length !== index.dim) {
@@ -430,18 +466,24 @@ export class KnowledgeStore {
430
466
  return [];
431
467
  }
432
468
  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);
469
+ const focused = new Map([...granted].filter(([artifactId]) => named.has(artifactId)));
470
+ const hits = focused.size ? await this._ranked(index, { query, among: focused, k }) : [];
471
+ const found = hits.length
472
+ ? hits
473
+ : await this._ranked(index, { query, among: granted, k, floor: this._minScore });
474
+ return this._withText(found);
475
+ }
476
+ async _ranked(index, { query, among, k, floor = -Infinity }) {
477
+ const chunks = [...among.values()].reduce((sum, stored) => sum + stored.ids.length, 0);
478
+ const want = Math.min(k, chunks);
439
479
  let fetch = Math.min(index.length, want * 4);
440
480
  for (;;) {
441
481
  const hits = await index.search({ query: unit(query), k: fetch });
442
482
  const found = hits.flatMap((hit) => {
443
- const entry = byId.get(hit.id);
444
- return entry && hit.score >= floor ? [{ ...entry, score: hit.score }] : [];
483
+ const located = this._located.get(hit.id);
484
+ return located && among.has(located.artifactId) && hit.score >= floor
485
+ ? [{ ...located, score: hit.score }]
486
+ : [];
445
487
  });
446
488
  const floored = (hits.at(-1)?.score ?? -Infinity) < floor;
447
489
  if (found.length >= want || floored || fetch >= index.length) {
@@ -450,22 +492,41 @@ export class KnowledgeStore {
450
492
  fetch = Math.min(index.length, fetch * 4);
451
493
  }
452
494
  }
453
- _chunksById(granted) {
454
- const byId = new Map();
455
- for (const [artifactId, stored] of Object.entries(this._manifest.artifacts)) {
456
- if (stored.pending || !granted.has(stored.scope))
457
- continue;
458
- for (const chunk of stored.chunks) {
459
- byId.set(chunk.id, {
460
- artifactId,
461
- chunkId: chunk.chunkId,
462
- scope: stored.scope,
463
- text: chunk.text,
464
- metadata: chunk.metadata
465
- });
495
+ _granted(scopes) {
496
+ return new Map(Object.entries(this._manifest.artifacts).filter(([, stored]) => !stored.pending && stored.ids.length > 0 && scopes.has(stored.scope)));
497
+ }
498
+ async _withText(found) {
499
+ 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
+ };
505
+ 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) {
509
+ return [];
466
510
  }
511
+ const { chunkId, text, metadata } = chunks[at];
512
+ return [{ artifactId, chunkId, scope, text, metadata, score }];
513
+ }));
514
+ for (const [artifactId, chunks] of files) {
515
+ if (!(await chunks)) {
516
+ await this._lose(artifactId, this._manifest.artifacts[artifactId]);
517
+ }
518
+ }
519
+ return hits.flat();
520
+ }
521
+ _chunks(ids) {
522
+ return readChunks(this._file(CHUNKS_DIR), ids).catch(() => null);
523
+ }
524
+ async _lose(artifactId, stored) {
525
+ if (this._manifest.artifacts[artifactId] !== stored) {
526
+ return;
467
527
  }
468
- return byId;
528
+ await this._drop(artifactId);
529
+ await this._release();
469
530
  }
470
531
  async _warm() {
471
532
  const index = this._index;
@@ -476,7 +537,7 @@ export class KnowledgeStore {
476
537
  await index.search({ query: probe, k: 1 });
477
538
  }
478
539
  _chunkCount() {
479
- return Object.values(this._manifest.artifacts).reduce((sum, stored) => sum + stored.chunks.length, 0);
540
+ return Object.values(this._manifest.artifacts).reduce((sum, stored) => sum + stored.ids.length, 0);
480
541
  }
481
542
  _file(name) {
482
543
  return path.join(this._dir, name);
@@ -514,11 +575,20 @@ export class KnowledgeStore {
514
575
  await writeManifest(this._file(MANIFEST_FILE), { ...this._manifest, generation });
515
576
  this._manifest.generation = generation;
516
577
  await fs.promises.rm(this._file(snapshotFile(replaced)), { force: true });
578
+ await this._remove(CHUNKS_DIR, this._freed.splice(0));
517
579
  }
518
580
  async _sweep(kept) {
519
581
  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 })));
582
+ await this._remove('.', files.filter((file) => isSnapshotFile(file) && file !== kept));
583
+ }
584
+ async _sweepChunks(saved) {
585
+ const named = new Set(Object.values(saved?.artifacts ?? {}).map((stored) => chunksFile(stored.ids)));
586
+ const files = await fs.promises.readdir(this._file(CHUNKS_DIR)).catch(() => []);
587
+ await this._remove(CHUNKS_DIR, files.filter((file) => !named.has(file)));
588
+ return new Set(files.filter((file) => named.has(file)));
589
+ }
590
+ async _remove(dir, files) {
591
+ await Promise.all(files.map((file) => fs.promises.rm(path.join(this._dir, dir, file), { force: true })));
522
592
  }
523
593
  }
524
594
  function noop() { }
@@ -2,10 +2,6 @@ import { HarnessError } from '../../lib/errors.js';
2
2
  import { retryMemo } from '../../lib/helpers/retry-memo.js';
3
3
  import { PluginRegistry } from '../../lib/plugins/index.js';
4
4
  import { createGenerateMusicTool, createMusicRuntime } from './generate-music.js';
5
- PluginRegistry.requirePeers('music', {
6
- '@qvac/audiogen-ggml': () => import.meta.resolve('@qvac/audiogen-ggml/binding.js'),
7
- '@qvac/decoder-audio': () => import.meta.resolve('@qvac/decoder-audio')
8
- });
9
5
  export { audioDurationSeconds, backendDevice, backendName, CPU_FALLBACK_NOTICE, createGenerateMusicTool, createMusicRuntime, gpuFallback, musicPercentTick, pcmToWav, presentStats } from './generate-music.js';
10
6
  export class Music {
11
7
  name = 'music';
@@ -15,6 +11,10 @@ export class Music {
15
11
  read;
16
12
  _options;
17
13
  constructor(options) {
14
+ PluginRegistry.requirePeers('music', {
15
+ '@qvac/audiogen-ggml': () => import.meta.resolve('@qvac/audiogen-ggml/binding.js'),
16
+ '@qvac/decoder-audio': () => import.meta.resolve('@qvac/decoder-audio')
17
+ });
18
18
  this._options = options;
19
19
  this.read = options?.read;
20
20
  }
@@ -4,11 +4,15 @@ import { PluginRegistry } from '../../lib/plugins/index.js';
4
4
  import { SKILL_STATE } from '../../lib/tools/skills/skill-state-constants.js';
5
5
  import { isObsidianVaultPath, isSandboxedWorkbenchInstall, OBSIDIAN_SKILL_NAME, OBSIDIAN_VAULT_MODE_NOTE, OBSIDIAN_VAULT_PATH_CREDENTIAL_KEY, obsidianCliState, obsidianInstallState } from './readiness.js';
6
6
  import { capOutput, MAX_OUTPUT_CHARS } from '../../lib/tools/exec/runner.js';
7
- import { runObsidianCli } from './cli.js';
8
7
  import { normalizeObsidianCommand, parseObsidianCommand } from './command.js';
9
8
  import { OBSIDIAN_DESKTOP_AGENT_REQUIRED, OBSIDIAN_NO_SHELL_FALLBACK, OBSIDIAN_VAULT_SETUP_REQUIRED } from './guidance.js';
10
- import { executeVaultFsAction } from './vault-fs.js';
9
+ import { retryMemo } from '../../lib/helpers/retry-memo.js';
11
10
  const DESKTOP_PLATFORMS = new Set(['darwin', 'linux', 'win32']);
11
+ const backends = retryMemo(() => Promise.all([import('./vault-fs.js'), import('./cli.js')]).catch((err) => {
12
+ throw new Error(`plugin 'obsidian' could not load its implementation: ${errorMessage(err)}`, {
13
+ cause: err
14
+ });
15
+ }));
12
16
  function credentialRecord(value) {
13
17
  if (typeof value === 'string') {
14
18
  return value ? { token: value } : null;
@@ -27,7 +31,7 @@ function vaultFsResult(stdout, exitCode) {
27
31
  ? { stdout, stderr: '', exitCode: 0 }
28
32
  : { stdout: '', stderr: `${stdout}\n\n${OBSIDIAN_NO_SHELL_FALLBACK}`, exitCode };
29
33
  }
30
- function runVaultFs(vaultPath, { action, args, maxOutputChars }) {
34
+ function runVaultFs(executeVaultFsAction, vaultPath, { action, args, maxOutputChars }) {
31
35
  try {
32
36
  return limitResult(vaultFsResult(executeVaultFsAction(vaultPath, action, args), 0), maxOutputChars);
33
37
  }
@@ -124,11 +128,17 @@ export class ObsidianRoute {
124
128
  }
125
129
  const vaultPath = await resolveVaultPath(this._options.credentialStore, ctx);
126
130
  if (vaultPath) {
127
- return runVaultFs(vaultPath, { action: parsed.action, args: parsed.args, maxOutputChars });
131
+ const [{ executeVaultFsAction }] = await backends();
132
+ return runVaultFs(executeVaultFsAction, vaultPath, {
133
+ action: parsed.action,
134
+ args: parsed.args,
135
+ maxOutputChars
136
+ });
128
137
  }
129
138
  if (isSandboxedWorkbenchInstall(this._options.env ?? process.env)) {
130
139
  return { stdout: '', stderr: OBSIDIAN_VAULT_SETUP_REQUIRED, exitCode: 1 };
131
140
  }
141
+ const [, { runObsidianCli }] = await backends();
132
142
  return runObsidianCli(normalizeObsidianCommand(command), await runtime(), {
133
143
  timeoutMs,
134
144
  maxOutputChars,
@@ -1,11 +1,13 @@
1
1
  import type { HarnessPlugin, PluginSetup } from '../../lib/plugins/index.ts';
2
2
  import { type PythonLanguageOptions } from './language.ts';
3
+ import type { PythonRunResult } from './pyodide.ts';
3
4
  import { closePythonWorker } from './worker/active.ts';
4
5
  import { preloadPythonAddons } from './worker/client.ts';
5
6
  export type { PythonLanguageOptions };
6
- export { runPython, type LoadPyodideFn, type PythonRunResult } from './pyodide.ts';
7
+ export type { LoadPyodideFn, PythonRunResult } from './pyodide.ts';
7
8
  export { planVendoredInstall, vendoredManifest, wheelsDir } from './wheels.ts';
8
9
  export { closePythonWorker };
10
+ export declare function runPython(...args: Parameters<typeof import('./pyodide.ts').runPython>): Promise<PythonRunResult>;
9
11
  export declare class Python implements HarnessPlugin {
10
12
  readonly name = "python";
11
13
  readonly api = 1;
@@ -1,11 +1,14 @@
1
1
  import { PluginRegistry } from '../../lib/plugins/index.js';
2
2
  import { createPythonLanguage } from './language.js';
3
+ import { pyodideModule } from './python-adapter.js';
3
4
  import { closePythonWorker } from './worker/active.js';
4
5
  import { preloadPythonAddons } from './worker/client.js';
5
6
  PluginRegistry.requirePeers('python', { pyodide: () => import.meta.resolve('pyodide') });
6
- export { runPython } from './pyodide.js';
7
7
  export { planVendoredInstall, vendoredManifest, wheelsDir } from './wheels.js';
8
8
  export { closePythonWorker };
9
+ export async function runPython(...args) {
10
+ return (await pyodideModule()).runPython(...args);
11
+ }
9
12
  export class Python {
10
13
  name = 'python';
11
14
  api = PluginRegistry.API_VERSION;
@@ -1,7 +1,8 @@
1
1
  import type { ExecutionAdapter } from '../../lib/contract/exec.ts';
2
2
  import { type ExecInput } from '../../lib/tools/attachments/staging.ts';
3
3
  import { type ExecError } from '../../lib/tools/attachments/output-policy.ts';
4
- import { type LoadPyodideFn } from './pyodide.ts';
4
+ import type { LoadPyodideFn } from './pyodide.ts';
5
+ export declare const pyodideModule: import("../../lib/helpers/retry-memo.ts").RetryMemo<typeof import("./pyodide.ts")>;
5
6
  export declare function pinned(spec: string): string;
6
7
  export declare function pipMessage(targets: readonly string[] | null, { sandbox }?: {
7
8
  sandbox?: boolean | undefined;
@@ -2,12 +2,18 @@ import b4a from 'b4a';
2
2
  import { Policy } from '../../lib/policy/index.js';
3
3
  import { attachOutputs, stageInputs } from '../../lib/tools/attachments/staging.js';
4
4
  import { checkFileName, checkOutputName, MAX_INPUTS, MAX_OUTPUTS } from '../../lib/tools/attachments/output-policy.js';
5
- import { runPython } from './pyodide.js';
5
+ import { errorMessage } from '../../lib/guards.js';
6
+ import { retryMemo } from '../../lib/helpers/retry-memo.js';
6
7
  import { isTranscoder, TRANSCODE_ERROR, VIDEO_TOOLS_ERROR, videoTool } from '../../lib/tools/exec/video-tools.js';
7
8
  import { moduleDistribution } from './distributions.js';
8
9
  import { namedHosts } from './named-hosts.js';
9
10
  import { normalizeDistribution, planVendoredInstall, vendoredSpec } from './wheels.js';
10
11
  import { isPythonLanguage, pipInstallTargets, unwrapPythonSource } from '../../lib/tools/exec/python-source.js';
12
+ export const pyodideModule = retryMemo(() => import('./pyodide.js').catch((err) => {
13
+ throw new Error(`plugin 'python' could not load its implementation: ${errorMessage(err)}`, {
14
+ cause: err
15
+ });
16
+ }));
11
17
  const SHELL_WRAPPER = /^(python3?|py|pip3?)(\s*$|\s+(-[A-Za-z]|['"]|[\w./]))/;
12
18
  const SANDBOX_NO_INSTALL = 'and sandbox mode installs only the packages bundled with this app, which do not include it. Use only what is already installed, or tell the user it is unavailable while sandbox mode is on.';
13
19
  const specName = (spec) => normalizeDistribution(spec.split(/[=<>!~[]/)[0] ?? '');
@@ -462,6 +468,7 @@ export function createPythonAdapter(loadPyodide, network = false) {
462
468
  if (refusal) {
463
469
  return fail(refusal);
464
470
  }
471
+ const { runPython } = await pyodideModule();
465
472
  const result = await runPython(install ? 'pass' : source, {
466
473
  timeoutMs: options.timeoutMs,
467
474
  maxOutputChars: options.maxOutputChars,