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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -1
  3. package/dist-lib/index.js +0 -1
  4. package/dist-lib/lib/agent/follow.js +9 -2
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +13 -3
  6. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +11 -6
  7. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.d.ts +2 -1
  8. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +19 -11
  9. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +3 -0
  10. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +10 -2
  11. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +3 -0
  12. package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
  13. package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
  14. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
  15. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
  16. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  17. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +2 -0
  18. package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
  19. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -0
  20. package/dist-lib/lib/capabilities/completion-engine/round.js +38 -19
  21. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
  22. package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
  23. package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
  24. package/dist-lib/lib/capabilities/tool-turns.js +1 -0
  25. package/dist-lib/lib/connect.js +4 -2
  26. package/dist-lib/lib/contract/completion.d.ts +2 -1
  27. package/dist-lib/lib/contract/knowledge.d.ts +10 -0
  28. package/dist-lib/lib/fold/index.d.ts +3 -2
  29. package/dist-lib/lib/fold/index.js +7 -6
  30. package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
  31. package/dist-lib/lib/helpers/goal-check.js +89 -7
  32. package/dist-lib/lib/helpers/html-helpers.js +9 -6
  33. package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
  34. package/dist-lib/lib/helpers/input-budget.js +9 -0
  35. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  36. package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
  37. package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
  38. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  39. package/dist-lib/lib/machine/completion/rules.js +14 -5
  40. package/dist-lib/lib/machine/completion/types.d.ts +3 -0
  41. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  42. package/dist-lib/lib/plugins/registry.js +49 -10
  43. package/dist-lib/lib/residency/index.js +2 -0
  44. package/dist-lib/lib/serve.js +56 -15
  45. package/dist-lib/lib/tools/files/glob.js +2 -2
  46. package/dist-lib/lib/tools/files/read-file.js +134 -15
  47. package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
  48. package/dist-lib/lib/tools/fs/walk.js +2 -1
  49. package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
  50. package/dist-lib/lib/tools/http-request.js +28 -11
  51. package/dist-lib/lib/tools/office.d.ts +1 -1
  52. package/dist-lib/lib/tools/office.js +34 -12
  53. package/dist-lib/lib/wire.js +23 -3
  54. package/dist-lib/plugins/knowledge/index.js +1 -0
  55. package/dist-lib/plugins/knowledge/manifest.d.ts +29 -0
  56. package/dist-lib/plugins/knowledge/manifest.js +41 -0
  57. package/dist-lib/plugins/knowledge/search-tool.js +8 -8
  58. package/dist-lib/plugins/knowledge/store.d.ts +35 -7
  59. package/dist-lib/plugins/knowledge/store.js +335 -143
  60. package/dist-lib/plugins/mcp/call.js +10 -3
  61. package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
  62. package/dist-lib/plugins/mcp/protocol.js +11 -10
  63. package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
  64. package/dist-lib/plugins/mcp/tool-listing.js +97 -0
  65. package/dist-lib/plugins/music/generate-music.js +2 -2
  66. package/dist-lib/plugins/python/language.js +2 -2
  67. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  68. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  69. package/dist-lib/schema/harness.js +4 -2
  70. package/dist-lib/spec/hrpc/messages.js +19 -4
  71. package/dist-lib/spec/hyperschema/index.js +19 -4
  72. package/dist-lib/spec/hyperschema/schema.json +12 -1
  73. package/dist-lib/spec/hyperschema/types.d.ts +2 -0
  74. package/package.json +5 -1
@@ -4,15 +4,17 @@ import { documentText, isDocument } from '../fs/document-text.js';
4
4
  import { createLocalRoots } from '../fs/local.js';
5
5
  import { defaultRealpath, resolveKey } from '../fs/scope.js';
6
6
  import { anchorOf, positiveInt, resolveRooted, rootedArgs, rootedPath, stringArg } from '../fs/tool-path.js';
7
+ const MAX_DOCUMENT_BYTES = 8 * 1024 * 1024;
7
8
  const READ_LINES = 400;
8
9
  const READ_CHARS = 20_000;
9
10
  const BINARY_PROBE = 1024;
11
+ const LINE_BYTES = 3 * READ_CHARS + 4;
10
12
  export function createReadFileTool({ realpath = defaultRealpath, deniedRoots } = {}) {
11
13
  return {
12
14
  name: 'read_file',
13
15
  toolset: 'files',
14
16
  description: 'Read one file from the shared folder. Lines come back numbered ("12| text"). For a long file, ' +
15
- 'read a range with startLine/endLine. PDF, Word and PowerPoint files come back as their text. ' +
17
+ 'read a range with startLine/endLine; partial reads may show an unknown total. PDF, Word and PowerPoint files come back as their text. ' +
16
18
  'Use this, not exec, for files in the shared folder.',
17
19
  parameters: {
18
20
  type: 'object',
@@ -45,14 +47,15 @@ export function createReadFileTool({ realpath = defaultRealpath, deniedRoots } =
45
47
  return resolved;
46
48
  }
47
49
  try {
48
- const text = await textOf(resolved, requested);
49
- if (typeof text !== 'string') {
50
- return text;
51
- }
52
- return numbered(text, {
50
+ const range = {
53
51
  start: positiveInt(args.startLine),
54
52
  end: positiveInt(args.endLine)
55
- });
53
+ };
54
+ if (isDocument(resolved.key)) {
55
+ const text = await documentOf(resolved, requested);
56
+ return typeof text === 'string' ? numbered(text, range) : text;
57
+ }
58
+ return await textRange(resolved, requested, range);
56
59
  }
57
60
  catch (err) {
58
61
  return { error: errorMessage(err) };
@@ -60,19 +63,24 @@ export function createReadFileTool({ realpath = defaultRealpath, deniedRoots } =
60
63
  }
61
64
  };
62
65
  }
63
- async function textOf(resolved, requested) {
66
+ async function documentOf(resolved, requested) {
64
67
  const { drive } = resolved.root;
65
- const bytes = (await drive.entry(resolved.key)) ? await drive.get(resolved.key) : null;
68
+ const entry = await drive.entry(resolved.key);
69
+ if (entry?.value.blob && entry.value.blob.byteLength > MAX_DOCUMENT_BYTES) {
70
+ return {
71
+ error: `${requested} is larger than the ${MAX_DOCUMENT_BYTES}-byte document extraction limit`
72
+ };
73
+ }
74
+ const bytes = entry ? await drive.get(resolved.key) : null;
66
75
  if (bytes === null) {
67
76
  return { error: `no such file: ${requested}. Use list_dir or glob to find the right path.` };
68
77
  }
69
- if (isDocument(resolved.key)) {
70
- return documentText(resolved.key, bytes);
71
- }
72
- if (bytes.subarray(0, BINARY_PROBE).includes(0)) {
73
- return { error: `${requested} is a binary file (not text, PDF, Word or PowerPoint)` };
78
+ if (bytes.byteLength > MAX_DOCUMENT_BYTES) {
79
+ return {
80
+ error: `${requested} is larger than the ${MAX_DOCUMENT_BYTES}-byte document extraction limit`
81
+ };
74
82
  }
75
- return b4a.toString(bytes, 'utf8');
83
+ return documentText(resolved.key, bytes);
76
84
  }
77
85
  function numbered(text, { start, end }) {
78
86
  const lines = text.split('\n');
@@ -103,3 +111,114 @@ function numbered(text, { start, end }) {
103
111
  const header = last < total ? `${shown}; continue with startLine ${last + 1}` : shown;
104
112
  return { content: `${header}\n${out.join('\n')}` };
105
113
  }
114
+ async function textRange(resolved, requested, range) {
115
+ const { drive } = resolved.root;
116
+ if (!(await drive.entry(resolved.key))) {
117
+ return { error: `no such file: ${requested}. Use list_dir or glob to find the right path.` };
118
+ }
119
+ const reader = new TextRange(range);
120
+ let probed = 0;
121
+ for await (const chunk of drive.createReadStream(resolved.key)) {
122
+ if (chunk.subarray(0, Math.max(0, BINARY_PROBE - probed)).includes(0)) {
123
+ return { error: `${requested} is a binary file (not text, PDF, Word or PowerPoint)` };
124
+ }
125
+ probed += chunk.length;
126
+ reader.feed(chunk);
127
+ if (reader.stopped) {
128
+ break;
129
+ }
130
+ }
131
+ return { content: reader.finish() };
132
+ }
133
+ class TextRange {
134
+ stopped = false;
135
+ #first;
136
+ #last;
137
+ #out = [];
138
+ #shownFirst;
139
+ #chars = 0;
140
+ #cut = false;
141
+ #full = false;
142
+ #lines = 0;
143
+ #line = emptyLine();
144
+ #previous = emptyLine();
145
+ constructor({ start, end }) {
146
+ this.#first = start ?? 1;
147
+ this.#last = end ?? this.#first + READ_LINES - 1;
148
+ this.#shownFirst = this.#first;
149
+ }
150
+ feed(chunk) {
151
+ let at = 0;
152
+ while (!this.stopped) {
153
+ if (this.#full) {
154
+ this.stopped = at < chunk.length;
155
+ return;
156
+ }
157
+ const newline = chunk.indexOf(0x0a, at);
158
+ this.#append(chunk.subarray(at, newline === -1 ? chunk.length : newline));
159
+ if (newline !== -1 || (this.#line.cut && this.#lines + 1 >= this.#first)) {
160
+ this.#close();
161
+ }
162
+ if (newline === -1) {
163
+ return;
164
+ }
165
+ at = newline + 1;
166
+ }
167
+ }
168
+ finish() {
169
+ const eof = !this.stopped;
170
+ if (eof && this.#line.bytes > 0) {
171
+ this.#close();
172
+ }
173
+ if (eof && this.#out.length === 0 && this.#last >= this.#first) {
174
+ this.#shownFirst = Math.max(this.#lines, 1);
175
+ const row = `${this.#shownFirst}| ${lineText(this.#previous)}`;
176
+ this.#out.push(row.slice(0, READ_CHARS));
177
+ this.#cut = this.#previous.cut || row.length > READ_CHARS;
178
+ }
179
+ const total = eof ? String(Math.max(this.#lines, 1)) : 'unknown';
180
+ const lastShown = this.#shownFirst + this.#out.length - 1;
181
+ const shown = this.#cut
182
+ ? `line ${this.#shownFirst} of ${total}, cut at ${READ_CHARS} characters`
183
+ : `lines ${this.#shownFirst}-${lastShown} of ${total}`;
184
+ const header = !eof || lastShown < this.#lines ? `${shown}; continue with startLine ${lastShown + 1}` : shown;
185
+ return `${header}\n${this.#out.join('\n')}`;
186
+ }
187
+ #append(bytes) {
188
+ const kept = bytes.subarray(0, LINE_BYTES - this.#line.bytes);
189
+ if (kept.length) {
190
+ this.#line.parts.push(kept);
191
+ }
192
+ this.#line.bytes += kept.length;
193
+ this.#line.cut ||= kept.length < bytes.length;
194
+ }
195
+ #close() {
196
+ this.#lines++;
197
+ this.#previous = this.#line;
198
+ this.#line = emptyLine();
199
+ if (this.#lines < this.#first) {
200
+ return;
201
+ }
202
+ const row = `${this.#lines}| ${lineText(this.#previous)}`;
203
+ if (this.#out.length === 0) {
204
+ this.#shownFirst = this.#lines;
205
+ }
206
+ if (this.#chars + row.length > READ_CHARS) {
207
+ this.#cut = this.#out.length === 0;
208
+ if (this.#cut) {
209
+ this.#out.push(row.slice(0, READ_CHARS));
210
+ }
211
+ this.stopped = true;
212
+ return;
213
+ }
214
+ this.#out.push(row);
215
+ this.#chars += row.length + 1;
216
+ this.#full = this.#lines === this.#last;
217
+ }
218
+ }
219
+ function emptyLine() {
220
+ return { parts: [], bytes: 0, cut: false };
221
+ }
222
+ function lineText(line) {
223
+ return b4a.toString(b4a.concat(line.parts), 'utf8');
224
+ }
@@ -6,6 +6,7 @@ export interface WalkedFile {
6
6
  path: string;
7
7
  key: string;
8
8
  byteLength: number;
9
+ mtime?: number;
9
10
  }
10
11
  export interface WalkSummary {
11
12
  truncated: boolean;
@@ -100,7 +100,8 @@ class Walk {
100
100
  this.#onFile({
101
101
  path: displayPath(this.#root, child.key),
102
102
  key: child.key,
103
- byteLength: child.value.blob?.byteLength ?? 0
103
+ byteLength: child.value.blob?.byteLength ?? 0,
104
+ mtime: child.mtime
104
105
  });
105
106
  }
106
107
  }
@@ -63,7 +63,16 @@ function fitString(value, budget) {
63
63
  if (room <= 0) {
64
64
  return ELISION;
65
65
  }
66
- return `${value.slice(0, room)}${ELISION}`;
66
+ let cut = Math.min(value.length, room);
67
+ let size = serializedLength(value.slice(0, cut));
68
+ while (size > room) {
69
+ cut = Math.min(cut - 1, Math.floor((cut * room) / size));
70
+ size = serializedLength(value.slice(0, cut));
71
+ }
72
+ return `${value.slice(0, cut)}${ELISION}`;
73
+ }
74
+ function serializedLength(value) {
75
+ return JSON.stringify(value).length - 2;
67
76
  }
68
77
  function fitArray(value, room) {
69
78
  const kept = [];
@@ -124,7 +133,7 @@ function fit(value, budget) {
124
133
  return fitObject(value, room);
125
134
  }
126
135
  if (typeof value === 'string' && JSON.stringify(value).length > budget) {
127
- return fitString(value, budget);
136
+ return fitString(value, room);
128
137
  }
129
138
  return value;
130
139
  }
@@ -66,6 +66,9 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
66
66
  },
67
67
  async execute(rawArgs, ctx) {
68
68
  const args = rawArgs;
69
+ if (ctx?.signal?.aborted) {
70
+ return { error: 'request cancelled', code: 'cancelled' };
71
+ }
69
72
  let url;
70
73
  try {
71
74
  url = new URL(args.url);
@@ -100,11 +103,21 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
100
103
  if (!auth.ok) {
101
104
  return { error: auth.error };
102
105
  }
103
- const allowList = credentialAllowList?.(ctx);
104
106
  const hosts = Policy.hostsOf(ctx?.policy);
105
107
  const controller = new AbortController();
106
- const timeout = setTimeout(() => controller.abort(undefined), TIMEOUT_MS);
108
+ let timedOut = false;
109
+ const timeout = setTimeout(() => {
110
+ timedOut = true;
111
+ controller.abort(undefined);
112
+ }, TIMEOUT_MS);
113
+ const onCallerAbort = () => controller.abort(undefined);
114
+ ctx?.signal?.addEventListener('abort', onCallerAbort);
115
+ const requestCtx = ctx ? { ...ctx, signal: controller.signal } : undefined;
107
116
  try {
117
+ const allowList = credentialAllowList?.(requestCtx);
118
+ if (controller.signal.aborted) {
119
+ throw new AbortedError();
120
+ }
108
121
  const initialCheck = await resolveOutboundUrl(url, {
109
122
  resolveHost,
110
123
  signal: controller.signal,
@@ -113,7 +126,7 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
113
126
  if (initialCheck.blocked) {
114
127
  return { error: initialCheck.blocked };
115
128
  }
116
- const bearer = await resolveBearerHeader(auth.value, url, credentialStore, allowList, ctx, controller.signal);
129
+ const bearer = await resolveBearerHeader(auth.value, url, credentialStore, allowList, requestCtx, controller.signal);
117
130
  if ('error' in bearer) {
118
131
  return { error: bearer.error };
119
132
  }
@@ -131,6 +144,9 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
131
144
  let validatedAddresses = initialCheck.addresses;
132
145
  let response;
133
146
  for (let redirects = 0;; redirects++) {
147
+ if (controller.signal.aborted) {
148
+ throw new AbortedError();
149
+ }
134
150
  const hopHeaders = { ...headers };
135
151
  delete hopHeaders['Authorization'];
136
152
  if (header) {
@@ -183,7 +199,7 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
183
199
  }
184
200
  currentUrl = nextUrl;
185
201
  validatedAddresses = hopCheck.addresses;
186
- const next = await resolveRedirectBearerHeader(redirectAuth, currentUrl, credentialStore, allowList, ctx, controller.signal);
202
+ const next = await resolveRedirectBearerHeader(redirectAuth, currentUrl, credentialStore, allowList, requestCtx, controller.signal);
187
203
  header = next.header;
188
204
  credentialKey = next.credentialKey;
189
205
  }
@@ -198,16 +214,17 @@ export function createHttpRequestTool({ policyVersion, fetch: fetchImpl, credent
198
214
  }
199
215
  catch (err) {
200
216
  const error = err instanceof Error ? err : new Error(String(err));
201
- const timedOut = error.name === 'AbortError' ||
202
- error.name === 'TimeoutError' ||
203
- error instanceof AbortedError;
204
- return {
205
- error: timedOut ? 'request timed out' : `request failed: ${error.message}`,
206
- code: timedOut ? 'timeout' : 'transport'
207
- };
217
+ if (ctx?.signal?.aborted) {
218
+ return { error: 'request cancelled', code: 'cancelled' };
219
+ }
220
+ if (timedOut || error.name === 'TimeoutError') {
221
+ return { error: 'request timed out', code: 'timeout' };
222
+ }
223
+ return { error: `request failed: ${error.message}`, code: 'transport' };
208
224
  }
209
225
  finally {
210
226
  clearTimeout(timeout);
227
+ ctx?.signal?.removeEventListener('abort', onCallerAbort);
211
228
  }
212
229
  }
213
230
  };
@@ -7,7 +7,7 @@ type Args = Record<string, unknown>;
7
7
  export declare function bodyLines(op: Args): Args;
8
8
  export declare function shapeFor(deck: Deck, op: Args): Args;
9
9
  export declare function sheetFor(book: Workbook, op: Args, created: boolean): Args;
10
- export declare function normalizeArgs(args: Args): Args;
10
+ export declare function normalizeArgs(raw: Args): Args;
11
11
  export declare function revisedName(format: FormatName, fileName: string): string;
12
12
  export declare function createOfficeTools(): ToolDefinition[];
13
13
  export {};
@@ -17,9 +17,9 @@ const WHERE_IDS_ARE = 'copy the id from the [Attached file "…" — attachmentI
17
17
  function isObject(value) {
18
18
  return isRecord(value) && !Array.isArray(value);
19
19
  }
20
- const LOOK_KEY = /colou?r|background|^bg|font|style|theme/i;
21
- function isLook(ops, key, value) {
22
- return value === null || (!(key in ops) && LOOK_KEY.test(key));
20
+ const LOOK_KEY = /colou?r|background|^bg|font|style|theme|^level$/i;
21
+ function isLook(key, value) {
22
+ return value === null || LOOK_KEY.test(key);
23
23
  }
24
24
  const TYPED_BULLET = /^\s*[•◦▪●]\s+/;
25
25
  export function bodyLines(op) {
@@ -131,13 +131,24 @@ const XLSX_FORMAT = {
131
131
  ? 'the workbook has macros, which cannot be saved as .xlsx — add a removeMacros op'
132
132
  : null
133
133
  };
134
- export function normalizeArgs(args) {
135
- if (!Array.isArray(args.ops))
134
+ export function normalizeArgs(raw) {
135
+ const blankId = raw.attachmentId === '' || raw.attachmentId === null;
136
+ const args = blankId && isObject(raw.create) ? withoutKeys(raw, ['attachmentId']) : raw;
137
+ if (!Array.isArray(args.ops)) {
136
138
  return args;
139
+ }
137
140
  const lifted = { ...args };
138
141
  const ops = [];
139
- for (const entry of args.ops) {
140
- const op = typeof entry === 'string' ? { op: entry } : entry;
142
+ const entries = args.ops.flat();
143
+ for (const [i, entry] of entries.entries()) {
144
+ if (entries[i - 1] === 'output' && entry === ':') {
145
+ continue;
146
+ }
147
+ if (entries[i - 2] === 'output' && entries[i - 1] === ':') {
148
+ lifted.output ??= typeof entry === 'string' && FILE_NAME.test(entry) ? entry : undefined;
149
+ continue;
150
+ }
151
+ const op = typeof entry === 'string' ? { op: entry } : opNamedByKey(entry);
141
152
  if (!isObject(op)) {
142
153
  ops.push(op);
143
154
  continue;
@@ -164,6 +175,12 @@ export function normalizeArgs(args) {
164
175
  lifted.ops = lifted.attachmentId === undefined ? ops.map(insertedWhereAsked) : ops;
165
176
  return lifted;
166
177
  }
178
+ function opNamedByKey(entry) {
179
+ if (!isObject(entry) || 'op' in entry)
180
+ return entry;
181
+ const [only, ...more] = Object.entries(entry);
182
+ return only && !more.length && isObject(only[1]) ? { ...only[1], op: only[0] } : entry;
183
+ }
167
184
  function insertedWhereAsked(op) {
168
185
  return isObject(op) && op.op === 'appendParagraphs' && op.at !== undefined
169
186
  ? { ...op, op: 'insertParagraphs' }
@@ -179,7 +196,7 @@ function parseOp(format, op, i) {
179
196
  }
180
197
  const keys = opKeys(spec);
181
198
  const extra = Object.keys(op).filter((key) => key !== 'op' && !keys.includes(key));
182
- const skippable = spec.skipsLooks ? extra.filter((key) => isLook(format.ops, key, op[key])) : [];
199
+ const skippable = spec.skipsLooks ? extra.filter((key) => isLook(key, op[key])) : [];
183
200
  const unknown = extra.filter((key) => !skippable.includes(key));
184
201
  if (!unknown.length) {
185
202
  const kept = Object.fromEntries(Object.entries(op).filter(([key]) => !skippable.includes(key)));
@@ -246,7 +263,7 @@ function parseRequest(format, raw) {
246
263
  return parsed;
247
264
  }
248
265
  const attachmentId = typeof args.attachmentId === 'string' ? args.attachmentId : undefined;
249
- if (attachmentId === undefined && !parsed.ops.length) {
266
+ if (attachmentId === undefined && !parsed.ops.length && !isObject(args.create)) {
250
267
  return `nothing to read: pass the attachmentId of a ${format.noun} (${WHERE_IDS_ARE}), or ops to build one`;
251
268
  }
252
269
  return {
@@ -353,7 +370,7 @@ async function imageInput(op, i, ctx) {
353
370
  if (!isObject(image)) {
354
371
  return { error: `ops[${i}]: image must be { attachmentId } or {}` };
355
372
  }
356
- const id = image.attachmentId;
373
+ const id = image.attachmentId ?? undefined;
357
374
  if (id !== undefined && (typeof id !== 'string' || !id)) {
358
375
  return { error: `ops[${i}]: image.attachmentId must be a non-empty string` };
359
376
  }
@@ -387,8 +404,8 @@ async function withoutMissingUploads(request, ctx) {
387
404
  }
388
405
  function idless(op) {
389
406
  const { image } = op.args;
390
- const noId = image === undefined || image === null || (isObject(image) && image.attachmentId === undefined);
391
- return takesImage(op) && noId;
407
+ const id = isObject(image) ? image.attachmentId : image;
408
+ return takesImage(op) && (id === undefined || id === null);
392
409
  }
393
410
  async function takesUpload(op, ctx) {
394
411
  const id = isObject(op.args.image) ? op.args.image.attachmentId : undefined;
@@ -604,6 +621,11 @@ async function execute(format, args, ctx) {
604
621
  return source;
605
622
  }
606
623
  const { document, fileName } = source;
624
+ if (!request.ops.length && request.attachmentId === undefined) {
625
+ return {
626
+ next: `No ${format.noun} exists yet, so there is nothing to open: make it in one call with create, ops and output.`
627
+ };
628
+ }
607
629
  if (!request.ops.length) {
608
630
  return { document: format.read(document) };
609
631
  }
@@ -140,7 +140,12 @@ function toWirePayload(event) {
140
140
  case 'input-rejected':
141
141
  return { type: 'input-rejected', text: stringField(event.reason) };
142
142
  case 'context':
143
- return { type: 'context', callId: stringField(event.id), payload: event.context };
143
+ return {
144
+ type: 'context',
145
+ callId: stringField(event.id),
146
+ payload: event.context,
147
+ result: event.sources
148
+ };
144
149
  case 'goal':
145
150
  return {
146
151
  type: 'goal',
@@ -280,8 +285,15 @@ function fromWirePayload(event) {
280
285
  return { type: 'input', text: event.text ?? '', id: event.callId || undefined };
281
286
  case 'input-rejected':
282
287
  return { type: 'input-rejected', reason: event.text ?? '' };
283
- case 'context':
284
- return { type: 'context', id: event.callId || undefined, context: objectField(event.payload) };
288
+ case 'context': {
289
+ const sources = Array.isArray(event.result) ? event.result.filter(isKnowledgeSource) : [];
290
+ return {
291
+ type: 'context',
292
+ id: event.callId || undefined,
293
+ context: objectField(event.payload),
294
+ sources: sources.length ? sources : undefined
295
+ };
296
+ }
285
297
  case 'goal': {
286
298
  const { status, turn, checks } = objectField(event.payload);
287
299
  return { type: 'goal', status, turn, text: event.text || undefined, checks };
@@ -421,6 +433,13 @@ function embeddingFrom(wire, rows) {
421
433
  function metadataOf(value) {
422
434
  return isRecord(value) ? value : undefined;
423
435
  }
436
+ function isKnowledgeSource(value) {
437
+ return (isRecord(value) &&
438
+ typeof value.artifactId === 'string' &&
439
+ typeof value.chunkId === 'string' &&
440
+ typeof value.score === 'number' &&
441
+ (value.metadata === undefined || isRecord(value.metadata)));
442
+ }
424
443
  export function toKnowledgeUpsertWire(artifact) {
425
444
  return {
426
445
  artifactId: artifact.artifactId,
@@ -456,6 +475,7 @@ export function fromKnowledgeHitWire({ metadata, ...hit }) {
456
475
  export function fromKnowledgeStatusWire(wire) {
457
476
  return {
458
477
  ...wire,
478
+ pending: wire.pending ?? 0,
459
479
  artifacts: wire.artifacts.map((artifact) => ({
460
480
  ...artifact,
461
481
  version: artifact.version || undefined
@@ -38,6 +38,7 @@ export class Knowledge {
38
38
  minScore: config.minScore,
39
39
  embed: ctx.service('embed')
40
40
  });
41
+ store.start();
41
42
  return {
42
43
  services: { knowledge: store },
43
44
  tools: config.tool ? [knowledgeSearchTool(store)] : [],
@@ -0,0 +1,29 @@
1
+ export declare const MANIFEST_FILE = "knowledge.json";
2
+ export interface StoredChunk {
3
+ id: string;
4
+ chunkId: string;
5
+ text: string;
6
+ metadata?: Record<string, unknown>;
7
+ }
8
+ export interface StoredArtifact {
9
+ version?: string;
10
+ scope: string;
11
+ seq: number;
12
+ pending?: boolean;
13
+ chunks: StoredChunk[];
14
+ }
15
+ export interface Manifest {
16
+ model: string;
17
+ dimensions: number;
18
+ nextId: number;
19
+ seq: number;
20
+ generation?: number;
21
+ artifacts: Record<string, StoredArtifact>;
22
+ }
23
+ export declare function emptyManifest(model: string): Manifest;
24
+ export declare function snapshotFile(generation: number | undefined): string;
25
+ export declare function isSnapshotFile(file: string): boolean;
26
+ export declare function chunkIds(stored: StoredArtifact): string[];
27
+ export declare function indexedChunks(manifest: Manifest): number;
28
+ export declare function readManifest(file: string): Promise<Manifest | null>;
29
+ export declare function writeManifest(file: string, manifest: Manifest): Promise<void>;
@@ -0,0 +1,41 @@
1
+ import fs from 'fs';
2
+ import { isRecord } from '../../lib/guards.js';
3
+ export const MANIFEST_FILE = 'knowledge.json';
4
+ const SNAPSHOT = /^knowledge(\.\d+)?\.qvi$/;
5
+ export function emptyManifest(model) {
6
+ return { model, dimensions: 0, nextId: 1, seq: 0, artifacts: {} };
7
+ }
8
+ export function snapshotFile(generation) {
9
+ return generation === undefined ? 'knowledge.qvi' : `knowledge.${generation}.qvi`;
10
+ }
11
+ export function isSnapshotFile(file) {
12
+ return SNAPSHOT.test(file);
13
+ }
14
+ export function chunkIds(stored) {
15
+ return stored.chunks.map((chunk) => chunk.id);
16
+ }
17
+ export function indexedChunks(manifest) {
18
+ return Object.values(manifest.artifacts).reduce((sum, stored) => sum + (stored.pending ? 0 : stored.chunks.length), 0);
19
+ }
20
+ export async function readManifest(file) {
21
+ try {
22
+ const value = JSON.parse(await fs.promises.readFile(file, 'utf8'));
23
+ return isManifest(value) ? value : null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ export async function writeManifest(file, manifest) {
30
+ await fs.promises.writeFile(`${file}.tmp`, JSON.stringify(manifest));
31
+ await fs.promises.rename(`${file}.tmp`, file);
32
+ }
33
+ function isManifest(value) {
34
+ return (isRecord(value) &&
35
+ typeof value.model === 'string' &&
36
+ typeof value.dimensions === 'number' &&
37
+ typeof value.nextId === 'number' &&
38
+ typeof value.seq === 'number' &&
39
+ (value.generation === undefined || typeof value.generation === 'number') &&
40
+ isRecord(value.artifacts));
41
+ }
@@ -23,16 +23,16 @@ export function knowledgeSearchTool(knowledge) {
23
23
  return { error: 'query must be a non-empty string' };
24
24
  }
25
25
  const scopes = ctx?.knowledge?.scopes ?? [];
26
+ const k = ctx?.knowledge?.k;
26
27
  const hits = scopes.length
27
- ? await knowledge.search({ text: query, scopes, signal: ctx?.signal })
28
+ ? await knowledge.search({ text: query, scopes, k, signal: ctx?.signal })
28
29
  : [];
29
- return {
30
- results: hits.map(({ artifactId, chunkId, text }) => ({
31
- source: artifactId,
32
- chunkId,
33
- text
34
- }))
35
- };
30
+ return { results: hits.map(toolResult) };
36
31
  }
37
32
  };
38
33
  }
34
+ function toolResult({ artifactId, chunkId, text, score, metadata }) {
35
+ const title = typeof metadata?.title === 'string' ? metadata.title : undefined;
36
+ const page = typeof metadata?.page === 'number' ? metadata.page : undefined;
37
+ return { source: artifactId, title, page, chunkId, text, score };
38
+ }
@@ -16,27 +16,55 @@ export declare class KnowledgeStore implements KnowledgeService {
16
16
  private _manifest;
17
17
  private _index;
18
18
  private _opened;
19
- private _lane;
19
+ private _writes;
20
+ private _lock;
21
+ private _dirty;
22
+ private _persisting;
23
+ private _refilling;
24
+ private _asking;
25
+ private _answered;
26
+ private _closed;
20
27
  constructor({ dir, model, maxChunks, minScore, embed }: KnowledgeStoreOptions);
28
+ start(): void;
21
29
  upsert(artifact: KnowledgeArtifact): Promise<KnowledgeUpsertResult>;
22
30
  remove(artifactId: string): Promise<KnowledgeRemoved>;
23
31
  search(query: KnowledgeQuery): Promise<KnowledgeHit[]>;
32
+ private _answer;
24
33
  status(): Promise<KnowledgeStatus>;
25
34
  close(): Promise<void>;
26
- private _serial;
35
+ private _quiet;
36
+ private _ordered;
37
+ private _exclusive;
38
+ private _locked;
39
+ private _ready;
27
40
  private _recovering;
28
41
  private _open;
29
- private _rebuild;
30
- private _unload;
31
- private _upsert;
32
- private _add;
33
- private _embedChunks;
42
+ private _load;
43
+ private _reload;
44
+ private _loadCurrent;
45
+ private _markPending;
46
+ private _reset;
47
+ private _prepare;
48
+ private _embedTexts;
49
+ private _apply;
34
50
  private _indexFor;
35
51
  private _drop;
36
52
  private _evict;
53
+ private _release;
54
+ private _refill;
55
+ private _refillAll;
56
+ private _refillOne;
57
+ private _nextPending;
58
+ private _fill;
59
+ private _searchable;
37
60
  private _search;
61
+ private _ranked;
38
62
  private _chunksById;
63
+ private _warm;
39
64
  private _chunkCount;
40
65
  private _file;
66
+ private _changed;
67
+ private _writeOut;
41
68
  private _persist;
69
+ private _sweep;
42
70
  }