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

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 (92) 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/loading-skill.js +1 -1
  7. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +21 -12
  8. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.d.ts +2 -1
  9. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +19 -11
  10. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +2 -2
  11. package/dist-lib/lib/capabilities/completion-engine/actors/stream.d.ts +1 -1
  12. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +11 -0
  13. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +16 -4
  14. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +8 -2
  15. package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
  16. package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
  17. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
  18. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
  19. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  20. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +2 -0
  21. package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
  22. package/dist-lib/lib/capabilities/completion-engine/ports.js +1 -1
  23. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -0
  24. package/dist-lib/lib/capabilities/completion-engine/round.js +40 -20
  25. package/dist-lib/lib/capabilities/completion-engine/session.d.ts +3 -3
  26. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
  27. package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
  28. package/dist-lib/lib/capabilities/prompt-prefix.d.ts +2 -0
  29. package/dist-lib/lib/capabilities/prompt-prefix.js +8 -0
  30. package/dist-lib/lib/capabilities/sdk-tool.d.ts +1 -1
  31. package/dist-lib/lib/capabilities/sdk-tool.js +17 -2
  32. package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
  33. package/dist-lib/lib/capabilities/tool-turns.js +1 -0
  34. package/dist-lib/lib/capabilities/usage-breakdown.d.ts +1 -0
  35. package/dist-lib/lib/capabilities/usage-breakdown.js +4 -1
  36. package/dist-lib/lib/connect.js +4 -2
  37. package/dist-lib/lib/contract/completion.d.ts +2 -1
  38. package/dist-lib/lib/contract/knowledge.d.ts +10 -0
  39. package/dist-lib/lib/fold/index.d.ts +3 -2
  40. package/dist-lib/lib/fold/index.js +7 -6
  41. package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
  42. package/dist-lib/lib/helpers/goal-check.js +89 -7
  43. package/dist-lib/lib/helpers/html-helpers.js +9 -6
  44. package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
  45. package/dist-lib/lib/helpers/input-budget.js +9 -0
  46. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  47. package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
  48. package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
  49. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  50. package/dist-lib/lib/machine/completion/rules.js +14 -5
  51. package/dist-lib/lib/machine/completion/types.d.ts +3 -0
  52. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  53. package/dist-lib/lib/plugins/registry.js +49 -10
  54. package/dist-lib/lib/residency/index.js +2 -0
  55. package/dist-lib/lib/serve.js +56 -15
  56. package/dist-lib/lib/tools/files/glob.js +2 -2
  57. package/dist-lib/lib/tools/files/read-file.js +134 -15
  58. package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
  59. package/dist-lib/lib/tools/fs/walk.js +2 -1
  60. package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
  61. package/dist-lib/lib/tools/http-request.js +28 -11
  62. package/dist-lib/lib/tools/office.d.ts +1 -1
  63. package/dist-lib/lib/tools/office.js +34 -12
  64. package/dist-lib/lib/wire.js +23 -3
  65. package/dist-lib/plugins/knowledge/index.d.ts +3 -0
  66. package/dist-lib/plugins/knowledge/index.js +5 -0
  67. package/dist-lib/plugins/knowledge/manifest.d.ts +53 -0
  68. package/dist-lib/plugins/knowledge/manifest.js +86 -0
  69. package/dist-lib/plugins/knowledge/search-tool.js +8 -8
  70. package/dist-lib/plugins/knowledge/store.d.ts +45 -8
  71. package/dist-lib/plugins/knowledge/store.js +428 -166
  72. package/dist-lib/plugins/mcp/call.js +10 -3
  73. package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
  74. package/dist-lib/plugins/mcp/protocol.js +11 -10
  75. package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
  76. package/dist-lib/plugins/mcp/tool-listing.js +97 -0
  77. package/dist-lib/plugins/music/generate-music.js +2 -2
  78. package/dist-lib/plugins/obsidian/index.js +14 -4
  79. package/dist-lib/plugins/python/index.d.ts +3 -1
  80. package/dist-lib/plugins/python/index.js +4 -1
  81. package/dist-lib/plugins/python/language.js +2 -2
  82. package/dist-lib/plugins/python/python-adapter.d.ts +2 -1
  83. package/dist-lib/plugins/python/python-adapter.js +8 -1
  84. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  85. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  86. package/dist-lib/schema/harness.js +4 -2
  87. package/dist-lib/spec/hrpc/messages.js +19 -4
  88. package/dist-lib/spec/hyperschema/index.js +19 -4
  89. package/dist-lib/spec/hyperschema/schema.json +12 -1
  90. package/dist-lib/spec/hyperschema/types.d.ts +2 -0
  91. package/package.json +28 -19
  92. package/scripts/addon-externals.cjs +4 -1
@@ -344,8 +344,16 @@ export class PluginRegistry {
344
344
  }
345
345
  };
346
346
  }
347
- unload() {
348
- return Promise.allSettled(this._held.map(async (setup) => setup.unload?.()));
347
+ async unload() {
348
+ const setups = [...this._held];
349
+ const outcomes = await Promise.allSettled(setups.map((setup) => setup.unload?.()));
350
+ outcomes.forEach((outcome, index) => {
351
+ if (outcome.status === 'fulfilled' &&
352
+ !this._loaded.some((loaded) => loaded.setup === setups[index])) {
353
+ this._forget(setups[index]);
354
+ }
355
+ });
356
+ return outcomes;
349
357
  }
350
358
  unloadIdle() {
351
359
  return Promise.allSettled(this._held.map(async (setup) => setup.unloadIdle?.()));
@@ -445,27 +453,58 @@ export class PluginRegistry {
445
453
  await this._runtime.add(this._plugin(plugin, ++this._revision, place));
446
454
  }
447
455
  catch (error) {
448
- await Promise.allSettled(this._held.splice(setups).map(async (setup) => setup.unload?.()));
449
- throw error;
456
+ const acquired = this._held.slice(setups);
457
+ const outcomes = await Promise.allSettled(acquired.map((setup) => setup.unload?.()));
458
+ const failures = [error];
459
+ outcomes.forEach((outcome, index) => {
460
+ if (outcome.status === 'fulfilled') {
461
+ this._forget(acquired[index]);
462
+ }
463
+ else {
464
+ failures.push(outcome.reason);
465
+ }
466
+ });
467
+ throw failures.length === 1
468
+ ? error
469
+ : new AggregateError(failures, 'Plugin setup and model cleanup failed', { cause: error });
450
470
  }
451
471
  }
452
472
  async _drop(name) {
453
473
  const index = this._loaded.findIndex((loaded) => loaded.plugin.name === name);
454
474
  const [{ plugin, setup }] = this._loaded.splice(index, 1);
455
- this._held.splice(this._held.indexOf(setup), 1);
456
475
  const errors = this._cleanupErrors.length;
476
+ const failures = [];
457
477
  try {
458
478
  await this._runtime.remove(name);
459
479
  }
460
- finally {
461
- this._cleanupErrors.length = errors;
462
- for (const service of plugin.provides ?? []) {
463
- this._services.delete(service);
464
- }
480
+ catch (error) {
481
+ failures.push(error);
482
+ }
483
+ this._cleanupErrors.length = errors;
484
+ for (const service of plugin.provides ?? []) {
485
+ this._services.delete(service);
486
+ }
487
+ try {
465
488
  await setup.unload?.();
489
+ this._forget(setup);
490
+ }
491
+ catch (error) {
492
+ failures.push(error);
493
+ }
494
+ if (failures.length === 1) {
495
+ throw failures[0];
496
+ }
497
+ if (failures.length > 1) {
498
+ throw new AggregateError(failures, `Plugin '${name}' removal and model cleanup failed`);
466
499
  }
467
500
  return index;
468
501
  }
502
+ _forget(setup) {
503
+ const index = this._held.indexOf(setup);
504
+ if (index !== -1) {
505
+ this._held.splice(index, 1);
506
+ }
507
+ }
469
508
  _check(plugin, replacing) {
470
509
  const others = this._loaded
471
510
  .map((loaded) => loaded.plugin)
@@ -1,6 +1,7 @@
1
1
  import ScopeLock from 'scope-lock';
2
2
  import { HarnessError } from '../errors.js';
3
3
  import { errorMessage, isRecord } from '../guards.js';
4
+ import { androidCpuPlacement } from '../hardware/cpu-placement.js';
4
5
  import { AbortedError, raceAbort } from '../helpers/race-abort.js';
5
6
  import { HarnessLog } from '../log.js';
6
7
  import { ContextChoice as ContextClimb } from '../models/context-choice.js';
@@ -259,6 +260,7 @@ export class Residency {
259
260
  slots: this._slots,
260
261
  mainGpu: resolveMainGpu,
261
262
  openclCacheDir,
263
+ cpuPlacement: androidCpuPlacement,
262
264
  contextFor: (key) => this._contexts.chosen(key) ?? this.fit.chosen(key),
263
265
  slotsFor: (key) => this.fit.chosenSlots(key)
264
266
  };
@@ -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 {};