@qvac/harness 1.0.0-rc.14 → 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 (91) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +36 -6
  3. package/dist-lib/index.d.ts +2 -0
  4. package/dist-lib/index.js +2 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +20 -1
  6. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +2 -0
  7. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +5 -2
  8. package/dist-lib/lib/capabilities/completion-engine/driver.js +15 -0
  9. package/dist-lib/lib/capabilities/completion-engine/engine.js +23 -39
  10. package/dist-lib/lib/capabilities/completion-engine/loop.js +2 -1
  11. package/dist-lib/lib/capabilities/completion-engine/operations.js +1 -0
  12. package/dist-lib/lib/capabilities/completion-engine/round.js +14 -6
  13. package/dist-lib/lib/contract/completion.d.ts +6 -0
  14. package/dist-lib/lib/contract/models.d.ts +1 -1
  15. package/dist-lib/lib/contract/ocr.d.ts +9 -0
  16. package/dist-lib/lib/contract/ocr.js +1 -0
  17. package/dist-lib/lib/contract/run.d.ts +2 -0
  18. package/dist-lib/lib/helpers/goal-check.d.ts +26 -0
  19. package/dist-lib/lib/helpers/goal-check.js +248 -22
  20. package/dist-lib/lib/helpers/spawn-path.d.ts +1 -0
  21. package/dist-lib/lib/helpers/spawn-path.js +2 -1
  22. package/dist-lib/lib/machine/completion/actions/completion.d.ts +3 -2
  23. package/dist-lib/lib/machine/completion/actions/completion.js +65 -15
  24. package/dist-lib/lib/machine/completion/actions/tools.js +47 -6
  25. package/dist-lib/lib/machine/completion/context.js +5 -1
  26. package/dist-lib/lib/machine/completion/implementations.d.ts +1 -0
  27. package/dist-lib/lib/machine/completion/implementations.js +7 -0
  28. package/dist-lib/lib/machine/completion/machine.d.ts +4 -1
  29. package/dist-lib/lib/machine/completion/machine.js +10 -1
  30. package/dist-lib/lib/machine/completion/rules.d.ts +3 -1
  31. package/dist-lib/lib/machine/completion/rules.js +25 -4
  32. package/dist-lib/lib/machine/completion/types.d.ts +16 -0
  33. package/dist-lib/lib/machine/index.d.ts +6 -1
  34. package/dist-lib/lib/machine/index.js +2 -0
  35. package/dist-lib/lib/models/gpu-selection.d.ts +6 -1
  36. package/dist-lib/lib/models/gpu-selection.js +29 -5
  37. package/dist-lib/lib/models/model-pool.js +1 -2
  38. package/dist-lib/lib/office/engine/pptx/presentation.js +10 -5
  39. package/dist-lib/lib/plugins/registry.d.ts +2 -0
  40. package/dist-lib/lib/serve.js +5 -34
  41. package/dist-lib/lib/sidecar/index.js +1 -1
  42. package/dist-lib/lib/skills-host/index.d.ts +1 -1
  43. package/dist-lib/lib/skills-host/index.js +3 -2
  44. package/dist-lib/lib/spawn.d.ts +1 -0
  45. package/dist-lib/lib/tools/exec/runner.d.ts +4 -0
  46. package/dist-lib/lib/tools/exec/runner.js +20 -3
  47. package/dist-lib/lib/tools/files/read-file.js +3 -3
  48. package/dist-lib/lib/tools/fs/document-text.d.ts +7 -1
  49. package/dist-lib/lib/tools/fs/document-text.js +9 -2
  50. package/dist-lib/lib/tools/office.js +1 -0
  51. package/dist-lib/lib/tools/operations/builders.d.ts +4 -3
  52. package/dist-lib/lib/tools/operations/builders.js +41 -3
  53. package/dist-lib/lib/tools/operations/calendar-range.d.ts +16 -0
  54. package/dist-lib/lib/tools/operations/calendar-range.js +40 -0
  55. package/dist-lib/lib/tools/operations/compile.js +4 -2
  56. package/dist-lib/lib/tools/operations/manifest.d.ts +4 -0
  57. package/dist-lib/lib/tools/pdf/build.d.ts +11 -1
  58. package/dist-lib/lib/tools/pdf/build.js +52 -16
  59. package/dist-lib/lib/tools/pdf/recognize.d.ts +13 -0
  60. package/dist-lib/lib/tools/pdf/recognize.js +58 -0
  61. package/dist-lib/lib/tools/pdf.js +18 -4
  62. package/dist-lib/lib/tools/skills/overlay-watch.d.ts +2 -2
  63. package/dist-lib/lib/tools/skills/overlay-watch.js +4 -3
  64. package/dist-lib/lib/wire.js +9 -3
  65. package/dist-lib/plugins/image/index.js +5 -5
  66. package/dist-lib/plugins/music/index.js +4 -4
  67. package/dist-lib/plugins/ocr/bmp.d.ts +2 -0
  68. package/dist-lib/plugins/ocr/bmp.js +27 -0
  69. package/dist-lib/plugins/ocr/index.d.ts +12 -0
  70. package/dist-lib/plugins/ocr/index.js +18 -0
  71. package/dist-lib/plugins/ocr/ocr-runtime.d.ts +23 -0
  72. package/dist-lib/plugins/ocr/ocr-runtime.js +82 -0
  73. package/dist-lib/plugins/ocr/reading-order.d.ts +5 -0
  74. package/dist-lib/plugins/ocr/reading-order.js +71 -0
  75. package/dist-lib/plugins/sandbox-linux/index.js +2 -2
  76. package/dist-lib/plugins/sandbox-macos/index.js +2 -2
  77. package/dist-lib/plugins/sandbox-vm/index.d.ts +2 -1
  78. package/dist-lib/plugins/sandbox-vm/index.js +2 -2
  79. package/dist-lib/plugins/sandbox-vm/vm-shell.d.ts +3 -1
  80. package/dist-lib/plugins/sandbox-vm/vm-shell.js +45 -16
  81. package/dist-lib/plugins/sandbox-windows/index.js +2 -2
  82. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  83. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  84. package/package.json +14 -5
  85. package/scripts/addon-externals.cjs +3 -0
  86. package/worker/harness-sidecar.mjs +5 -0
  87. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +0 -20
  88. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +0 -110
  89. package/dist-lib/lib/helpers/input-budget.d.ts +0 -8
  90. package/dist-lib/lib/helpers/input-budget.js +0 -9
  91. package/patches/localwatch@1.4.3.patch +0 -13
@@ -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 {
@@ -587,6 +587,7 @@ function parameters(format) {
587
587
  items: {
588
588
  type: 'object',
589
589
  properties: { op: { type: 'string', enum: Object.keys(format.ops) } },
590
+ additionalProperties: true,
590
591
  required: ['op']
591
592
  }
592
593
  },
@@ -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
+ }
@@ -42,7 +42,7 @@ function operationTool(owningSkill, operation, transportTool) {
42
42
  },
43
43
  async execute(args, ctx) {
44
44
  const skillContext = { ...ctx, skills: [owningSkill] };
45
- const built = builder.build(args);
45
+ const built = builder.build(args, ctx);
46
46
  if ('error' in built) {
47
47
  return { error: `${operation.tool}: ${built.error}` };
48
48
  }
@@ -115,7 +115,9 @@ const PLACEHOLDER = /\{(\w+)\}/g;
115
115
  function fillTemplate(template, args, defaults) {
116
116
  const missing = [];
117
117
  const value = template.replace(PLACEHOLDER, (_match, name) => {
118
- const filled = args[name] ?? defaults?.[name];
118
+ const filled = args[name] === '' && defaults?.[name] !== undefined
119
+ ? defaults[name]
120
+ : (args[name] ?? defaults?.[name]);
119
121
  if (filled === undefined) {
120
122
  missing.push(name);
121
123
  }
@@ -17,6 +17,8 @@ declare const OperationSchema: z.ZodObject<{
17
17
  url: z.ZodString;
18
18
  builder: z.ZodEnum<{
19
19
  "calendar-add-meet": "calendar-add-meet";
20
+ "calendar-list-calendars": "calendar-list-calendars";
21
+ "calendar-list-events": "calendar-list-events";
20
22
  "calendar-meet-event": "calendar-meet-event";
21
23
  "docs-append-text": "docs-append-text";
22
24
  "docs-create": "docs-create";
@@ -45,6 +47,8 @@ declare const OperationSchema: z.ZodObject<{
45
47
  urlDefaults: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
46
48
  builder: z.ZodEnum<{
47
49
  "calendar-add-meet": "calendar-add-meet";
50
+ "calendar-list-calendars": "calendar-list-calendars";
51
+ "calendar-list-events": "calendar-list-events";
48
52
  "calendar-meet-event": "calendar-meet-event";
49
53
  "docs-append-text": "docs-append-text";
50
54
  "docs-create": "docs-create";
@@ -7,9 +7,14 @@ export interface Source {
7
7
  readonly fileName: string;
8
8
  readonly bytes: Uint8Array;
9
9
  }
10
+ export interface Recognized {
11
+ readonly pages: ReadonlyMap<number, string>;
12
+ readonly unreadFrom: number | null;
13
+ }
10
14
  export interface Opened {
11
15
  readonly source: Source;
12
16
  readonly doc: Doc;
17
+ readonly recognized?: Recognized | undefined;
13
18
  }
14
19
  export interface Built {
15
20
  readonly bytes: Uint8Array;
@@ -37,9 +42,14 @@ export interface ReadDocument {
37
42
  export interface ReadDocuments {
38
43
  readonly documents: readonly ReadDocument[];
39
44
  }
45
+ export interface ReadBudget {
46
+ chars: number;
47
+ }
48
+ export declare const READ_TEXT_LIMIT = 30000;
49
+ export declare function cleanText(text: string): string;
40
50
  export declare function pagesLabel(count: number): string;
41
51
  export type ShownPage = (fileName: string, page: number) => boolean;
42
- export declare function textless({ doc }: Opened): boolean;
52
+ export declare function textless(opened: Opened): boolean;
43
53
  export declare function everyPageShown({ source, doc }: Opened, isShown: ShownPage): boolean;
44
54
  export declare function shownNote({ source, doc }: Opened): string;
45
55
  export declare function readDocs(opened: readonly Opened[], isShown: ShownPage): ReadDocument | ReadDocuments;
@@ -1,5 +1,8 @@
1
1
  import b4a from 'b4a';
2
- const READ_TEXT_LIMIT = 30_000;
2
+ export const READ_TEXT_LIMIT = 30_000;
3
+ export function cleanText(text) {
4
+ return text.replace(/\r\n?/g, '\n').trim();
5
+ }
3
6
  function plural(count, noun) {
4
7
  return `${count} ${noun}${count === 1 ? '' : 's'}`;
5
8
  }
@@ -30,16 +33,39 @@ const SHOWN = {
30
33
  one: 'shown to you as an image in the user message, so read its content from that image',
31
34
  many: 'shown to you as images in the user message, so read their content from those images'
32
35
  };
33
- function scannedNote(scanned, shown) {
36
+ function scannedNote(scanned, { shown, blank }) {
34
37
  if (!scanned.length)
35
38
  return undefined;
36
39
  const one = scanned.length === 1;
37
40
  const what = one ? 'it is a scanned image' : 'they are scanned images';
38
- const where = shown ? SHOWN[one ? 'one' : 'many'] : 'and there is no OCR here';
41
+ let where = 'and there is no OCR here';
42
+ if (shown) {
43
+ where = SHOWN[one ? 'one' : 'many'];
44
+ }
45
+ else if (blank) {
46
+ where = `and OCR found no text on ${one ? 'it' : 'them'}`;
47
+ }
39
48
  return `${one ? 'page' : 'pages'} ${scanned.join(', ')} ${one ? 'has' : 'have'} no text layer: ${what}, ${where}`;
40
49
  }
41
- export function textless({ doc }) {
42
- for (const page of doc.textPages()) {
50
+ function recognizedNote(pages) {
51
+ if (!pages.length)
52
+ return undefined;
53
+ const one = pages.length === 1;
54
+ const what = one ? 'is a scanned image' : 'are scanned images';
55
+ return `${one ? 'page' : 'pages'} ${pages.join(', ')} ${what}, read here by OCR, so a word may be misread`;
56
+ }
57
+ function readNote(fileName, { read, scanned, blank }, isShown) {
58
+ const shown = scanned.every((page) => isShown(fileName, page));
59
+ const notes = [recognizedNote(read), scannedNote(scanned, { shown, blank })].filter((note) => note !== undefined);
60
+ return notes.length ? notes.join('; ') : undefined;
61
+ }
62
+ function* pageTexts({ doc, recognized }) {
63
+ for (const { page, text } of doc.textPages()) {
64
+ yield { page, text: recognized?.pages.get(page) ?? text };
65
+ }
66
+ }
67
+ export function textless(opened) {
68
+ for (const page of pageTexts(opened)) {
43
69
  if (page.text.trim())
44
70
  return false;
45
71
  }
@@ -57,29 +83,37 @@ export function shownNote({ source, doc }) {
57
83
  const what = one ? 'it is a scanned image' : 'its pages are scanned images';
58
84
  return `${source.fileName} has no text layer: ${what}, ${SHOWN[one ? 'one' : 'many']}`;
59
85
  }
60
- function readOne({ source, doc }, budget, isShown) {
86
+ function readOne(opened, budget, isShown) {
87
+ const { source, doc, recognized } = opened;
88
+ const unreadFrom = recognized?.unreadFrom ?? Infinity;
61
89
  const pages = [];
90
+ const read = [];
62
91
  const scanned = [];
63
92
  let truncated = false;
64
- for (const { page, text } of doc.textPages()) {
65
- const clean = text.replace(/\r\n?/g, '\n').trim();
66
- if (!clean) {
93
+ for (const { page, text } of pageTexts(opened)) {
94
+ const unread = page >= unreadFrom;
95
+ const clean = cleanText(text);
96
+ if (!clean && !unread) {
67
97
  scanned.push(page + 1);
68
98
  }
69
99
  const kept = clean.slice(0, Math.max(0, budget.chars));
70
100
  budget.chars -= kept.length;
71
- truncated ||= kept.length < clean.length;
101
+ truncated ||= unread || kept.length < clean.length;
72
102
  if (budget.chars > 0 || kept) {
73
103
  pages.push({ page: page + 1, text: kept });
104
+ if (kept && recognized?.pages.has(page)) {
105
+ read.push(page + 1);
106
+ }
74
107
  }
75
108
  }
109
+ const blank = scanned.every((page) => recognized?.pages.has(page - 1));
76
110
  return {
77
111
  attachmentId: source.attachmentId,
78
112
  fileName: source.fileName,
79
113
  pageCount: doc.pageCount(),
80
114
  pages,
81
115
  fields: doc.fields().map(describeField),
82
- note: scannedNote(scanned, scanned.every((page) => isShown(source.fileName, page))),
116
+ note: readNote(source.fileName, { read, scanned, blank }, isShown),
83
117
  truncated: truncated || undefined
84
118
  };
85
119
  }
@@ -104,12 +138,14 @@ function joinPages(pdfium, parts, pages) {
104
138
  out.close();
105
139
  }
106
140
  }
107
- function textFile({ source, doc }) {
108
- const text = [...doc.textPages()]
109
- .map((page) => page.text.replace(/\r\n?/g, '\n').trim())
110
- .join('\n\n');
141
+ function textFile(opened) {
142
+ const { source, doc } = opened;
143
+ const text = [...pageTexts(opened)].map((page) => cleanText(page.text)).join('\n\n');
111
144
  if (!text.trim()) {
112
- return `${source.fileName} has no text layer: its pages are scanned images, and there is no OCR here`;
145
+ const why = opened.recognized?.pages.size
146
+ ? 'and OCR found no text on them'
147
+ : 'and there is no OCR here';
148
+ return `${source.fileName} has no text layer: its pages are scanned images, ${why}`;
113
149
  }
114
150
  return { bytes: b4a.from(text + '\n', 'utf8'), pageCount: doc.pageCount() };
115
151
  }
@@ -0,0 +1,13 @@
1
+ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ import type { OcrService } from '../../contract/ocr.ts';
3
+ import { type Doc, type ReadBudget, type Recognized } from './build.ts';
4
+ export interface ScannedDocument {
5
+ readonly doc: Doc;
6
+ readonly bytes: Uint8Array;
7
+ }
8
+ export interface RecognizeOptions {
9
+ readonly ocr: OcrService;
10
+ readonly signal?: BareAbortSignal | undefined;
11
+ readonly budget?: ReadBudget | undefined;
12
+ }
13
+ export declare function recognizePages({ doc, bytes }: ScannedDocument, { ocr, signal, budget }: RecognizeOptions): Promise<Recognized>;
@@ -0,0 +1,58 @@
1
+ import { createHash } from 'crypto';
2
+ import { errorMessage } from '../../guards.js';
3
+ import { HarnessLog } from '../../log.js';
4
+ import { cleanText } from './build.js';
5
+ const OCR_SCALE = 2;
6
+ const KEPT_DOCUMENTS = 8;
7
+ const keptByService = new WeakMap();
8
+ export async function recognizePages({ doc, bytes }, { ocr, signal, budget }) {
9
+ const pages = new Map();
10
+ let kept = null;
11
+ let failed = false;
12
+ for (const { page, text } of doc.textPages()) {
13
+ if (budget && budget.chars <= 0) {
14
+ return { pages, unreadFrom: page };
15
+ }
16
+ let read = cleanText(text);
17
+ if (!read && !failed && doc.pageFlags(page).hasImage) {
18
+ kept ??= keptPages(ocr, bytes);
19
+ const found = kept.get(page) ?? (await readPage(doc, page, { ocr, signal }));
20
+ failed = found === null;
21
+ if (found !== null) {
22
+ kept.set(page, found);
23
+ pages.set(page, found);
24
+ read = found;
25
+ }
26
+ }
27
+ if (budget) {
28
+ budget.chars -= read.length;
29
+ }
30
+ }
31
+ return { pages, unreadFrom: null };
32
+ }
33
+ async function readPage(doc, page, { ocr, signal }) {
34
+ try {
35
+ return cleanText(await ocr.read(await doc.renderAsync(page, { scale: OCR_SCALE }), signal));
36
+ }
37
+ catch (err) {
38
+ if (signal?.aborted) {
39
+ throw err;
40
+ }
41
+ HarnessLog.warn('ocr failed; scanned pages stay unread', { page, err: errorMessage(err) });
42
+ return null;
43
+ }
44
+ }
45
+ function keptPages(ocr, bytes) {
46
+ const documents = keptByService.get(ocr) ?? new Map();
47
+ keptByService.set(ocr, documents);
48
+ const id = createHash('sha256').update(bytes).digest('hex');
49
+ const pages = documents.get(id) ?? new Map();
50
+ documents.delete(id);
51
+ documents.set(id, pages);
52
+ for (const oldest of documents.keys()) {
53
+ if (documents.size <= KEPT_DOCUMENTS)
54
+ break;
55
+ documents.delete(oldest);
56
+ }
57
+ return pages;
58
+ }
@@ -1,7 +1,8 @@
1
1
  import { errorCode, errorMessage } from '../guards.js';
2
2
  import { checkOutputBytes, RUN_OUTPUT_BUDGET_BYTES } from './attachments/output-policy.js';
3
- import { build, pagesLabel, everyPageShown, readDocs, shownNote, textless } from './pdf/build.js';
3
+ import { build, pagesLabel, everyPageShown, readDocs, READ_TEXT_LIMIT, shownNote, textless } from './pdf/build.js';
4
4
  import { placeImages } from './pdf/images.js';
5
+ import { recognizePages } from './pdf/recognize.js';
5
6
  import { PAGE_SIZES, parseRequest, PDF_ACTIONS, WHERE_IDS_ARE } from './pdf/request.js';
6
7
  export { parsePages, parseRequest } from './pdf/request.js';
7
8
  const SUFFIXES = {
@@ -208,6 +209,18 @@ function shownPages(ctx) {
208
209
  const names = (ctx.turnImages ?? []).map((image) => image.path.split(/[\\/]/).pop()?.slice(33));
209
210
  return (fileName, page) => names.includes(renderedPageName(fileName, page));
210
211
  }
212
+ async function withRecognized(opened, request, { ocr, signal }) {
213
+ if (!ocr || (request.action !== 'read' && request.action !== 'text')) {
214
+ return opened;
215
+ }
216
+ const budget = request.action === 'read' ? { chars: READ_TEXT_LIMIT } : undefined;
217
+ const out = [];
218
+ for (const one of opened) {
219
+ const scanned = { doc: one.doc, bytes: one.source.bytes };
220
+ out.push({ ...one, recognized: await recognizePages(scanned, { ocr, signal, budget }) });
221
+ }
222
+ return out;
223
+ }
211
224
  async function run(pdfium, asked, ctx) {
212
225
  if (asked.action === 'create') {
213
226
  const placed = await placeImages(asked, ctx);
@@ -223,17 +236,18 @@ async function run(pdfium, asked, ctx) {
223
236
  if (error) {
224
237
  return { error };
225
238
  }
239
+ const read = await withRecognized(opened, request, ctx);
226
240
  if (request.action === 'read') {
227
- return readDocs(opened, shownPages(ctx));
241
+ return readDocs(read, shownPages(ctx));
228
242
  }
229
- const [only] = opened;
243
+ const [only] = read;
230
244
  if (request.action === 'text' &&
231
245
  only &&
232
246
  textless(only) &&
233
247
  everyPageShown(only, shownPages(ctx))) {
234
248
  return { note: shownNote(only) };
235
249
  }
236
- return await deliver({ pdfium, request, opened }, ctx);
250
+ return await deliver({ pdfium, request, opened: read }, ctx);
237
251
  }
238
252
  finally {
239
253
  for (const { doc } of opened) {
@@ -1,10 +1,10 @@
1
1
  export interface OverlayWatcher {
2
- stop(): void;
2
+ stop(): Promise<void>;
3
3
  }
4
4
  export type OverlayChangeStream = AsyncIterable<{
5
5
  diff?: readonly unknown[];
6
6
  }> & {
7
- destroy?: () => void;
7
+ destroy: () => void;
8
8
  };
9
9
  export type WatchStreamFactory = (overlayDir: string) => OverlayChangeStream;
10
10
  export interface WatchSkillsOverlayOptions {
@@ -19,7 +19,7 @@ export function watchSkillsOverlay(overlayDir, onChange, opts = {}) {
19
19
  }
20
20
  }, debounceMs);
21
21
  };
22
- void (async () => {
22
+ const drained = (async () => {
23
23
  try {
24
24
  for await (const batch of stream) {
25
25
  if (batch?.diff && batch.diff.length > 0) {
@@ -33,13 +33,14 @@ export function watchSkillsOverlay(overlayDir, onChange, opts = {}) {
33
33
  return {
34
34
  stop() {
35
35
  if (stopped)
36
- return;
36
+ return drained;
37
37
  stopped = true;
38
38
  if (timer) {
39
39
  clearTimeout(timer);
40
40
  }
41
41
  timer = null;
42
- stream.destroy?.();
42
+ stream.destroy();
43
+ return drained;
43
44
  }
44
45
  };
45
46
  }
@@ -150,7 +150,13 @@ function toWirePayload(event) {
150
150
  return {
151
151
  type: 'goal',
152
152
  text: stringField(event.text),
153
- payload: { status: event.status, turn: event.turn, checks: event.checks }
153
+ payload: {
154
+ status: event.status,
155
+ turn: event.turn,
156
+ checks: event.checks,
157
+ proof: event.proof,
158
+ cases: event.cases
159
+ }
154
160
  };
155
161
  case 'fold':
156
162
  return event.phase === 'done'
@@ -295,8 +301,8 @@ function fromWirePayload(event) {
295
301
  };
296
302
  }
297
303
  case 'goal': {
298
- const { status, turn, checks } = objectField(event.payload);
299
- return { type: 'goal', status, turn, text: event.text || undefined, checks };
304
+ const { status, turn, checks, proof, cases } = objectField(event.payload);
305
+ return { type: 'goal', status, turn, text: event.text || undefined, checks, proof, cases };
300
306
  }
301
307
  case 'fold': {
302
308
  const { phase, summary, throughId, foldedTurns } = objectField(event.payload);
@@ -3,11 +3,6 @@ import { retryMemo } from '../../lib/helpers/retry-memo.js';
3
3
  import { PluginRegistry } from '../../lib/plugins/index.js';
4
4
  import { createEditImageTool, loadMediaCodecs } from './edit-image.js';
5
5
  import { createDiffusionRuntime, createGenerateImageTool } from './generate-image.js';
6
- PluginRegistry.requirePeers('image', {
7
- '@qvac/diffusion-cpp': () => import.meta.resolve('@qvac/diffusion-cpp/addonLogging'),
8
- 'bare-image-resample': () => import.meta.resolve('bare-image-resample'),
9
- 'bare-media': () => import.meta.resolve('bare-media')
10
- });
11
6
  export { createEditImageTool } from './edit-image.js';
12
7
  export { createDiffusionRuntime, createGenerateImageTool, generationPercentTick, settingsDimension, settingsSteps } from './generate-image.js';
13
8
  function diffusionRuntime(models, model) {
@@ -67,6 +62,11 @@ export class Image {
67
62
  read;
68
63
  _options;
69
64
  constructor(options) {
65
+ PluginRegistry.requirePeers('image', {
66
+ '@qvac/diffusion-cpp': () => import.meta.resolve('@qvac/diffusion-cpp/addonLogging'),
67
+ 'bare-image-resample': () => import.meta.resolve('bare-image-resample'),
68
+ 'bare-media': () => import.meta.resolve('bare-media')
69
+ });
70
70
  this._options = options;
71
71
  this.read = options.read;
72
72
  }