@qvac/harness 1.0.0-rc.20 → 1.0.0-rc.21

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 (191) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist-lib/index.d.ts +7 -5
  3. package/dist-lib/index.js +5 -4
  4. package/dist-lib/lib/agent/resolve.js +2 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/answering.js +2 -2
  6. package/dist-lib/lib/capabilities/completion-engine/actors/direct-search.js +1 -1
  7. package/dist-lib/lib/capabilities/completion-engine/actors/execute.d.ts +1 -1
  8. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +8 -6
  9. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +1 -1
  10. package/dist-lib/lib/capabilities/completion-engine/actors/inspect-prepare.js +1 -1
  11. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +2 -1
  12. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +8 -3
  13. package/dist-lib/lib/capabilities/completion-engine/actors/resolving.js +10 -4
  14. package/dist-lib/lib/capabilities/completion-engine/actors/run-prepare.js +2 -1
  15. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +8 -8
  16. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +2 -2
  17. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +3 -2
  18. package/dist-lib/lib/capabilities/completion-engine/loop.js +1 -0
  19. package/dist-lib/lib/capabilities/completion-engine/round.js +9 -9
  20. package/dist-lib/lib/capabilities/completion-engine/tool-caller.js +3 -1
  21. package/dist-lib/lib/capabilities/completion-engine/tool-execution.d.ts +5 -41
  22. package/dist-lib/lib/capabilities/completion-engine/tool-execution.js +4 -133
  23. package/dist-lib/lib/capabilities/completion-engine/tool-outcome.d.ts +4 -0
  24. package/dist-lib/lib/capabilities/completion-engine/tool-outcome.js +42 -0
  25. package/dist-lib/lib/capabilities/completion-engine/tool-preflight.d.ts +43 -0
  26. package/dist-lib/lib/capabilities/completion-engine/tool-preflight.js +91 -0
  27. package/dist-lib/lib/capabilities/completion-engine/turns.js +7 -4
  28. package/dist-lib/lib/capabilities/tool-turns/attachments.d.ts +7 -0
  29. package/dist-lib/lib/capabilities/tool-turns/attachments.js +39 -0
  30. package/dist-lib/lib/capabilities/tool-turns/copy.d.ts +13 -0
  31. package/dist-lib/lib/capabilities/tool-turns/copy.js +29 -0
  32. package/dist-lib/lib/capabilities/tool-turns/result-turn.d.ts +22 -0
  33. package/dist-lib/lib/capabilities/tool-turns/result-turn.js +120 -0
  34. package/dist-lib/lib/capabilities/tool-turns/run-limits.d.ts +6 -0
  35. package/dist-lib/lib/capabilities/tool-turns/run-limits.js +32 -0
  36. package/dist-lib/lib/capabilities/tool-turns/skill-loads.d.ts +9 -0
  37. package/dist-lib/lib/capabilities/tool-turns/skill-loads.js +71 -0
  38. package/dist-lib/lib/capabilities/tool-turns.d.ts +8 -54
  39. package/dist-lib/lib/capabilities/tool-turns.js +6 -281
  40. package/dist-lib/lib/client/index.js +3 -3
  41. package/dist-lib/lib/connect/abort.d.ts +6 -0
  42. package/dist-lib/lib/connect/abort.js +52 -0
  43. package/dist-lib/lib/connect/bridges.d.ts +21 -0
  44. package/dist-lib/lib/connect/bridges.js +185 -0
  45. package/dist-lib/lib/connect/decode.d.ts +31 -0
  46. package/dist-lib/lib/connect/decode.js +114 -0
  47. package/dist-lib/lib/connect/host-run-log.d.ts +16 -0
  48. package/dist-lib/lib/connect/host-run-log.js +74 -0
  49. package/dist-lib/lib/connect/served.d.ts +7 -0
  50. package/dist-lib/lib/connect/served.js +45 -0
  51. package/dist-lib/lib/connect.d.ts +3 -3
  52. package/dist-lib/lib/connect.js +24 -468
  53. package/dist-lib/lib/context-window.d.ts +13 -7
  54. package/dist-lib/lib/context-window.js +13 -6
  55. package/dist-lib/lib/contract/agent.d.ts +12 -1
  56. package/dist-lib/lib/contract/completion.d.ts +5 -1
  57. package/dist-lib/lib/contract/drive.d.ts +130 -4
  58. package/dist-lib/lib/contract/ocr.d.ts +5 -1
  59. package/dist-lib/lib/contract-types.d.ts +5 -3
  60. package/dist-lib/lib/errors.js +3 -3
  61. package/dist-lib/lib/helpers/goal-check/asks.d.ts +25 -0
  62. package/dist-lib/lib/helpers/goal-check/asks.js +52 -0
  63. package/dist-lib/lib/helpers/goal-check/checks.d.ts +8 -0
  64. package/dist-lib/lib/helpers/goal-check/checks.js +92 -0
  65. package/dist-lib/lib/helpers/goal-check/commands.d.ts +7 -0
  66. package/dist-lib/lib/helpers/goal-check/commands.js +130 -0
  67. package/dist-lib/lib/helpers/goal-check/paths.d.ts +5 -0
  68. package/dist-lib/lib/helpers/goal-check/paths.js +44 -0
  69. package/dist-lib/lib/helpers/goal-check/shell.d.ts +9 -0
  70. package/dist-lib/lib/helpers/goal-check/shell.js +96 -0
  71. package/dist-lib/lib/helpers/goal-check.d.ts +35 -43
  72. package/dist-lib/lib/helpers/goal-check.js +34 -406
  73. package/dist-lib/lib/helpers/recent-map.d.ts +7 -0
  74. package/dist-lib/lib/helpers/recent-map.js +23 -0
  75. package/dist-lib/lib/helpers/tool-call-markup/emit.d.ts +6 -0
  76. package/dist-lib/lib/helpers/tool-call-markup/emit.js +15 -0
  77. package/dist-lib/lib/helpers/tool-call-markup/recover.d.ts +22 -0
  78. package/dist-lib/lib/helpers/tool-call-markup/recover.js +130 -0
  79. package/dist-lib/lib/helpers/tool-call-markup/skill-recovery.d.ts +3 -0
  80. package/dist-lib/lib/helpers/tool-call-markup/skill-recovery.js +56 -0
  81. package/dist-lib/lib/helpers/tool-call-markup/strip.d.ts +4 -0
  82. package/dist-lib/lib/helpers/tool-call-markup/strip.js +149 -0
  83. package/dist-lib/lib/helpers/tool-call-markup.d.ts +19 -24
  84. package/dist-lib/lib/helpers/tool-call-markup.js +17 -343
  85. package/dist-lib/lib/machine/completion/actions/completion.d.ts +12 -18
  86. package/dist-lib/lib/machine/completion/actions/completion.js +19 -178
  87. package/dist-lib/lib/machine/completion/actions/goal.d.ts +10 -0
  88. package/dist-lib/lib/machine/completion/actions/goal.js +93 -0
  89. package/dist-lib/lib/machine/completion/actions/prepare.js +2 -1
  90. package/dist-lib/lib/machine/completion/actions/reject-tool.d.ts +16 -0
  91. package/dist-lib/lib/machine/completion/actions/reject-tool.js +147 -0
  92. package/dist-lib/lib/machine/completion/actions/retry-round.d.ts +6 -0
  93. package/dist-lib/lib/machine/completion/actions/retry-round.js +50 -0
  94. package/dist-lib/lib/machine/completion/actions/rounds.d.ts +5 -0
  95. package/dist-lib/lib/machine/completion/actions/rounds.js +31 -0
  96. package/dist-lib/lib/machine/completion/actions/tools.d.ts +1 -16
  97. package/dist-lib/lib/machine/completion/actions/tools.js +16 -161
  98. package/dist-lib/lib/machine/completion/context.js +3 -3
  99. package/dist-lib/lib/machine/completion/implementations.d.ts +2 -2
  100. package/dist-lib/lib/machine/completion/implementations.js +6 -2
  101. package/dist-lib/lib/machine/completion/machine.d.ts +2 -2
  102. package/dist-lib/lib/machine/completion/metrics.d.ts +25 -0
  103. package/dist-lib/lib/machine/completion/metrics.js +68 -0
  104. package/dist-lib/lib/machine/completion/nudges.d.ts +5 -0
  105. package/dist-lib/lib/machine/completion/nudges.js +33 -0
  106. package/dist-lib/lib/machine/completion/rules.d.ts +5 -34
  107. package/dist-lib/lib/machine/completion/rules.js +4 -120
  108. package/dist-lib/lib/machine/completion/splice.d.ts +9 -0
  109. package/dist-lib/lib/machine/completion/splice.js +19 -0
  110. package/dist-lib/lib/machine/completion/types.d.ts +4 -13
  111. package/dist-lib/lib/machine/index.d.ts +3 -3
  112. package/dist-lib/lib/machine/index.js +2 -2
  113. package/dist-lib/lib/media-host.js +2 -2
  114. package/dist-lib/lib/media-wire.js +2 -2
  115. package/dist-lib/lib/residency/completion-runtime.d.ts +2 -1
  116. package/dist-lib/lib/residency/completion-runtime.js +44 -1
  117. package/dist-lib/lib/residency/index.d.ts +3 -2
  118. package/dist-lib/lib/residency/index.js +2 -2
  119. package/dist-lib/lib/round-host.js +3 -3
  120. package/dist-lib/lib/round-port.js +3 -3
  121. package/dist-lib/lib/run-log/redact.js +7 -7
  122. package/dist-lib/lib/serve/completion.d.ts +7 -0
  123. package/dist-lib/lib/serve/completion.js +553 -0
  124. package/dist-lib/lib/serve/downloads.d.ts +4 -0
  125. package/dist-lib/lib/serve/downloads.js +79 -0
  126. package/dist-lib/lib/serve/models.d.ts +5 -0
  127. package/dist-lib/lib/serve/models.js +120 -0
  128. package/dist-lib/lib/serve/noop.d.ts +1 -0
  129. package/dist-lib/lib/serve/noop.js +1 -0
  130. package/dist-lib/lib/serve/requests.d.ts +147 -0
  131. package/dist-lib/lib/serve/requests.js +1 -0
  132. package/dist-lib/lib/serve/rounds.d.ts +11 -0
  133. package/dist-lib/lib/serve/rounds.js +67 -0
  134. package/dist-lib/lib/serve/run-log-start.d.ts +38 -0
  135. package/dist-lib/lib/serve/run-log-start.js +254 -0
  136. package/dist-lib/lib/serve/skills.d.ts +32 -0
  137. package/dist-lib/lib/serve/skills.js +46 -0
  138. package/dist-lib/lib/serve.d.ts +5 -1
  139. package/dist-lib/lib/serve.js +14 -1071
  140. package/dist-lib/lib/skills-host/index.d.ts +4 -2
  141. package/dist-lib/lib/skills-host/index.js +20 -8
  142. package/dist-lib/lib/tools/fs/drive.d.ts +1 -17
  143. package/dist-lib/lib/tools/fs/remote-protocol.d.ts +1 -81
  144. package/dist-lib/lib/tools/fs/scope.d.ts +2 -17
  145. package/dist-lib/lib/tools/fs/search.d.ts +2 -18
  146. package/dist-lib/lib/tools/fs/walk.d.ts +1 -5
  147. package/dist-lib/lib/tools/pdf/build.d.ts +2 -2
  148. package/dist-lib/lib/tools/pdf/recognize.js +4 -8
  149. package/dist-lib/lib/tools/pdf/request.d.ts +3 -8
  150. package/dist-lib/lib/tools/pdf/request.js +4 -4
  151. package/dist-lib/lib/tools/pdf.d.ts +0 -1
  152. package/dist-lib/lib/tools/pdf.js +0 -1
  153. package/dist-lib/lib/tools/skill.js +13 -4
  154. package/dist-lib/lib/tools/skills/bundled-dir.d.ts +3 -0
  155. package/dist-lib/lib/tools/skills/bundled-dir.js +27 -24
  156. package/dist-lib/lib/tools/skills/bundled-hash.d.ts +1 -0
  157. package/dist-lib/lib/tools/skills/bundled-hash.js +4 -1
  158. package/dist-lib/lib/tools/skills/catalog-loader.d.ts +12 -0
  159. package/dist-lib/lib/tools/skills/catalog-loader.js +173 -0
  160. package/dist-lib/lib/tools/skills/catalog.d.ts +5 -8
  161. package/dist-lib/lib/tools/skills/catalog.js +1 -162
  162. package/dist-lib/lib/tools/skills/index.d.ts +1 -0
  163. package/dist-lib/lib/tools/skills/index.js +1 -0
  164. package/dist-lib/lib/tools/skills/skill-tree.d.ts +5 -0
  165. package/dist-lib/lib/tools/skills/skill-tree.js +54 -0
  166. package/dist-lib/lib/wire/download.d.ts +10 -0
  167. package/dist-lib/lib/wire/download.js +35 -0
  168. package/dist-lib/lib/wire/event.d.ts +41 -0
  169. package/dist-lib/lib/wire/event.js +306 -0
  170. package/dist-lib/lib/wire/fields.d.ts +3 -0
  171. package/dist-lib/lib/wire/fields.js +12 -0
  172. package/dist-lib/lib/wire/knowledge.d.ts +9 -0
  173. package/dist-lib/lib/wire/knowledge.js +68 -0
  174. package/dist-lib/lib/wire/round.d.ts +14 -0
  175. package/dist-lib/lib/wire/round.js +45 -0
  176. package/dist-lib/lib/wire/vectors.d.ts +6 -0
  177. package/dist-lib/lib/wire/vectors.js +33 -0
  178. package/dist-lib/lib/wire.d.ts +28 -77
  179. package/dist-lib/lib/wire.js +24 -489
  180. package/dist-lib/plugins/ocr/coverage.d.ts +3 -0
  181. package/dist-lib/plugins/ocr/coverage.js +67 -0
  182. package/dist-lib/plugins/ocr/ocr-runtime.d.ts +4 -2
  183. package/dist-lib/plugins/ocr/ocr-runtime.js +25 -4
  184. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  185. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  186. package/dist-lib/schema/harness.js +4 -1
  187. package/dist-lib/spec/hrpc/messages.js +25 -1
  188. package/dist-lib/spec/hyperschema/index.js +25 -1
  189. package/dist-lib/spec/hyperschema/schema.json +6 -1
  190. package/dist-lib/spec/hyperschema/types.d.ts +1 -0
  191. package/package.json +2 -2
@@ -1,490 +1,25 @@
1
- import b4a from 'b4a';
2
- import { errorMessage, isRecord } from './guards.js';
3
- function stringField(value) {
4
- return typeof value === 'string' ? value : undefined;
5
- }
6
- function isRunVersion(value) {
7
- return (typeof value === 'string' &&
8
- value.length <= 40 &&
9
- /^\d{1,10}(?:\.\d{1,10}){0,3}(?:-[A-Za-z0-9.-]{1,16})?$/.test(value));
10
- }
11
- function objectField(value) {
12
- return isRecord(value) ? value : {};
13
- }
14
- export function isPlainWireValue(value) {
15
- if (value === null)
16
- return true;
17
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
18
- return true;
19
- }
20
- return (Array.isArray(value) &&
21
- value.every((item) => typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean'));
22
- }
23
- function isResource(value) {
24
- return isRecord(value) && typeof value.kind === 'string' && typeof value.label === 'string';
25
- }
26
- const REDACTED_RECOVERY_KEYS = new Set(['forkAt', 'forkSafe', 'recoveryOperationIds']);
27
- export function redactedRecoveryFields(source) {
28
- const fields = {};
29
- for (const [key, value] of Object.entries(source)) {
30
- if (!REDACTED_RECOVERY_KEYS.has(key))
31
- continue;
32
- if (isPlainWireValue(value)) {
33
- fields[key] = value;
34
- }
35
- }
36
- return fields;
37
- }
38
- export function toWire(event) {
39
- const wire = toWirePayload(event);
40
- if (typeof event.runId === 'string') {
41
- wire.runId = event.runId;
42
- }
43
- if (typeof event.round === 'number') {
44
- wire.round = event.round;
45
- }
46
- if (typeof event.callId === 'string') {
47
- wire.callId = event.callId;
48
- }
49
- return wire;
50
- }
51
- function toWirePayload(event) {
52
- switch (event.type) {
53
- case 'run-started':
54
- return typeof event.parentRunId === 'string'
55
- ? { type: event.type, payload: { parentRunId: event.parentRunId } }
56
- : { type: event.type };
57
- case 'run-resumed':
58
- case 'paused':
59
- return { type: event.type };
60
- case 'round-reset': {
61
- const wire = { type: event.type };
62
- if (Array.isArray(event.replacedTypes)) {
63
- wire.replacedTypes = event.replacedTypes.filter((value) => typeof value === 'string');
64
- }
65
- return wire;
66
- }
67
- case 'recovery-required':
68
- return { type: event.type, payload: event.operation };
69
- case 'content':
70
- case 'thinking':
71
- return { type: event.type, text: event.text };
72
- case 'tool-call':
73
- return {
74
- type: 'tool-call',
75
- name: stringField(event.name),
76
- arguments: event.args,
77
- rawCall: stringField(event.rawCall) ?? null,
78
- effect: stringField(event.effect) ?? null,
79
- display: event.display
80
- };
81
- case 'tool-result':
82
- return {
83
- type: 'tool-result',
84
- name: stringField(event.name),
85
- result: event.result
86
- };
87
- case 'tool-activity':
88
- return {
89
- type: 'tool-activity',
90
- name: stringField(event.name),
91
- arguments: event.args,
92
- resource: isResource(event.resource) ? event.resource : null,
93
- effect: stringField(event.effect),
94
- decision: stringField(event.decision)
95
- };
96
- case 'metrics': {
97
- const { type, runId, ...metrics } = event;
98
- return { type, metrics };
99
- }
100
- case 'inference-call':
101
- return { type: 'inference-call', payload: event.call };
102
- case 'inference-sent':
103
- return {
104
- type: 'inference-sent',
105
- payload: {
106
- round: event.round,
107
- droppedTurns: event.droppedTurns,
108
- tokens: event.tokens,
109
- outcome: event.outcome,
110
- reason: event.reason
111
- }
112
- };
113
- case 'error': {
114
- const diagnostic = {};
115
- if (event.code === 'PENDING_ARGS_REDACTED') {
116
- diagnostic.code = event.code;
117
- Object.assign(diagnostic, redactedRecoveryFields(event));
118
- }
119
- if (event.name === 'RunIncompatible' &&
120
- (event.kind === 'machine' || event.kind === 'log' || event.kind === 'xstate') &&
121
- isRunVersion(event.found) &&
122
- isRunVersion(event.expected)) {
123
- diagnostic.kind = event.kind;
124
- diagnostic.found = event.found;
125
- diagnostic.expected = event.expected;
126
- }
127
- const wire = { type: 'error', message: event.message };
128
- if (typeof event.name === 'string') {
129
- wire.name = event.name;
130
- }
131
- if (Object.keys(diagnostic).length > 0) {
132
- wire.payload = diagnostic;
133
- }
134
- return wire;
135
- }
136
- case 'aborted':
137
- return { type: 'aborted' };
138
- case 'input':
139
- return { type: 'input', text: stringField(event.text), callId: stringField(event.id) };
140
- case 'input-rejected':
141
- return { type: 'input-rejected', text: stringField(event.reason) };
142
- case 'context':
143
- return {
144
- type: 'context',
145
- callId: stringField(event.id),
146
- payload: event.context,
147
- result: event.sources
148
- };
149
- case 'goal':
150
- return {
151
- type: 'goal',
152
- text: stringField(event.text),
153
- payload: {
154
- status: event.status,
155
- turn: event.turn,
156
- checks: event.checks,
157
- proof: event.proof,
158
- cases: event.cases
159
- }
160
- };
161
- case 'fold':
162
- return event.phase === 'done'
163
- ? {
164
- type: 'fold',
165
- payload: {
166
- phase: 'done',
167
- summary: event.summary,
168
- throughId: event.throughId,
169
- foldedTurns: event.foldedTurns
170
- }
171
- }
172
- : { type: 'fold', payload: { phase: 'start' } };
173
- default:
174
- return { type: 'error', message: `unmapped harness event: ${event.type}` };
175
- }
176
- }
177
- export function fromWire(event) {
178
- const decoded = fromWirePayload(event);
179
- if (event.runId) {
180
- decoded.runId = event.runId;
181
- }
182
- if (event.runId &&
183
- event.round !== null &&
184
- event.round !== undefined &&
185
- [
186
- 'content',
187
- 'thinking',
188
- 'tool-call',
189
- 'tool-result',
190
- 'tool-activity',
191
- 'round-reset',
192
- 'input',
193
- 'context',
194
- 'goal'
195
- ].includes(event.type)) {
196
- decoded.round = event.round;
197
- }
198
- if (event.callId) {
199
- decoded.callId = event.callId;
200
- }
201
- return decoded;
202
- }
203
- function fromWirePayload(event) {
204
- switch (event.type) {
205
- case 'run-started': {
206
- const { parentRunId } = Object(event.payload);
207
- return typeof parentRunId === 'string'
208
- ? { type: event.type, parentRunId }
209
- : { type: event.type };
210
- }
211
- case 'run-resumed':
212
- case 'paused':
213
- return { type: event.type };
214
- case 'round-reset':
215
- return {
216
- type: event.type,
217
- replacedTypes: event.replacedTypes ?? undefined
218
- };
219
- case 'recovery-required':
220
- return { type: event.type, operation: event.payload };
221
- case 'content':
222
- case 'thinking':
223
- return { type: event.type, text: event.text ?? '' };
224
- case 'tool-call':
225
- return {
226
- type: 'tool-call',
227
- name: event.name ?? '',
228
- args: event.arguments ?? {},
229
- rawCall: event.rawCall ?? undefined,
230
- effect: event.effect === 'read' ? 'read' : 'write',
231
- display: event.display ?? undefined
232
- };
233
- case 'tool-result':
234
- return {
235
- type: 'tool-result',
236
- name: event.name ?? '',
237
- result: event.result
238
- };
239
- case 'tool-activity':
240
- return {
241
- type: 'tool-activity',
242
- name: event.name ?? '',
243
- args: event.arguments ?? {},
244
- resource: event.resource ?? null,
245
- effect: event.effect === 'read' ? 'read' : 'write',
246
- decision: event.decision || 'blocked'
247
- };
248
- case 'metrics':
249
- return { type: 'metrics', ...objectField(event.metrics) };
250
- case 'inference-call':
251
- return { type: 'inference-call', call: event.payload };
252
- case 'inference-sent': {
253
- const sent = objectField(event.payload);
254
- return {
255
- type: 'inference-sent',
256
- round: Number(sent.round ?? 0),
257
- droppedTurns: Number(sent.droppedTurns ?? 0),
258
- tokens: sent.tokens,
259
- outcome: sent.outcome || 'completed',
260
- reason: sent.reason || undefined
261
- };
262
- }
263
- case 'error': {
264
- const diagnostic = objectField(event.payload);
265
- const decoded = {
266
- type: 'error',
267
- message: event.message ?? 'harness error'
268
- };
269
- if (event.name) {
270
- decoded.name = event.name;
271
- }
272
- if (diagnostic.code === 'PENDING_ARGS_REDACTED') {
273
- decoded.code = diagnostic.code;
274
- Object.assign(decoded, redactedRecoveryFields(diagnostic));
275
- }
276
- if (event.name === 'RunIncompatible' &&
277
- (diagnostic.kind === 'machine' ||
278
- diagnostic.kind === 'log' ||
279
- diagnostic.kind === 'xstate') &&
280
- isRunVersion(diagnostic.found) &&
281
- isRunVersion(diagnostic.expected)) {
282
- decoded.kind = diagnostic.kind;
283
- decoded.found = diagnostic.found;
284
- decoded.expected = diagnostic.expected;
285
- }
286
- return decoded;
287
- }
288
- case 'aborted':
289
- return { type: 'aborted' };
290
- case 'input':
291
- return { type: 'input', text: event.text ?? '', id: event.callId || undefined };
292
- case 'input-rejected':
293
- return { type: 'input-rejected', reason: event.text ?? '' };
294
- case 'context': {
295
- const sources = Array.isArray(event.result) ? event.result.filter(isKnowledgeSource) : [];
296
- return {
297
- type: 'context',
298
- id: event.callId || undefined,
299
- context: objectField(event.payload),
300
- sources: sources.length ? sources : undefined
301
- };
302
- }
303
- case 'goal': {
304
- const { status, turn, checks, proof, cases } = objectField(event.payload);
305
- return { type: 'goal', status, turn, text: event.text || undefined, checks, proof, cases };
306
- }
307
- case 'fold': {
308
- const { phase, summary, throughId, foldedTurns } = objectField(event.payload);
309
- return phase === 'done'
310
- ? { type: 'fold', phase, summary, throughId, foldedTurns }
311
- : { type: 'fold', phase: 'start' };
312
- }
313
- default:
314
- return { type: event.type };
315
- }
316
- }
317
- export function roundFailureWire(err) {
318
- const { name = 'Error', code } = isRecord(err) ? err : {};
319
- return {
320
- message: errorMessage(err),
321
- payload: {
322
- name: String(name),
323
- code: typeof code === 'string' || typeof code === 'number' ? code : undefined
324
- }
325
- };
326
- }
327
- export function roundFailureFrom(wire) {
328
- const { name, code } = objectField(wire.payload);
329
- return Object.assign(new Error(wire.message ?? 'model round failed'), {
330
- name: typeof name === 'string' ? name : 'Error',
331
- code
332
- });
333
- }
334
- function isRoundRequest(value) {
335
- return (isRecord(value) &&
336
- typeof value.runId === 'string' &&
337
- typeof value.round === 'number' &&
338
- typeof value.modelId === 'string' &&
339
- Array.isArray(value.history));
340
- }
341
- export function roundRequestFrom(payload) {
342
- if (!isRoundRequest(payload)) {
343
- throw new TypeError('invalid model round request');
344
- }
345
- return payload;
346
- }
347
- function isRoundResult(value) {
348
- return isRecord(value) && typeof value.contentText === 'string' && isRecord(value.final);
349
- }
350
- export function roundResultFrom(wire) {
351
- if (isRoundResult(wire.result)) {
352
- return wire.result;
353
- }
354
- throw roundFailureFrom(wire);
355
- }
356
- export function roundChunkFrom(payload) {
357
- const { type, text } = objectField(payload);
358
- return { type: type === 'thinking' ? 'thinking' : 'content', text: String(text ?? '') };
359
- }
360
- export function toDownloadWire(event) {
361
- switch (event.type) {
362
- case 'progress': {
363
- const { type, ...progress } = event;
364
- return { type, progress };
365
- }
366
- case 'complete':
367
- return {
368
- type: 'complete',
369
- assetId: stringField(event.assetId),
370
- downloaded: typeof event.downloaded === 'boolean' ? event.downloaded : undefined
371
- };
372
- case 'error':
373
- return { type: 'error', message: event.message };
374
- case 'aborted':
375
- return { type: 'aborted' };
376
- default:
377
- return { type: 'error', message: `unmapped download event: ${event.type}` };
378
- }
379
- }
380
- export function fromDownloadWire(event) {
381
- switch (event.type) {
382
- case 'progress':
383
- return { type: 'progress', ...objectField(event.progress) };
384
- case 'complete':
385
- return { type: 'complete', assetId: event.assetId ?? '', downloaded: event.downloaded };
386
- case 'error':
387
- return { type: 'error', message: event.message ?? 'download error' };
388
- case 'aborted':
389
- return { type: 'aborted' };
390
- default:
391
- return { type: event.type };
392
- }
393
- }
394
- export function packVectors(vectors) {
395
- const dimensions = vectors[0]?.length ?? 0;
396
- const bytes = b4a.alloc(vectors.length * dimensions * 4);
397
- let offset = 0;
398
- for (const vector of vectors) {
399
- if (vector.length !== dimensions) {
400
- throw new Error('embed returned ragged vectors — every row must share one dimension');
401
- }
402
- for (const value of vector) {
403
- b4a.writeFloatLE(bytes, value, offset);
404
- offset += 4;
405
- }
406
- }
407
- return { dimensions, vectors: bytes };
408
- }
409
- export function unpackVectors(dimensions, bytes) {
410
- if (dimensions === 0)
411
- return [];
412
- const rowBytes = dimensions * 4;
413
- if (bytes.byteLength % rowBytes !== 0) {
414
- throw new Error('embed response length does not match its dimensions');
415
- }
416
- const rows = [];
417
- for (let offset = 0; offset < bytes.byteLength; offset += rowBytes) {
418
- const row = [];
419
- for (let index = 0; index < dimensions; index++) {
420
- row.push(b4a.readFloatLE(bytes, offset + index * 4));
421
- }
422
- rows.push(row);
423
- }
424
- return rows;
425
- }
426
- function embeddingWire(embedding) {
427
- return embedding ? { model: embedding.model, ...packVectors(embedding.vectors) } : {};
428
- }
429
- function embeddingFrom(wire, rows) {
430
- if (!wire.model)
431
- return null;
432
- const dimensions = wire.dimensions ?? 0;
433
- const vectors = unpackVectors(dimensions, wire.vectors ?? b4a.alloc(0));
434
- if (vectors.length !== rows) {
435
- throw new Error(`knowledge carried ${vectors.length} vectors for ${rows} chunks`);
436
- }
437
- return { model: wire.model, dimensions, vectors };
438
- }
439
- function metadataOf(value) {
440
- return isRecord(value) ? value : undefined;
441
- }
442
- function isKnowledgeSource(value) {
443
- return (isRecord(value) &&
444
- typeof value.artifactId === 'string' &&
445
- typeof value.chunkId === 'string' &&
446
- typeof value.score === 'number' &&
447
- (value.metadata === undefined || isRecord(value.metadata)));
448
- }
449
- export function toKnowledgeUpsertWire(artifact) {
450
- return {
451
- artifactId: artifact.artifactId,
452
- version: artifact.version,
453
- scope: artifact.scope,
454
- chunks: artifact.chunks.map(({ id, text, metadata }) => ({ id, text, metadata })),
455
- ...embeddingWire(artifact.embedding)
456
- };
457
- }
458
- export function fromKnowledgeUpsertWire(wire) {
459
- const chunks = wire.chunks.map(({ id, text, metadata }) => ({
460
- id,
461
- text,
462
- metadata: metadataOf(metadata)
463
- }));
464
- return {
465
- artifactId: wire.artifactId,
466
- version: wire.version || undefined,
467
- scope: wire.scope,
468
- chunks,
469
- embedding: embeddingFrom(wire, chunks.length) ?? undefined
470
- };
471
- }
472
- export function toKnowledgeUpsertResultWire(result) {
473
- return { added: result.added, ...embeddingWire(result.embedded) };
474
- }
475
- export function fromKnowledgeUpsertResultWire(wire, chunks) {
476
- return { added: wire.added, embedded: embeddingFrom(wire, chunks) };
477
- }
478
- export function fromKnowledgeHitWire({ metadata, ...hit }) {
479
- return { ...hit, metadata: metadataOf(metadata) };
480
- }
481
- export function fromKnowledgeStatusWire(wire) {
482
- return {
483
- ...wire,
484
- pending: wire.pending ?? 0,
485
- artifacts: wire.artifacts.map((artifact) => ({
486
- ...artifact,
487
- version: artifact.version || undefined
488
- }))
489
- };
1
+ import { fromDownloadWire, toDownloadWire } from './wire/download.js';
2
+ import { fromWire, redactedRecoveryFields, toWire } from './wire/event.js';
3
+ import { fromKnowledgeHitWire, fromKnowledgeStatusWire, fromKnowledgeUpsertResultWire, fromKnowledgeUpsertWire, toKnowledgeUpsertResultWire, toKnowledgeUpsertWire } from './wire/knowledge.js';
4
+ import { roundChunkFrom, roundFailureFrom, roundFailureWire, roundRequestFrom, roundResultFrom } from './wire/round.js';
5
+ import { packVectors, unpackVectors } from './wire/vectors.js';
6
+ export class Wire {
7
+ static fromDownloadWire = fromDownloadWire;
8
+ static fromKnowledgeHitWire = fromKnowledgeHitWire;
9
+ static fromKnowledgeStatusWire = fromKnowledgeStatusWire;
10
+ static fromKnowledgeUpsertResultWire = fromKnowledgeUpsertResultWire;
11
+ static fromKnowledgeUpsertWire = fromKnowledgeUpsertWire;
12
+ static fromWire = fromWire;
13
+ static packVectors = packVectors;
14
+ static redactedRecoveryFields = redactedRecoveryFields;
15
+ static roundChunkFrom = roundChunkFrom;
16
+ static roundFailureFrom = roundFailureFrom;
17
+ static roundFailureWire = roundFailureWire;
18
+ static roundRequestFrom = roundRequestFrom;
19
+ static roundResultFrom = roundResultFrom;
20
+ static toDownloadWire = toDownloadWire;
21
+ static toKnowledgeUpsertResultWire = toKnowledgeUpsertResultWire;
22
+ static toKnowledgeUpsertWire = toKnowledgeUpsertWire;
23
+ static toWire = toWire;
24
+ static unpackVectors = unpackVectors;
490
25
  }
@@ -0,0 +1,3 @@
1
+ import type { OcrImage } from '../../lib/contract/ocr.ts';
2
+ import type { OcrBlock } from './reading-order.ts';
3
+ export declare function inkCoverage(image: OcrImage, blocks: readonly OcrBlock[]): number;
@@ -0,0 +1,67 @@
1
+ const BOX_PAD = 2;
2
+ export function inkCoverage(image, blocks) {
3
+ const lum = luminance(image);
4
+ const level = otsu(lum);
5
+ const words = wordMask(image, blocks);
6
+ let ink = 0;
7
+ let covered = 0;
8
+ for (let i = 0; i < lum.length; i++) {
9
+ if ((lum[i] ?? 0) > level)
10
+ continue;
11
+ ink++;
12
+ covered += words[i] ?? 0;
13
+ }
14
+ return ink === 0 ? 1 : covered / ink;
15
+ }
16
+ function luminance({ width, height, data }) {
17
+ const lum = new Uint8Array(width * height);
18
+ for (let i = 0; i < lum.length; i++) {
19
+ const at = i * 4;
20
+ lum[i] = ((data[at] ?? 0) * 299 + (data[at + 1] ?? 0) * 587 + (data[at + 2] ?? 0) * 114) / 1000;
21
+ }
22
+ return lum;
23
+ }
24
+ function otsu(lum) {
25
+ const counts = new Float64Array(256);
26
+ for (const value of lum) {
27
+ counts[value] = (counts[value] ?? 0) + 1;
28
+ }
29
+ let total = 0;
30
+ counts.forEach((count, value) => {
31
+ total += value * count;
32
+ });
33
+ let dark = 0;
34
+ let darkSum = 0;
35
+ let best = -1;
36
+ let level = 0;
37
+ counts.forEach((count, value) => {
38
+ dark += count;
39
+ darkSum += value * count;
40
+ const light = lum.length - dark;
41
+ if (dark === 0 || light === 0) {
42
+ return;
43
+ }
44
+ const between = dark * light * (darkSum / dark - (total - darkSum) / light) ** 2;
45
+ if (between > best) {
46
+ best = between;
47
+ level = value;
48
+ }
49
+ });
50
+ return level;
51
+ }
52
+ function wordMask({ width, height }, blocks) {
53
+ const mask = new Uint8Array(width * height);
54
+ for (const { bbox } of blocks) {
55
+ if (!bbox)
56
+ continue;
57
+ const [x0, y0, x1, y1] = bbox;
58
+ const left = Math.max(0, Math.floor(x0) - BOX_PAD);
59
+ const right = Math.min(width, Math.ceil(x1) + BOX_PAD);
60
+ const top = Math.max(0, Math.floor(y0) - BOX_PAD);
61
+ const bottom = Math.min(height, Math.ceil(y1) + BOX_PAD);
62
+ for (let y = top; y < bottom; y++) {
63
+ mask.fill(1, y * width + left, y * width + right);
64
+ }
65
+ }
66
+ return mask;
67
+ }
@@ -1,6 +1,6 @@
1
1
  import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  import type { ModelHost } from '../../lib/contract/models.ts';
3
- import type { OcrImage, OcrService } from '../../lib/contract/ocr.ts';
3
+ import type { OcrImage, OcrPage, OcrService } from '../../lib/contract/ocr.ts';
4
4
  import { type OcrBlock } from './reading-order.ts';
5
5
  export interface OcrSdk {
6
6
  ocr(params: {
@@ -15,9 +15,11 @@ export declare class OcrRuntime implements OcrService {
15
15
  private readonly _loadSdk;
16
16
  private readonly _pool;
17
17
  private _tail;
18
+ private readonly _kept;
18
19
  constructor(models: ModelHost);
19
- read(image: OcrImage, signal?: BareAbortSignal): Promise<string>;
20
+ read(image: OcrImage, signal?: BareAbortSignal): Promise<OcrPage>;
20
21
  unloadIdle(): Promise<void>;
22
+ private _recognize;
21
23
  private _open;
22
24
  private _serial;
23
25
  }
@@ -1,11 +1,15 @@
1
+ import { createHash } from 'crypto';
1
2
  import { OCR_DOCTR, OCR_DOCTR_1 } from '@qvac/inference/models';
2
3
  import { errorMessage } from '../../lib/guards.js';
3
4
  import { raceAbort } from '../../lib/helpers/race-abort.js';
5
+ import { RecentMap } from '../../lib/helpers/recent-map.js';
4
6
  import { retryMemo } from '../../lib/helpers/retry-memo.js';
5
7
  import { HarnessLog } from '../../lib/log.js';
6
8
  import { bmp } from './bmp.js';
9
+ import { inkCoverage } from './coverage.js';
7
10
  import { readingOrder } from './reading-order.js';
8
11
  const OCR_MODEL_LABEL = 'OCR model';
12
+ const KEPT_PAGES = 1024;
9
13
  function ocrSdk(models) {
10
14
  return retryMemo(async () => {
11
15
  const sdk = await models.sdk();
@@ -29,6 +33,7 @@ export class OcrRuntime {
29
33
  _loadSdk;
30
34
  _pool;
31
35
  _tail = Promise.resolve();
36
+ _kept = new RecentMap(KEPT_PAGES);
32
37
  constructor(models) {
33
38
  this._models = models;
34
39
  this._loadSdk = ocrSdk(models);
@@ -41,12 +46,28 @@ export class OcrRuntime {
41
46
  });
42
47
  }
43
48
  async read(image, signal) {
49
+ const key = pageKey(image);
50
+ const kept = this._kept.get(key);
51
+ if (kept) {
52
+ return kept;
53
+ }
54
+ const page = await this._recognize(image, signal);
55
+ this._kept.set(key, page);
56
+ return page;
57
+ }
58
+ unloadIdle() {
59
+ return this._pool.evictIdle(() => true);
60
+ }
61
+ async _recognize(image, signal) {
44
62
  const { held, releaseWork } = this._open();
45
63
  let job = null;
46
64
  try {
47
65
  const { modelId } = await raceAbort(held.load(), signal);
48
66
  const sdk = await this._loadSdk();
49
- job = this._serial(async () => readingOrder(await sdk.ocr({ modelId, image: bmp(image) }).blocks));
67
+ job = this._serial(async () => {
68
+ const blocks = await sdk.ocr({ modelId, image: bmp(image) }).blocks;
69
+ return { text: readingOrder(blocks), coverage: inkCoverage(image, blocks) };
70
+ });
50
71
  return await raceAbort(job, signal);
51
72
  }
52
73
  finally {
@@ -60,9 +81,6 @@ export class OcrRuntime {
60
81
  });
61
82
  }
62
83
  }
63
- unloadIdle() {
64
- return this._pool.evictIdle(() => true);
65
- }
66
84
  _open() {
67
85
  const releaseWork = this._models.enterWork();
68
86
  try {
@@ -80,3 +98,6 @@ export class OcrRuntime {
80
98
  }
81
99
  }
82
100
  function noop() { }
101
+ function pageKey({ width, height, data }) {
102
+ return createHash('sha256').update(`${width}x${height}:`).update(data).digest('hex');
103
+ }