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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -1
  3. package/dist-lib/index.js +1 -2
  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.d.ts +3 -2
  10. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +21 -3
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +11 -2
  12. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +4 -0
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
  14. package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
  15. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
  16. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
  17. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  18. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +4 -1
  19. package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
  20. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +11 -0
  21. package/dist-lib/lib/capabilities/completion-engine/round.js +41 -22
  22. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
  23. package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
  24. package/dist-lib/lib/capabilities/tool-failed-note.d.ts +1 -0
  25. package/dist-lib/lib/capabilities/tool-failed-note.js +1 -0
  26. package/dist-lib/lib/capabilities/tool-turns.d.ts +3 -1
  27. package/dist-lib/lib/capabilities/tool-turns.js +8 -1
  28. package/dist-lib/lib/connect.js +4 -2
  29. package/dist-lib/lib/contract/completion.d.ts +2 -1
  30. package/dist-lib/lib/contract/knowledge.d.ts +10 -0
  31. package/dist-lib/lib/fold/index.d.ts +3 -2
  32. package/dist-lib/lib/fold/index.js +7 -6
  33. package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
  34. package/dist-lib/lib/helpers/goal-check.js +89 -7
  35. package/dist-lib/lib/helpers/html-helpers.js +9 -6
  36. package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
  37. package/dist-lib/lib/helpers/input-budget.js +9 -0
  38. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  39. package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
  40. package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
  41. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  42. package/dist-lib/lib/machine/completion/rules.js +14 -5
  43. package/dist-lib/lib/machine/completion/types.d.ts +3 -0
  44. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  45. package/dist-lib/lib/plugins/registry.js +49 -10
  46. package/dist-lib/lib/residency/index.d.ts +1 -1
  47. package/dist-lib/lib/residency/index.js +4 -2
  48. package/dist-lib/lib/serve.js +56 -15
  49. package/dist-lib/lib/tools/files/glob.js +2 -2
  50. package/dist-lib/lib/tools/files/read-file.js +134 -15
  51. package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
  52. package/dist-lib/lib/tools/fs/walk.js +2 -1
  53. package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
  54. package/dist-lib/lib/tools/http-request.js +28 -11
  55. package/dist-lib/lib/tools/office.d.ts +1 -1
  56. package/dist-lib/lib/tools/office.js +34 -12
  57. package/dist-lib/lib/wire.js +23 -3
  58. package/dist-lib/plugins/knowledge/index.js +1 -0
  59. package/dist-lib/plugins/knowledge/manifest.d.ts +29 -0
  60. package/dist-lib/plugins/knowledge/manifest.js +41 -0
  61. package/dist-lib/plugins/knowledge/search-tool.js +8 -8
  62. package/dist-lib/plugins/knowledge/store.d.ts +35 -7
  63. package/dist-lib/plugins/knowledge/store.js +335 -143
  64. package/dist-lib/plugins/mcp/call.js +10 -3
  65. package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
  66. package/dist-lib/plugins/mcp/protocol.js +11 -10
  67. package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
  68. package/dist-lib/plugins/mcp/tool-listing.js +97 -0
  69. package/dist-lib/plugins/music/generate-music.js +2 -2
  70. package/dist-lib/plugins/python/language.js +2 -2
  71. package/dist-lib/plugins/run-report/story.js +4 -1
  72. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  73. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  74. package/dist-lib/schema/harness.js +4 -2
  75. package/dist-lib/spec/hrpc/messages.js +19 -4
  76. package/dist-lib/spec/hyperschema/index.js +19 -4
  77. package/dist-lib/spec/hyperschema/schema.json +12 -1
  78. package/dist-lib/spec/hyperschema/types.d.ts +2 -0
  79. package/package.json +9 -1
@@ -8,6 +8,7 @@ import { bindApi } from '../spec/bind.js';
8
8
  import HRPC from '../spec/hrpc/index.js';
9
9
  import { encode } from '../spec/hrpc/messages.js';
10
10
  import { checkGoal, checkMaxToolRounds } from './capabilities/tool-turns.js';
11
+ import { acceptsInput, inputBytes } from './helpers/input-budget.js';
11
12
  import { isCapability } from './capabilities/invoke.js';
12
13
  import { CUSTOM_TASK_TYPES } from './models/model-catalog.js';
13
14
  import { unsupportedKvCacheDeletion } from './capabilities/kv-cache.js';
@@ -153,11 +154,7 @@ function startPayloadFrom(value) {
153
154
  });
154
155
  }
155
156
  if (isRecord(value.knowledge)) {
156
- const { scopes } = value.knowledge;
157
- if (!Array.isArray(scopes) || !scopes.every((scope) => typeof scope === 'string')) {
158
- throw new TypeError('Invalid knowledge grant');
159
- }
160
- payload.knowledge = { scopes };
157
+ payload.knowledge = knowledgeGrant(value.knowledge);
161
158
  }
162
159
  if (value.planMode === true) {
163
160
  payload.planMode = true;
@@ -461,11 +458,12 @@ export function serveHarness(stream, harness) {
461
458
  }
462
459
  return harness.knowledgeRemove(artifactId);
463
460
  },
464
- knowledgeSearch: async ({ text, scopes, k }) => {
461
+ knowledgeSearch: async ({ text, scopes, k, focus }) => {
465
462
  if (!harness.knowledgeSearch) {
466
463
  throw unsupportedKnowledge();
467
464
  }
468
- return { hits: await harness.knowledgeSearch({ text, scopes, k: k || undefined }) };
465
+ const query = { text, scopes, k: k || undefined, focus: focus?.length ? focus : undefined };
466
+ return { hits: await harness.knowledgeSearch(query) };
469
467
  },
470
468
  knowledgeStatus: async () => {
471
469
  if (!harness.knowledgeStatus) {
@@ -642,6 +640,8 @@ function runFrame(harness, frame, context) {
642
640
  });
643
641
  }
644
642
  function completion(harness) {
643
+ let writeTurn = Promise.resolve();
644
+ const waitForWriteTurn = () => (writeTurn = writeTurn.then(tick));
645
645
  return async function* (duplex) {
646
646
  const events = pushQueue({ highWaterMark: WIRE_HIGH_WATER_MARK });
647
647
  const pending = new Map();
@@ -650,7 +650,19 @@ function completion(harness) {
650
650
  const pendingQuestion = new Map();
651
651
  const pendingDrive = new Map();
652
652
  const pendingRunLog = new Map();
653
- const input = pushQueue();
653
+ const inputQueue = pushQueue();
654
+ let queuedInputCount = 0;
655
+ let queuedInputBytes = 0;
656
+ let inputLimitNotified = false;
657
+ const input = {
658
+ async *[Symbol.asyncIterator]() {
659
+ for await (const item of inputQueue) {
660
+ queuedInputCount--;
661
+ queuedInputBytes -= inputBytes(item);
662
+ yield item;
663
+ }
664
+ }
665
+ };
654
666
  const controller = new AbortController();
655
667
  const rounds = new RoundPort((event) => events.push(event));
656
668
  let calls = 0;
@@ -688,7 +700,7 @@ function completion(harness) {
688
700
  }
689
701
  pendingRunLog.clear();
690
702
  rounds.close();
691
- input.end();
703
+ inputQueue.end();
692
704
  events.end();
693
705
  };
694
706
  duplex.on('close', gone);
@@ -801,11 +813,27 @@ function completion(harness) {
801
813
  return;
802
814
  }
803
815
  if (frame.type === 'steer' || frame.type === 'follow-up') {
804
- void input.push({
816
+ const item = {
805
817
  mode: frame.type,
806
818
  text: frame.messages?.[0]?.content ?? '',
807
819
  id: frame.callId || undefined
808
- });
820
+ };
821
+ const bytes = inputBytes(item);
822
+ if (!acceptsInput(queuedInputCount, queuedInputBytes, item)) {
823
+ if (!inputLimitNotified) {
824
+ inputLimitNotified = true;
825
+ void events.push({
826
+ type: 'input-rejected',
827
+ text: 'Input queue limit exceeded; one or more inputs were rejected'
828
+ });
829
+ }
830
+ }
831
+ else {
832
+ inputLimitNotified = false;
833
+ queuedInputCount++;
834
+ queuedInputBytes += bytes;
835
+ void inputQueue.push(item);
836
+ }
809
837
  return;
810
838
  }
811
839
  if (frame.type === 'run-log-result') {
@@ -1071,7 +1099,7 @@ function completion(harness) {
1071
1099
  await text.flush();
1072
1100
  events.push({ type: 'error', message: errorMessage(err) });
1073
1101
  }
1074
- input.end();
1102
+ inputQueue.end();
1075
1103
  events.push({ type: 'done' });
1076
1104
  HarnessLog.debug('wire end', { produced, frames });
1077
1105
  events.end();
@@ -1082,16 +1110,18 @@ function completion(harness) {
1082
1110
  encode('@harness/completion-event', event);
1083
1111
  }
1084
1112
  catch (err) {
1113
+ await waitForWriteTurn();
1085
1114
  yield { type: 'error', message: `cannot encode ${event.type} event: ${errorMessage(err)}` };
1086
- await tick();
1115
+ await waitForWriteTurn();
1087
1116
  yield { type: 'done' };
1088
- await tick();
1117
+ await waitForWriteTurn();
1089
1118
  gone();
1090
1119
  return;
1091
1120
  }
1121
+ await waitForWriteTurn();
1092
1122
  yield event;
1093
- await tick();
1094
1123
  }
1124
+ await waitForWriteTurn();
1095
1125
  HarnessLog.info('wire handed off');
1096
1126
  };
1097
1127
  }
@@ -1218,3 +1248,14 @@ function downloadStream(harness, req) {
1218
1248
  };
1219
1249
  return stream;
1220
1250
  }
1251
+ function knowledgeGrant({ scopes, focus, k }) {
1252
+ if (!isStrings(scopes) ||
1253
+ (focus !== undefined && !isStrings(focus)) ||
1254
+ (k !== undefined && !(typeof k === 'number' && Number.isSafeInteger(k) && k > 0))) {
1255
+ throw new TypeError('Invalid knowledge grant');
1256
+ }
1257
+ return { scopes, focus, k };
1258
+ }
1259
+ function isStrings(value) {
1260
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
1261
+ }
@@ -51,8 +51,8 @@ export function createGlobTool({ realpath = defaultRealpath, deniedRoots } = {})
51
51
  if (isDeniedPath(file.path, deny) || !(test(rel) || (byName && test(name)))) {
52
52
  continue;
53
53
  }
54
- const entry = await target.root.drive.entry(file.key);
55
- hits.push({ path: shownPath(file.path, anchorOf(ctx)), mtime: entry?.mtime ?? 0 });
54
+ const mtime = file.mtime ?? (await target.root.drive.entry(file.key))?.mtime ?? 0;
55
+ hits.push({ path: shownPath(file.path, anchorOf(ctx)), mtime });
56
56
  }
57
57
  }
58
58
  hits.sort((a, b) => b.mtime - a.mtime);
@@ -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)] : [],