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

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 (44) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist-lib/index.d.ts +1 -0
  3. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +2 -0
  4. package/dist-lib/lib/capabilities/completion-engine/engine.js +23 -39
  5. package/dist-lib/lib/contract/completion.d.ts +3 -0
  6. package/dist-lib/lib/contract/models.d.ts +1 -1
  7. package/dist-lib/lib/contract/ocr.d.ts +9 -0
  8. package/dist-lib/lib/contract/ocr.js +1 -0
  9. package/dist-lib/lib/models/gpu-selection.d.ts +6 -1
  10. package/dist-lib/lib/models/gpu-selection.js +29 -5
  11. package/dist-lib/lib/plugins/registry.d.ts +2 -0
  12. package/dist-lib/lib/serve.js +5 -34
  13. package/dist-lib/lib/spawn.d.ts +1 -0
  14. package/dist-lib/lib/tools/files/read-file.js +3 -3
  15. package/dist-lib/lib/tools/fs/document-text.d.ts +7 -1
  16. package/dist-lib/lib/tools/fs/document-text.js +9 -2
  17. package/dist-lib/lib/tools/operations/builders.d.ts +4 -3
  18. package/dist-lib/lib/tools/operations/builders.js +41 -3
  19. package/dist-lib/lib/tools/operations/calendar-range.d.ts +16 -0
  20. package/dist-lib/lib/tools/operations/calendar-range.js +40 -0
  21. package/dist-lib/lib/tools/operations/compile.js +4 -2
  22. package/dist-lib/lib/tools/operations/manifest.d.ts +4 -0
  23. package/dist-lib/lib/tools/pdf/build.d.ts +11 -1
  24. package/dist-lib/lib/tools/pdf/build.js +52 -16
  25. package/dist-lib/lib/tools/pdf/recognize.d.ts +13 -0
  26. package/dist-lib/lib/tools/pdf/recognize.js +58 -0
  27. package/dist-lib/lib/tools/pdf.js +18 -4
  28. package/dist-lib/plugins/ocr/bmp.d.ts +2 -0
  29. package/dist-lib/plugins/ocr/bmp.js +27 -0
  30. package/dist-lib/plugins/ocr/index.d.ts +12 -0
  31. package/dist-lib/plugins/ocr/index.js +18 -0
  32. package/dist-lib/plugins/ocr/ocr-runtime.d.ts +23 -0
  33. package/dist-lib/plugins/ocr/ocr-runtime.js +82 -0
  34. package/dist-lib/plugins/ocr/reading-order.d.ts +5 -0
  35. package/dist-lib/plugins/ocr/reading-order.js +71 -0
  36. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  37. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  38. package/package.json +10 -1
  39. package/scripts/addon-externals.cjs +3 -0
  40. package/worker/harness-sidecar.mjs +5 -0
  41. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +0 -20
  42. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +0 -110
  43. package/dist-lib/lib/helpers/input-budget.d.ts +0 -8
  44. package/dist-lib/lib/helpers/input-budget.js +0 -9
package/CHANGELOG.md CHANGED
@@ -21,6 +21,16 @@ breaking change is listed under Changed and Removed.
21
21
 
22
22
  ### Added
23
23
 
24
+ - A scanned PDF page is read by OCR. The `ocr` plugin
25
+ (`@qvac/harness/plugins/ocr`) runs DocTR over the SDK's `ggml-ocr` as one
26
+ pooled model, unloaded when idle; `pdf` and `read_file` use it for a page with
27
+ an image and no text layer, and the reply notes the page was read by OCR. On
28
+ by default; `pluginOptions.ocr: false` leaves it out for a host that shows
29
+ scanned pages to the model as images. See
30
+ [plugins/ocr/README.md](plugins/ocr/README.md) and
31
+ [the decision record](docs/decisions/2026-11-03-a-scanned-pdf-page-is-read-by-ocr.md).
32
+ (#768)
33
+
24
34
  - `isLoading` covers image and music models, and a reply waiting for room. An
25
35
  image or music row reads `true` from the request, through any wait for a
26
36
  download or for room, until the model is resident or the load fails, and the
@@ -1177,6 +1187,18 @@ breaking change is listed under Changed and Removed.
1177
1187
 
1178
1188
  ### Fixed
1179
1189
 
1190
+ - Calendar reads build their own query: validated arguments, encoded dates
1191
+ and timezone offsets, and a local day range resolved from the turn's clock
1192
+ that holds across pages and DST, so "today" and "tomorrow" no longer fail
1193
+ and get explained as a credential problem. (#770)
1194
+ - On Linux the NVIDIA card is pinned as `main-gpu` only when another GPU could
1195
+ take the load. A host whose NVIDIA GPU is the only one, such as a DGX Spark
1196
+ or a Jetson, registers it as integrated and was loading on the CPU. (#786)
1197
+ - Restore the completion output queue and pending-input handling from before #684.
1198
+ Output events retain their original boundaries, with no mailbox chunking,
1199
+ coalescing, or count/byte limits. Pending steer/follow-up inputs no longer have
1200
+ admission limits in the engine or transport. Unread output and pending input
1201
+ remain unbounded in memory.
1180
1202
  - `tools/list` through `mcp_call` comes back as a line per tool, with each
1181
1203
  argument's type and allowed values, and `params.names` gives the tools named
1182
1204
  whole. Asana's 52 tools were 148 KB, so the model saw 5 of them cut or waited
@@ -44,6 +44,7 @@ export type { ModelSourceFile, ModelSourcePreview, ModelSourceRefusal, PreviewMo
44
44
  export type { ModelFitBasis, ModelFitEvidence, ModelFitVerdict } from './lib/models/model-fit.ts';
45
45
  export * from './lib/capabilities/download.ts';
46
46
  export type { EmbedContext } from './lib/capabilities/embed.ts';
47
+ export type { OcrImage, OcrService } from './lib/contract/ocr.ts';
47
48
  export type { SpeakContext, SpeakResult, SpeakStreamContext, SpeechService, TranscribeContext } from './lib/contract/speech.ts';
48
49
  export type { EmbedDevice } from './lib/models/embed-config.ts';
49
50
  export type { MemoryBudget } from './lib/hardware/memory-budget.ts';
@@ -21,6 +21,7 @@ export function resolvedCall(session, call) {
21
21
  export function toolContext({ deps, context, name }) {
22
22
  const { args, session, commitFacts } = deps;
23
23
  return {
24
+ currentTime: args.messages.findLast((turn) => turn.role === 'user')?.sentAt || session.startedAt,
24
25
  ...session.toolContext(session.turnImages, context.metrics.ctxSize ?? args.ctxSize, args.signal),
25
26
  skills: context.activated.filter((skill) => Agent.skillIsActive(skill, session.activation) &&
26
27
  !unreadySkillState(skill, args.skillCatalog ?? [])),
@@ -32,6 +33,7 @@ export function toolContext({ deps, context, name }) {
32
33
  policy: session.access,
33
34
  toolNames: session.enabled.map((tool) => tool.name),
34
35
  knowledge: args.knowledge,
36
+ ocr: deps.services?.ocr,
35
37
  planMode: context.planMode,
36
38
  spill: session.enabled.some((tool) => tool.name === 'read_file')
37
39
  ? runSpill(session.runId)
@@ -9,8 +9,6 @@ import { createCompletionActors, createInvokeTracker } from './actors.js';
9
9
  import { replayFinalRound, replaySuccessOutput } from './replay-output.js';
10
10
  import { AbortedError, rehydrateError, tagError } from '../../helpers/engine-error.js';
11
11
  import { turnText } from './turns.js';
12
- import { EventMailbox } from './event-mailbox.js';
13
- import { acceptsInput, inputBytes } from '../../helpers/input-budget.js';
14
12
  import { CompletionMachine } from '../../machine/index.js';
15
13
  function readRestoredSnapshot(value) {
16
14
  if (!isRecord(value) || Array.isArray(value))
@@ -115,7 +113,7 @@ export async function* runEngine(run, options = {}) {
115
113
  yield started(run);
116
114
  const invokes = createInvokeTracker();
117
115
  const boot = RunLog.boundaryBoot(journal);
118
- const mailbox = new EventMailbox();
116
+ const mailbox = createEventMailbox();
119
117
  const { ports, context } = await run.start({
120
118
  operations: createOperationPort(journal),
121
119
  invokes,
@@ -151,6 +149,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
151
149
  const pausedMs = run.resume && journal.snapshotSavedAt !== undefined
152
150
  ? Math.max(0, now() - journal.snapshotSavedAt)
153
151
  : 0;
152
+ const { queue } = mailbox;
154
153
  let detached = false;
155
154
  const detach = () => {
156
155
  detached = true;
@@ -165,17 +164,14 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
165
164
  wakeVersion++;
166
165
  wake();
167
166
  };
168
- let pause = () => { };
169
- let inputLimitNotified = false;
170
167
  mailbox.notify = notify;
171
- mailbox.onOverflow = () => queueMicrotask(pause);
172
168
  const { actor, persistence } = await RunLog.createPersistedActor(journal, machine, notify, now);
173
169
  actor.on('*', (event) => {
174
- mailbox.push(event);
170
+ queue.push(event);
175
171
  notify();
176
172
  });
177
173
  actor.subscribe({ next: notify, error: notify });
178
- pause = () => {
174
+ const pause = () => {
179
175
  if (actor.getSnapshot().status === 'active') {
180
176
  actor.send({ type: 'PAUSE' });
181
177
  }
@@ -193,30 +189,11 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
193
189
  return pumping;
194
190
  }
195
191
  if ('reason' in item) {
196
- mailbox.push({ type: 'input-rejected', runId, reason: item.reason });
192
+ queue.push({ type: 'input-rejected', runId, reason: item.reason });
197
193
  notify();
198
194
  }
199
195
  else {
200
- const pending = [
201
- ...actor.getSnapshot().context.steering,
202
- ...actor.getSnapshot().context.followUps
203
- ];
204
- const bytes = pending.reduce((total, queued) => total + inputBytes(queued), 0);
205
- if (!acceptsInput(pending.length, bytes, item)) {
206
- if (!inputLimitNotified) {
207
- inputLimitNotified = true;
208
- mailbox.push({
209
- type: 'input-rejected',
210
- runId,
211
- reason: 'Pending input limit exceeded; one or more inputs were rejected'
212
- });
213
- notify();
214
- }
215
- }
216
- else {
217
- inputLimitNotified = false;
218
- actor.send(inputMessage(item));
219
- }
196
+ actor.send(inputMessage(item));
220
197
  }
221
198
  return pumping;
222
199
  }).catch(noop);
@@ -248,11 +225,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
248
225
  if (journal.hasPendingFlush()) {
249
226
  await persistence.flush();
250
227
  }
251
- yield* drainQueue(mailbox);
252
- if (mailbox.failure) {
253
- const snapshot = actor.getSnapshot();
254
- return { status: 'error', snapshot, error: mailbox.failure };
255
- }
228
+ yield* drainQueue(queue);
256
229
  if (isActiveIdle(actor.getSnapshot()) && !signal?.aborted) {
257
230
  actor.send({ type: 'START' });
258
231
  }
@@ -268,7 +241,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
268
241
  ? await drainSettling({ actor, persistence, durable, detach })
269
242
  : undefined;
270
243
  if (settlingResult) {
271
- yield* drainQueue(mailbox);
244
+ yield* drainQueue(queue);
272
245
  return settlingResult;
273
246
  }
274
247
  if (isSettling) {
@@ -282,12 +255,12 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
282
255
  durable,
283
256
  detach,
284
257
  journal,
285
- queue: mailbox,
258
+ queue,
286
259
  runId
287
260
  });
288
261
  }
289
262
  const observedWakeVersion = wakeVersion;
290
- if (mailbox.size) {
263
+ if (queue.length) {
291
264
  continue;
292
265
  }
293
266
  await new Promise((resolve) => {
@@ -298,7 +271,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
298
271
  });
299
272
  }
300
273
  await persistence.flush();
301
- yield* drainQueue(mailbox);
274
+ yield* drainQueue(queue);
302
275
  return { status: 'done', snapshot: actor.getSnapshot() };
303
276
  }
304
277
  finally {
@@ -419,13 +392,24 @@ function settling(snapshot) {
419
392
  return value === 'pausing';
420
393
  }
421
394
  function* drainQueue(queue) {
422
- while (queue.size) {
395
+ while (queue.length) {
423
396
  const event = queue.shift();
424
397
  if (event) {
425
398
  yield event;
426
399
  }
427
400
  }
428
401
  }
402
+ function createEventMailbox() {
403
+ const mailbox = {
404
+ queue: [],
405
+ notify() { },
406
+ emit(event) {
407
+ mailbox.queue.push(event);
408
+ mailbox.notify();
409
+ }
410
+ };
411
+ return mailbox;
412
+ }
429
413
  function createOperationPort(journal) {
430
414
  return Object.freeze({
431
415
  flush: () => journal.flush(),
@@ -7,6 +7,7 @@ import type { DriveRoot } from '../tools/fs/scope.ts';
7
7
  import type { CliValidator } from '../tools/skills/cli-schema-types.ts';
8
8
  import type { UsageBreakdown } from '../capabilities/usage-breakdown.ts';
9
9
  import type { KnowledgeGrant, KnowledgeSource } from './knowledge.ts';
10
+ import type { OcrService } from './ocr.ts';
10
11
  import type { AccessPolicy, CompiledPolicy } from './policy.ts';
11
12
  import type { GoalStatus, HistoryToolCall, HookRejection, Message, ResourceDescriptor, RoundSpeed, RunBackendUse, RunBudget, RunLifecycleEvent, RunOutcome, ToolActivityEvent, ToolCallDisplay, ToolDecision, ToolEffect, ToolSpeed, TrustedSource, TrustedSourceFacts, TurnContext } from './run.ts';
12
13
  export type { CliValidator, DriveRoot, LlmGenerationParams };
@@ -134,6 +135,7 @@ export interface ToolSpill {
134
135
  sink(stream: string): SpillSink;
135
136
  }
136
137
  export interface ToolExecuteContext {
138
+ currentTime?: number | undefined;
137
139
  agentId?: string | null | undefined;
138
140
  skills?: readonly string[] | undefined;
139
141
  skillsLoadedThisTurn?: readonly string[] | undefined;
@@ -162,6 +164,7 @@ export interface ToolExecuteContext {
162
164
  approval?: ToolDecision | undefined;
163
165
  fetch?: ToolFetch | undefined;
164
166
  knowledge?: KnowledgeGrant | undefined;
167
+ ocr?: OcrService | undefined;
165
168
  spill?: ToolSpill | undefined;
166
169
  planMode?: boolean | undefined;
167
170
  callTool?: CallTool | undefined;
@@ -24,7 +24,7 @@ export interface BorrowedModel {
24
24
  release(): void;
25
25
  }
26
26
  export interface ResidentPoolSpec {
27
- addon: 'tts' | 'parakeet';
27
+ addon: 'tts' | 'parakeet' | 'ocr';
28
28
  modelType: PendingLoad['modelType'];
29
29
  modelConfig?: Record<string, unknown>;
30
30
  modelConfigFor?: (modelSrc: ModelSrc) => Readonly<Record<string, unknown>> | undefined;
@@ -0,0 +1,9 @@
1
+ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ export interface OcrImage {
3
+ readonly width: number;
4
+ readonly height: number;
5
+ readonly data: Uint8Array;
6
+ }
7
+ export interface OcrService {
8
+ read(image: OcrImage, signal?: BareAbortSignal): Promise<string>;
9
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,3 +1,8 @@
1
1
  export type MainGpuProbe = () => Promise<string | undefined>;
2
- export declare function resolveMainGpu(): Promise<string | undefined>;
2
+ interface GpuHost {
3
+ readonly platform?: string;
4
+ readonly root?: string;
5
+ }
6
+ export declare function resolveMainGpu(host?: GpuHost): Promise<string | undefined>;
3
7
  export declare function resetMainGpuCache(): void;
8
+ export {};
@@ -1,12 +1,15 @@
1
1
  import { promises } from 'fs';
2
2
  import { platform } from 'os';
3
+ import path from 'path';
4
+ const NVIDIA_VENDOR = '0x10de';
3
5
  let cachedDedicated = null;
4
- export async function resolveMainGpu() {
5
- if (platform() !== 'linux')
6
+ export async function resolveMainGpu(host = {}) {
7
+ if ((host.platform ?? platform()) !== 'linux')
6
8
  return undefined;
7
9
  if (cachedDedicated !== null)
8
10
  return cachedDedicated;
9
- if (await hasNvidiaGpu()) {
11
+ const root = host.root ?? '/';
12
+ if ((await hasNvidiaGpu(root)) && (await hasOtherGpu(root))) {
10
13
  cachedDedicated = 'dedicated';
11
14
  return cachedDedicated;
12
15
  }
@@ -15,12 +18,33 @@ export async function resolveMainGpu() {
15
18
  export function resetMainGpuCache() {
16
19
  cachedDedicated = null;
17
20
  }
18
- async function hasNvidiaGpu() {
21
+ async function hasNvidiaGpu(root) {
19
22
  try {
20
- const entries = await promises.readdir('/proc/driver/nvidia/gpus');
23
+ const entries = await promises.readdir(path.join(root, 'proc/driver/nvidia/gpus'));
21
24
  return entries.length > 0;
22
25
  }
23
26
  catch {
24
27
  return false;
25
28
  }
26
29
  }
30
+ async function hasOtherGpu(root) {
31
+ const drm = path.join(root, 'sys/class/drm');
32
+ let entries;
33
+ try {
34
+ entries = await promises.readdir(drm);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ const cards = entries.filter((name) => /^card\d+$/.test(name));
40
+ const vendors = await Promise.all(cards.map((card) => vendorOf(path.join(drm, card, 'device/vendor'))));
41
+ return vendors.some((vendor) => vendor !== '' && vendor !== NVIDIA_VENDOR);
42
+ }
43
+ async function vendorOf(file) {
44
+ try {
45
+ return (await promises.readFile(file, 'utf8')).trim().toLowerCase();
46
+ }
47
+ catch {
48
+ return '';
49
+ }
50
+ }
@@ -1,5 +1,6 @@
1
1
  import type { AddonLoaders, ToolDefinition, ToolExecuteContext, ToolFetch } from '../contract/index.ts';
2
2
  import type { KnowledgeService } from '../contract/knowledge.ts';
3
+ import type { OcrService } from '../contract/ocr.ts';
3
4
  import type { SandboxService } from '../contract/sandbox.ts';
4
5
  import type { EgressProxyService } from '../contract/egress-proxy.ts';
5
6
  import type { EmbedHost, ModelHost } from '../contract/models.ts';
@@ -15,6 +16,7 @@ declare module './context.ts' {
15
16
  models: ModelHost;
16
17
  embed: EmbedHost;
17
18
  knowledge: KnowledgeService;
19
+ ocr: OcrService;
18
20
  sandbox: SandboxService;
19
21
  'egress-proxy': EgressProxyService;
20
22
  }
@@ -8,7 +8,6 @@ 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';
12
11
  import { isCapability } from './capabilities/invoke.js';
13
12
  import { CUSTOM_TASK_TYPES } from './models/model-catalog.js';
14
13
  import { unsupportedKvCacheDeletion } from './capabilities/kv-cache.js';
@@ -650,19 +649,7 @@ function completion(harness) {
650
649
  const pendingQuestion = new Map();
651
650
  const pendingDrive = new Map();
652
651
  const pendingRunLog = new Map();
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
- };
652
+ const input = pushQueue();
666
653
  const controller = new AbortController();
667
654
  const rounds = new RoundPort((event) => events.push(event));
668
655
  let calls = 0;
@@ -700,7 +687,7 @@ function completion(harness) {
700
687
  }
701
688
  pendingRunLog.clear();
702
689
  rounds.close();
703
- inputQueue.end();
690
+ input.end();
704
691
  events.end();
705
692
  };
706
693
  duplex.on('close', gone);
@@ -813,27 +800,11 @@ function completion(harness) {
813
800
  return;
814
801
  }
815
802
  if (frame.type === 'steer' || frame.type === 'follow-up') {
816
- const item = {
803
+ void input.push({
817
804
  mode: frame.type,
818
805
  text: frame.messages?.[0]?.content ?? '',
819
806
  id: frame.callId || undefined
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
- }
807
+ });
837
808
  return;
838
809
  }
839
810
  if (frame.type === 'run-log-result') {
@@ -1099,7 +1070,7 @@ function completion(harness) {
1099
1070
  await text.flush();
1100
1071
  events.push({ type: 'error', message: errorMessage(err) });
1101
1072
  }
1102
- inputQueue.end();
1073
+ input.end();
1103
1074
  events.push({ type: 'done' });
1104
1075
  HarnessLog.debug('wire end', { produced, frames });
1105
1076
  events.end();
@@ -49,6 +49,7 @@ export interface HarnessPluginOptions {
49
49
  mcp?: {
50
50
  servers?: HarnessMcpServer[];
51
51
  };
52
+ ocr?: boolean;
52
53
  [name: string]: unknown;
53
54
  }
54
55
  export interface HarnessChildOptions {
@@ -52,7 +52,7 @@ export function createReadFileTool({ realpath = defaultRealpath, deniedRoots } =
52
52
  end: positiveInt(args.endLine)
53
53
  };
54
54
  if (isDocument(resolved.key)) {
55
- const text = await documentOf(resolved, requested);
55
+ const text = await documentOf(resolved, requested, ctx);
56
56
  return typeof text === 'string' ? numbered(text, range) : text;
57
57
  }
58
58
  return await textRange(resolved, requested, range);
@@ -63,7 +63,7 @@ export function createReadFileTool({ realpath = defaultRealpath, deniedRoots } =
63
63
  }
64
64
  };
65
65
  }
66
- async function documentOf(resolved, requested) {
66
+ async function documentOf(resolved, requested, ctx) {
67
67
  const { drive } = resolved.root;
68
68
  const entry = await drive.entry(resolved.key);
69
69
  if (entry?.value.blob && entry.value.blob.byteLength > MAX_DOCUMENT_BYTES) {
@@ -80,7 +80,7 @@ async function documentOf(resolved, requested) {
80
80
  error: `${requested} is larger than the ${MAX_DOCUMENT_BYTES}-byte document extraction limit`
81
81
  };
82
82
  }
83
- return documentText(resolved.key, bytes);
83
+ return documentText(resolved.key, bytes, { ocr: ctx?.ocr, signal: ctx?.signal });
84
84
  }
85
85
  function numbered(text, { start, end }) {
86
86
  const lines = text.split('\n');
@@ -1,2 +1,8 @@
1
+ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ import type { OcrService } from '../../contract/ocr.ts';
1
3
  export declare function isDocument(key: string): boolean;
2
- export declare function documentText(key: string, bytes: Uint8Array): Promise<string>;
4
+ export interface DocumentTextOptions {
5
+ readonly ocr?: OcrService | undefined;
6
+ readonly signal?: BareAbortSignal | undefined;
7
+ }
8
+ export declare function documentText(key: string, bytes: Uint8Array, { ocr, signal }?: DocumentTextOptions): Promise<string>;
@@ -1,5 +1,6 @@
1
1
  import { HarnessError } from '../../errors.js';
2
2
  import { docx, pptx } from '../../office/engine/index.js';
3
+ import { recognizePages } from '../pdf/recognize.js';
3
4
  let pdfium = null;
4
5
  function loadPdfium() {
5
6
  pdfium ??= import('bare-pdfium').then((loaded) => loaded, () => null);
@@ -8,7 +9,7 @@ function loadPdfium() {
8
9
  export function isDocument(key) {
9
10
  return /\.(pdf|docx|pptx)$/i.test(key);
10
11
  }
11
- export async function documentText(key, bytes) {
12
+ export async function documentText(key, bytes, { ocr, signal } = {}) {
12
13
  if (!/\.pdf$/i.test(key)) {
13
14
  const read = /\.docx$/i.test(key) ? docx.open(bytes).read() : pptx.open(bytes).read();
14
15
  return collectText(read).join('\n');
@@ -19,8 +20,14 @@ export async function documentText(key, bytes) {
19
20
  }
20
21
  const doc = lib.open(bytes);
21
22
  try {
23
+ const recognized = ocr
24
+ ? (await recognizePages({ doc, bytes }, { ocr, signal })).pages
25
+ : undefined;
22
26
  return [...doc.textPages()]
23
- .map(({ page, text }) => `--- page ${page + 1} ---\n${text.replace(/\r\n?/g, '\n').trim()}`)
27
+ .map(({ page, text }) => {
28
+ const read = recognized?.get(page) ?? text;
29
+ return `--- page ${page + 1} ---\n${read.replace(/\r\n?/g, '\n').trim()}`;
30
+ })
24
31
  .join('\n');
25
32
  }
26
33
  finally {
@@ -1,3 +1,4 @@
1
+ import type { ToolExecuteContext } from '../../contract/index.ts';
1
2
  export interface OperationRequest {
2
3
  body?: Record<string, unknown>;
3
4
  params?: Record<string, unknown>;
@@ -10,9 +11,9 @@ export type BuilderOutcome = {
10
11
  error: string;
11
12
  };
12
13
  export interface OperationBuilder {
13
- build: (args: Record<string, unknown>) => BuilderOutcome;
14
+ build: (args: Record<string, unknown>, context?: ToolExecuteContext) => BuilderOutcome;
14
15
  }
15
- export declare const BUILDER_POLICY_VERSION = 1;
16
- export declare const BUILDER_NAMES: readonly ['gmail-send', 'gmail-draft', 'gmail-get', 'calendar-meet-event', 'calendar-add-meet', 'docs-create', 'docs-append-text', 'sheets-create', 'sheets-write-values', 'sheets-append-values', 'drive-create-folder', 'drive-trash', 'notion-create-page', 'notion-insert-content'];
16
+ export declare const BUILDER_POLICY_VERSION = 3;
17
+ export declare const BUILDER_NAMES: readonly ['gmail-send', 'gmail-draft', 'gmail-get', 'calendar-list-events', 'calendar-list-calendars', 'calendar-meet-event', 'calendar-add-meet', 'docs-create', 'docs-append-text', 'sheets-create', 'sheets-write-values', 'sheets-append-values', 'drive-create-folder', 'drive-trash', 'notion-create-page', 'notion-insert-content'];
17
18
  export type BuilderName = (typeof BUILDER_NAMES)[number];
18
19
  export declare const BUILDERS: Record<BuilderName, OperationBuilder>;
@@ -2,11 +2,14 @@ import { randomBytes } from 'crypto';
2
2
  import b4a from 'b4a';
3
3
  import { z } from 'zod';
4
4
  import { buildGmailMessage, GmailEnvelopeSchema } from './gmail-message.js';
5
- export const BUILDER_POLICY_VERSION = 1;
5
+ import { calendarBounds, CalendarRangeSchema } from './calendar-range.js';
6
+ export const BUILDER_POLICY_VERSION = 3;
6
7
  export const BUILDER_NAMES = [
7
8
  'gmail-send',
8
9
  'gmail-draft',
9
10
  'gmail-get',
11
+ 'calendar-list-events',
12
+ 'calendar-list-calendars',
10
13
  'calendar-meet-event',
11
14
  'calendar-add-meet',
12
15
  'docs-create',
@@ -21,12 +24,12 @@ export const BUILDER_NAMES = [
21
24
  ];
22
25
  function builder(schema, build) {
23
26
  return {
24
- build(args) {
27
+ build(args, context) {
25
28
  const parsed = schema.safeParse(args);
26
29
  if (!parsed.success) {
27
30
  return { error: parsed.error.issues[0]?.message ?? 'invalid arguments' };
28
31
  }
29
- return { request: build(parsed.data) };
32
+ return { request: build(parsed.data, context) };
30
33
  }
31
34
  };
32
35
  }
@@ -58,6 +61,39 @@ function createRequest() {
58
61
  }
59
62
  };
60
63
  }
64
+ const CalendarListEventsSchema = z
65
+ .object({
66
+ ...CalendarRangeSchema.shape,
67
+ calendarId: z.string().optional(),
68
+ q: z.string().optional(),
69
+ maxResults: z.number().int().min(1).max(2500).optional(),
70
+ pageToken: z.string().optional()
71
+ })
72
+ .refine((args) => !(args.range && args.date), {
73
+ message: 'Choose range or date, not both'
74
+ })
75
+ .refine((args) => !((args.range || args.date) && (args.timeMin || args.timeMax)), {
76
+ message: 'Use range or date for local dates; use timeMin/timeMax for explicit bounds'
77
+ })
78
+ .refine((args) => !args.timeMin || !args.timeMax || Date.parse(args.timeMax) > Date.parse(args.timeMin), {
79
+ message: 'timeMax must be later than timeMin'
80
+ });
81
+ const calendarListEvents = builder(CalendarListEventsSchema, (args, context) => ({
82
+ query: {
83
+ ...calendarBounds(args, context?.currentTime),
84
+ q: args.q,
85
+ maxResults: args.maxResults ?? 10,
86
+ pageToken: args.pageToken || undefined,
87
+ singleEvents: true,
88
+ orderBy: 'startTime'
89
+ }
90
+ }));
91
+ const calendarListCalendars = builder(z.object({
92
+ maxResults: z.number().int().min(1).max(250).optional(),
93
+ pageToken: z.string().optional()
94
+ }), (args) => ({
95
+ query: { maxResults: args.maxResults ?? 100, pageToken: args.pageToken || undefined }
96
+ }));
61
97
  const MeetEventSchema = z.object({
62
98
  summary: z.string(),
63
99
  start: z.iso.datetime({ offset: true }),
@@ -179,6 +215,8 @@ export const BUILDERS = {
179
215
  'gmail-send': gmailSend,
180
216
  'gmail-draft': gmailDraft,
181
217
  'gmail-get': gmailGet,
218
+ 'calendar-list-events': calendarListEvents,
219
+ 'calendar-list-calendars': calendarListCalendars,
182
220
  'calendar-meet-event': calendarMeetEvent,
183
221
  'calendar-add-meet': calendarAddMeet,
184
222
  'docs-create': docsCreate,
@@ -0,0 +1,16 @@
1
+ import { z } from 'zod';
2
+ export declare const CalendarRangeSchema: z.ZodObject<{
3
+ range: z.ZodPreprocess<z.ZodOptional<z.ZodEnum<{
4
+ all: "all";
5
+ today: "today";
6
+ tomorrow: "tomorrow";
7
+ upcoming: "upcoming";
8
+ }>>, unknown>;
9
+ date: z.ZodPreprocess<z.ZodOptional<z.ZodISODate>, unknown>;
10
+ timeMin: z.ZodPreprocess<z.ZodOptional<z.ZodISODateTime>, unknown>;
11
+ timeMax: z.ZodPreprocess<z.ZodOptional<z.ZodISODateTime>, unknown>;
12
+ }, z.core.$strip>;
13
+ type CalendarRange = z.infer<typeof CalendarRangeSchema>;
14
+ type CalendarBounds = Pick<CalendarRange, 'timeMin' | 'timeMax'>;
15
+ export declare function calendarBounds(args: CalendarRange, currentTime?: number): CalendarBounds;
16
+ export {};
@@ -0,0 +1,40 @@
1
+ import { z } from 'zod';
2
+ const emptyToAbsent = (value) => (value === '' ? undefined : value);
3
+ export const CalendarRangeSchema = z.object({
4
+ range: z.preprocess(emptyToAbsent, z
5
+ .enum(['upcoming', 'today', 'tomorrow', 'all'], {
6
+ error: 'range must be upcoming, today, tomorrow or all'
7
+ })
8
+ .optional()),
9
+ date: z.preprocess(emptyToAbsent, z.iso.date({ error: 'date must be YYYY-MM-DD' }).optional()),
10
+ timeMin: z.preprocess(emptyToAbsent, z.iso
11
+ .datetime({ offset: true, error: 'timeMin must be an RFC 3339 datetime with an offset' })
12
+ .optional()),
13
+ timeMax: z.preprocess(emptyToAbsent, z.iso
14
+ .datetime({ offset: true, error: 'timeMax must be an RFC 3339 datetime with an offset' })
15
+ .optional())
16
+ });
17
+ export function calendarBounds(args, currentTime = Date.now()) {
18
+ if (args.timeMin || args.timeMax) {
19
+ return { timeMin: args.timeMin ?? new Date(currentTime).toISOString(), timeMax: args.timeMax };
20
+ }
21
+ if (args.range === 'all')
22
+ return {};
23
+ const now = new Date(currentTime);
24
+ if (!args.date && (!args.range || args.range === 'upcoming')) {
25
+ return { timeMin: now.toISOString() };
26
+ }
27
+ const start = new Date(now);
28
+ if (args.date) {
29
+ const [year, month, day] = args.date.split('-').map(Number);
30
+ start.setFullYear(year, month - 1, day);
31
+ }
32
+ else if (args.range === 'tomorrow') {
33
+ start.setDate(start.getDate() + 1);
34
+ }
35
+ start.setHours(0, 0, 0, 0);
36
+ const end = new Date(start);
37
+ end.setDate(end.getDate() + 1);
38
+ end.setHours(0, 0, 0, 0);
39
+ return { timeMin: start.toISOString(), timeMax: end.toISOString() };
40
+ }