@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,273 +1,21 @@
1
1
  import b4a from 'b4a';
2
- import { AbortController } from 'bare-abort-controller';
3
- import fs from 'fs';
4
2
  import { HarnessError } from './errors.js';
5
- import { AbortedError } from './helpers/engine-error.js';
6
3
  import { settleOnClose } from './rpc-session.js';
7
- import { pipeline, Readable } from 'streamx';
4
+ import { pipeline } from 'streamx';
8
5
  import { bindApi } from '../spec/bind.js';
9
6
  import HRPC from '../spec/hrpc/index.js';
10
- import { encode } from '../spec/hrpc/messages.js';
11
- import { checkGoal, checkMaxToolRounds } from './capabilities/tool-turns.js';
12
- import { isCapability } from './capabilities/invoke.js';
13
7
  import { CUSTOM_TASK_TYPES } from './models/model-catalog.js';
14
8
  import { unsupportedKvCacheDeletion } from './capabilities/kv-cache.js';
15
- import { RunLog } from './run-log/index.js';
16
- import { errorMessage, isRecord } from './guards.js';
17
- import { HarnessLog } from './log.js';
18
- import { pushQueue } from './queue.js';
19
- import { MediaPort } from './media-port.js';
20
- import { mediaRequestFrom, mediaResultWire } from './media-wire.js';
21
- import { RoundPort } from './round-port.js';
22
- import { TextCoalescer } from './helpers/text-coalescer.js';
23
9
  import { prepareOpenclCache } from './models/opencl-cache.js';
24
- import { stageFile, sweepStaging } from './staging.js';
10
+ import { sweepStaging } from './staging.js';
25
11
  import { sweepSpill } from './spill.js';
26
- import { readSetup, toWireSetup } from './tools/skills/manifest-parse.js';
27
- import { fromKnowledgeUpsertWire, roundFailureWire, roundRequestFrom, packVectors, toDownloadWire, toKnowledgeUpsertResultWire, toWire } from './wire.js';
28
- const MODEL_STATUSES = new Set([
29
- 'loading',
30
- 'downloading',
31
- 'downloaded',
32
- 'ready',
33
- 'error',
34
- 'unloading',
35
- 'unloaded',
36
- 'held'
37
- ]);
38
- const DOWNLOAD_PROGRESS_INTERVAL_MS = 500;
39
- const WIRE_HIGH_WATER_MARK = 64;
40
- const TEXT_COALESCE_CAP = 8192;
41
- const TEXT_COALESCE_MS = 60;
42
- function noop() { }
43
- function decodeDigestKey(value) {
44
- if (typeof value !== 'string' || !/^[0-9a-f]{64}$/i.test(value)) {
45
- return undefined;
46
- }
47
- return b4a.from(value, 'hex');
48
- }
49
- function isEngineBoot(value) {
50
- if (!isEngineBootEnvelope(value)) {
51
- return false;
52
- }
53
- try {
54
- RunLog.validateEngineBoot(value);
55
- return true;
56
- }
57
- catch {
58
- return false;
59
- }
60
- }
61
- function isEngineBootEnvelope(value) {
62
- if (!isRecord(value)) {
63
- return false;
64
- }
65
- const counter = (name) => typeof value[name] === 'number' && Number.isSafeInteger(value[name]) && value[name] >= 0;
66
- const metadata = value.metadata;
67
- const hasMetadata = metadata === null ||
68
- (isRecord(metadata) && metadata.version === RunLog.VERSION && metadata.type === 'metadata');
69
- return (value.protocolVersion === 1 &&
70
- counter('length') &&
71
- counter('nextSeq') &&
72
- counter('deltasSinceCheckpoint') &&
73
- counter('unredactedLength') &&
74
- (value.machineVersion === null || typeof value.machineVersion === 'number') &&
75
- (value.xstateVersion === null || typeof value.xstateVersion === 'string') &&
76
- hasMetadata &&
77
- 'eventState' in value &&
78
- (value.snapshotSavedAt === undefined || typeof value.snapshotSavedAt === 'number') &&
79
- (value.firstSavedAt === undefined || typeof value.firstSavedAt === 'number') &&
80
- (value.redactedPendingArgs === null || typeof value.redactedPendingArgs === 'boolean') &&
81
- typeof value.restoredRedacted === 'boolean' &&
82
- Array.isArray(value.forkBeforeWrite) &&
83
- Array.isArray(value.receipts) &&
84
- Array.isArray(value.intentArgs));
85
- }
86
- const EMPTY_IDENTITY_FIELDS = new Set([
87
- 'model',
88
- 'cacheKey',
89
- 'thinkingDefault',
90
- 'agent.id',
91
- 'agent.name',
92
- 'agent.bio'
93
- ]);
94
- function optionalNumber(value) {
95
- return value === undefined || typeof value === 'number';
96
- }
97
- function goalFrom(value) {
98
- const { objective, rounds, ms, tokens, checks, checksProve } = value;
99
- if (typeof objective !== 'string' ||
100
- !optionalNumber(rounds) ||
101
- !optionalNumber(ms) ||
102
- !optionalNumber(tokens) ||
103
- (checks !== undefined &&
104
- (!Array.isArray(checks) || !checks.every((check) => typeof check === 'string'))) ||
105
- (checksProve !== undefined && typeof checksProve !== 'boolean')) {
106
- throw new TypeError('Invalid goal');
107
- }
108
- return { objective, rounds, ms, tokens, checks, checksProve };
109
- }
110
- function startPayloadFrom(value) {
111
- if (!isRecord(value)) {
112
- return {};
113
- }
114
- const payload = {};
115
- if (value.resume === null || typeof value.resume === 'boolean') {
116
- payload.resume = value.resume;
117
- }
118
- if (value.recoveryEvents === null || typeof value.recoveryEvents === 'boolean') {
119
- payload.recoveryEvents = value.recoveryEvents;
120
- }
121
- if (Object.hasOwn(value, 'explicitEmptyIdentity')) {
122
- if (!Array.isArray(value.explicitEmptyIdentity) ||
123
- value.explicitEmptyIdentity.length > EMPTY_IDENTITY_FIELDS.size) {
124
- throw new TypeError('Invalid explicit-empty identity marker');
125
- }
126
- const fields = new Set();
127
- for (const field of value.explicitEmptyIdentity) {
128
- if (typeof field !== 'string' || !EMPTY_IDENTITY_FIELDS.has(field)) {
129
- throw new TypeError('Invalid explicit-empty identity marker');
130
- }
131
- fields.add(field);
132
- }
133
- if (fields.size) {
134
- payload.explicitEmptyIdentity = [...fields];
135
- }
136
- }
137
- if (Array.isArray(value.resolutions)) {
138
- payload.resolutions = value.resolutions.map((resolution) => {
139
- if (!isRecord(resolution) || typeof resolution.operationId !== 'string') {
140
- throw new TypeError('Invalid run recovery resolution');
141
- }
142
- if (resolution.decision === 'retry') {
143
- return { operationId: resolution.operationId, decision: 'retry' };
144
- }
145
- if (resolution.decision === 'result' && 'result' in resolution) {
146
- return {
147
- operationId: resolution.operationId,
148
- decision: 'result',
149
- result: resolution.result
150
- };
151
- }
152
- if (resolution.decision === 'skip') {
153
- return { operationId: resolution.operationId, decision: 'skip' };
154
- }
155
- throw new TypeError('Invalid run recovery resolution');
156
- });
157
- }
158
- if (isRecord(value.knowledge)) {
159
- payload.knowledge = knowledgeGrant(value.knowledge);
160
- }
161
- if (value.planMode === true) {
162
- payload.planMode = true;
163
- }
164
- if (value.deferTools === true) {
165
- payload.deferTools = true;
166
- }
167
- if (typeof value.parentRunId === 'string') {
168
- payload.parentRunId = value.parentRunId;
169
- }
170
- if (isRecord(value.goal)) {
171
- payload.goal = goalFrom(value.goal);
172
- }
173
- if (typeof value.typedText === 'string') {
174
- payload.typedText = value.typedText;
175
- }
176
- if (typeof value.maxToolRounds === 'number') {
177
- payload.maxToolRounds = checkMaxToolRounds(value.maxToolRounds);
178
- }
179
- if (value.replaysContext === true) {
180
- payload.replaysContext = true;
181
- }
182
- if (value.modelRound === true) {
183
- payload.modelRound = true;
184
- }
185
- if (value.roundCut === true) {
186
- payload.roundCut = true;
187
- }
188
- if (value.showImage === true) {
189
- payload.showImage = true;
190
- }
191
- if (value.mediaRound === true) {
192
- payload.mediaRound = true;
193
- }
194
- if (value.runLog === null) {
195
- payload.runLog = null;
196
- }
197
- else if (value.runLog) {
198
- const runLog = isRecord(value.runLog) ? value.runLog : {};
199
- payload.runLog = {
200
- boot: runLog.boot,
201
- digestKey: runLog.digestKey,
202
- hostAppendTimeoutMs: typeof runLog.hostAppendTimeoutMs === 'number' ? runLog.hostAppendTimeoutMs : undefined
203
- };
204
- }
205
- return payload;
206
- }
207
- function assertEmptyIdentityMarkersMatchFrame(frame, fields) {
208
- for (const field of fields) {
209
- let value;
210
- switch (field) {
211
- case 'model':
212
- value = frame.model;
213
- break;
214
- case 'cacheKey':
215
- value = frame.cacheKey;
216
- break;
217
- case 'thinkingDefault':
218
- value = frame.thinkingDefault;
219
- break;
220
- case 'agent.id':
221
- if (frame.agent === null || frame.agent === undefined) {
222
- throw new TypeError('Explicit-empty agent identity requires an agent frame');
223
- }
224
- value = frame.agent?.id;
225
- break;
226
- case 'agent.name':
227
- if (frame.agent === null || frame.agent === undefined) {
228
- throw new TypeError('Explicit-empty agent identity requires an agent frame');
229
- }
230
- value = frame.agent?.name;
231
- break;
232
- case 'agent.bio':
233
- if (frame.agent === null || frame.agent === undefined) {
234
- throw new TypeError('Explicit-empty agent identity requires an agent frame');
235
- }
236
- value = frame.agent?.bio;
237
- break;
238
- }
239
- if (value !== null && value !== undefined && value !== '') {
240
- throw new TypeError('Conflicting explicit-empty identity marker');
241
- }
242
- }
243
- }
244
- function normalizeAgentKnobs(agent) {
245
- const normalized = { ...agent };
246
- if (normalized.id === null || normalized.id === undefined) {
247
- delete normalized.id;
248
- }
249
- if (normalized.name === null || normalized.name === undefined) {
250
- delete normalized.name;
251
- }
252
- if (normalized.bio === null || normalized.bio === undefined) {
253
- delete normalized.bio;
254
- }
255
- if (normalized.handoffs === null || normalized.handoffs === undefined) {
256
- delete normalized.handoffs;
257
- }
258
- if (normalized.model === null || normalized.model === undefined) {
259
- delete normalized.model;
260
- }
261
- if (normalized.policy === null || normalized.policy === undefined) {
262
- delete normalized.policy;
263
- }
264
- Reflect.deleteProperty(normalized, 'sandboxMode');
265
- return normalized;
266
- }
267
- function tick() {
268
- return new Promise((resolve) => setTimeout(resolve, 0));
269
- }
270
- export function serveHarness(stream, harness) {
12
+ import { Wire } from './wire.js';
13
+ import { noop } from './serve/noop.js';
14
+ import { toWireSkill, unsupportedKnowledge, unsupportedEmbeddingDeviceControl } from './serve/skills.js';
15
+ import { modelEvents, speakStream } from './serve/models.js';
16
+ import { completion } from './serve/completion.js';
17
+ import { downloadStream } from './serve/downloads.js';
18
+ function serveHarness(stream, harness) {
271
19
  sweepStaging();
272
20
  sweepSpill();
273
21
  prepareOpenclCache();
@@ -364,7 +112,7 @@ export function serveHarness(stream, harness) {
364
112
  if (!harness.embed) {
365
113
  throw new HarnessError('CAPABILITY_UNSUPPORTED', ['embed']);
366
114
  }
367
- return packVectors(await harness.embed({ model, texts: texts ?? [] }));
115
+ return Wire.packVectors(await harness.embed({ model, texts: texts ?? [] }));
368
116
  },
369
117
  transcribe: async ({ model, audio }) => {
370
118
  if (!harness.transcribe) {
@@ -379,7 +127,7 @@ export function serveHarness(stream, harness) {
379
127
  throw new HarnessError('CAPABILITY_UNSUPPORTED', ['ocr']);
380
128
  }
381
129
  const image = { width: width ?? 0, height: height ?? 0, data: data ?? b4a.alloc(0) };
382
- return { text: await harness.ocrRead({ image }) };
130
+ return await harness.ocrRead({ image });
383
131
  },
384
132
  detectLanguage: async ({ text, topK }) => {
385
133
  if (!harness.detectLanguage) {
@@ -465,7 +213,7 @@ export function serveHarness(stream, harness) {
465
213
  if (!harness.knowledgeUpsert) {
466
214
  throw unsupportedKnowledge();
467
215
  }
468
- return toKnowledgeUpsertResultWire(await harness.knowledgeUpsert(fromKnowledgeUpsertWire(req)));
216
+ return Wire.toKnowledgeUpsertResultWire(await harness.knowledgeUpsert(Wire.fromKnowledgeUpsertWire(req)));
469
217
  },
470
218
  knowledgeRemove: async ({ artifactId }) => {
471
219
  if (!harness.knowledgeRemove) {
@@ -495,811 +243,6 @@ export function serveHarness(stream, harness) {
495
243
  out.writeStream?.on('close', () => src.destroy());
496
244
  });
497
245
  }
498
- function toWireSkill(skill) {
499
- const setupV2 = toWireSetup(readSetup(skill.setup));
500
- const binaries = (skill.requires?.bins ?? []).map((bin) => ({
501
- bin,
502
- minVersion: skill.requires?.binMinVersions?.[bin]?.min,
503
- command: skill.requires?.binMinVersions?.[bin]?.command
504
- }));
505
- return {
506
- name: skill.name,
507
- displayName: skill.displayName || undefined,
508
- description: skill.description,
509
- tools: skill.tools,
510
- credentials: skill.credentials,
511
- allowList: skill.allowList,
512
- platforms: skill.platform,
513
- status: skill.status,
514
- requirements: skill.requires
515
- ? { binaries, credentials: skill.requires.credentials ?? [] }
516
- : undefined,
517
- install: skill.install || undefined,
518
- setup: skill.setup || undefined,
519
- setupV2,
520
- stub: skill.stub,
521
- minCapabilityProfile: skill.minCapabilityProfile || undefined,
522
- emoji: skill.emoji || undefined
523
- };
524
- }
525
- function unsupportedKnowledge() {
526
- return new Error('harness does not support knowledge');
527
- }
528
- function unsupportedEmbeddingDeviceControl() {
529
- return new HarnessError('CAPABILITY_UNSUPPORTED', ['embedding device control']);
530
- }
531
- function modelEvents(harness) {
532
- let last = '';
533
- let pendingProgress = null;
534
- let lastProgressAt = 0;
535
- const flushProgress = (at) => {
536
- if (pendingProgress === null)
537
- return;
538
- stream.push(pendingProgress);
539
- pendingProgress = null;
540
- lastProgressAt = at;
541
- };
542
- const onModel = (state) => {
543
- if (!MODEL_STATUSES.has(state.status))
544
- return;
545
- const percentage = Math.floor(state.percentage ?? 0);
546
- const downloaded = Math.floor(state.downloaded ?? 0);
547
- const total = Math.floor(state.total ?? 0);
548
- const loaded = state.loaded ?? [];
549
- const catalogChanged = state.catalogChanged === true;
550
- const key = [
551
- state.status,
552
- state.model ?? '',
553
- percentage,
554
- downloaded,
555
- total,
556
- state.message ?? '',
557
- catalogChanged,
558
- ...loaded.map((entry) => `${entry.model}:${entry.refs}`)
559
- ].join('\0');
560
- if (key === last && !catalogChanged) {
561
- return;
562
- }
563
- last = key;
564
- const frame = encodableModelEvent({
565
- status: state.status,
566
- model: state.model,
567
- percentage,
568
- downloaded,
569
- total,
570
- message: state.message,
571
- catalogChanged,
572
- loaded,
573
- addon: state.addon
574
- });
575
- const now = Date.now();
576
- if (frame.status === 'downloading') {
577
- pendingProgress = frame;
578
- if (lastProgressAt === 0 || now - lastProgressAt >= DOWNLOAD_PROGRESS_INTERVAL_MS) {
579
- flushProgress(now);
580
- }
581
- return;
582
- }
583
- flushProgress(now);
584
- lastProgressAt = 0;
585
- stream.push(frame);
586
- };
587
- const stream = new Readable({
588
- open(cb) {
589
- harness.on?.('model', onModel);
590
- cb(null);
591
- },
592
- destroy(cb) {
593
- harness.off?.('model', onModel);
594
- cb(null);
595
- }
596
- });
597
- return stream;
598
- }
599
- function encodableModelEvent(frame) {
600
- try {
601
- encode('@harness/model-event', frame);
602
- return frame;
603
- }
604
- catch (err) {
605
- return { status: 'error', message: `cannot encode model event: ${errorMessage(err)}` };
606
- }
607
- }
608
- function speakStream(harness) {
609
- return async function* (duplex) {
610
- if (!harness.speakStream) {
611
- throw new HarnessError('CAPABILITY_UNSUPPORTED', ['speakStream']);
612
- }
613
- const text = pushQueue();
614
- const end = () => text.end();
615
- duplex.on('close', end);
616
- duplex.on('end', end);
617
- duplex.readStream?.on('close', end);
618
- duplex.on('data', (frame) => {
619
- if (frame.text) {
620
- text.push(frame.text);
621
- }
622
- });
623
- for await (const chunk of harness.speakStream({ model: '', text })) {
624
- const frame = { audio: chunk.audio, sampleRate: chunk.sampleRate };
625
- try {
626
- encode('@harness/speak-response', frame);
627
- }
628
- catch (err) {
629
- throw new Error(`cannot encode speak frame: ${errorMessage(err)}`);
630
- }
631
- yield frame;
632
- }
633
- };
634
- }
635
- function runFrame(harness, frame, context) {
636
- if (frame.type !== 'invoke') {
637
- return harness.completion(context);
638
- }
639
- if (!harness.invoke) {
640
- throw new HarnessError('CAPABILITY_UNSUPPORTED', ['invoke']);
641
- }
642
- const capability = frame.capability ?? '';
643
- if (!isCapability(capability)) {
644
- throw new HarnessError('UNKNOWN_CAPABILITY', [capability]);
645
- }
646
- return harness.invoke({
647
- capability,
648
- args: frame.arguments ?? {},
649
- enhance: frame.enhance === 'auto' ? 'auto' : 'never',
650
- agent: frame.agent ?? undefined,
651
- attach: context.attach,
652
- fetchAttachment: context.fetchAttachment,
653
- progress: context.progress,
654
- signal: context.signal
655
- });
656
- }
657
- function completion(harness) {
658
- let writeTurn = Promise.resolve();
659
- const waitForWriteTurn = () => (writeTurn = writeTurn.then(tick));
660
- return async function* (duplex) {
661
- const events = pushQueue({ highWaterMark: WIRE_HIGH_WATER_MARK });
662
- const pending = new Map();
663
- const pendingAttach = new Map();
664
- const pendingFetch = new Map();
665
- const pendingShow = new Map();
666
- const pendingQuestion = new Map();
667
- const pendingDrive = new Map();
668
- const pendingRunLog = new Map();
669
- const input = pushQueue();
670
- const controller = new AbortController();
671
- const rounds = new RoundPort((event) => events.push(event));
672
- const media = new MediaPort((event) => events.push(event));
673
- let calls = 0;
674
- let started = false;
675
- let clientGone = false;
676
- const gone = () => {
677
- clientGone = true;
678
- controller.abort('client gone');
679
- for (const resolve of pending.values()) {
680
- resolve(false);
681
- }
682
- pending.clear();
683
- for (const { reject, staged } of pendingAttach.values()) {
684
- void fs.promises.unlink(staged).catch(noop);
685
- reject(new HarnessError('CLIENT_GONE'));
686
- }
687
- pendingAttach.clear();
688
- for (const { reject } of pendingFetch.values()) {
689
- reject(new HarnessError('CLIENT_GONE'));
690
- }
691
- pendingFetch.clear();
692
- for (const { reject } of pendingShow.values()) {
693
- reject(new HarnessError('CLIENT_GONE'));
694
- }
695
- pendingShow.clear();
696
- for (const { resolve } of pendingQuestion.values()) {
697
- resolve(null);
698
- }
699
- pendingQuestion.clear();
700
- for (const { reject, path } of pendingDrive.values()) {
701
- if (path) {
702
- void fs.promises.unlink(path).catch(noop);
703
- }
704
- reject(new HarnessError('CLIENT_GONE'));
705
- }
706
- pendingDrive.clear();
707
- for (const { reject } of pendingRunLog.values()) {
708
- reject(new HarnessError('CLIENT_GONE'));
709
- }
710
- pendingRunLog.clear();
711
- rounds.close();
712
- media.close();
713
- input.end();
714
- events.end();
715
- };
716
- duplex.on('close', gone);
717
- duplex.on('end', gone);
718
- duplex.readStream?.on('close', gone);
719
- duplex.on('data', (frame) => {
720
- if (rounds.frame(frame) || media.frame(frame)) {
721
- return;
722
- }
723
- if (frame.type === 'media-round-ask' && !started) {
724
- started = true;
725
- void serveMedia(harness, frame.payload, { signal: controller.signal, events });
726
- return;
727
- }
728
- if (frame.type === 'model-round-ask' && !started) {
729
- started = true;
730
- void serveRound(harness, frame.payload, {
731
- signal: controller.signal,
732
- events
733
- });
734
- return;
735
- }
736
- if (frame.type === 'decision') {
737
- if (typeof frame.callId !== 'string') {
738
- return;
739
- }
740
- pending.get(frame.callId)?.(frame.approved === true);
741
- pending.delete(frame.callId);
742
- return;
743
- }
744
- if (frame.type === 'attach-result') {
745
- if (typeof frame.callId !== 'string') {
746
- return;
747
- }
748
- const waiter = pendingAttach.get(frame.callId);
749
- pendingAttach.delete(frame.callId);
750
- if (!waiter) {
751
- return;
752
- }
753
- void fs.promises.unlink(waiter.staged).catch(noop);
754
- if (frame.attachment) {
755
- waiter.resolve(frame.attachment);
756
- }
757
- else {
758
- waiter.reject(new Error(frame.message || 'the host failed to store the attachment'));
759
- }
760
- return;
761
- }
762
- if (frame.type === 'fetch-result') {
763
- if (typeof frame.callId !== 'string') {
764
- return;
765
- }
766
- const shown = pendingShow.get(frame.callId);
767
- if (shown) {
768
- pendingShow.delete(frame.callId);
769
- return frame.message
770
- ? shown.reject(new Error(frame.message))
771
- : shown.resolve(frame.path || null);
772
- }
773
- const waiter = pendingFetch.get(frame.callId);
774
- pendingFetch.delete(frame.callId);
775
- if (!waiter) {
776
- return;
777
- }
778
- if (frame.message) {
779
- return waiter.reject(new Error(frame.message));
780
- }
781
- const staged = frame.path;
782
- const { fileName, mimeType, attachmentId, size } = frame;
783
- if (frame.meta === true) {
784
- return waiter.resolve({
785
- id: attachmentId ?? '',
786
- fileName: fileName ?? '',
787
- mimeType: mimeType ?? '',
788
- byteLength: typeof size === 'number' ? size : 0
789
- });
790
- }
791
- if (!staged) {
792
- return waiter.resolve(null);
793
- }
794
- fs.promises.readFile(staged).then((bytes) => waiter.resolve({
795
- id: attachmentId ?? '',
796
- fileName: fileName ?? '',
797
- mimeType: mimeType ?? '',
798
- byteLength: typeof size === 'number' ? size : bytes.byteLength,
799
- bytes
800
- }), (err) => waiter.reject(err));
801
- return;
802
- }
803
- if (frame.type === 'question-result') {
804
- if (typeof frame.callId !== 'string') {
805
- return;
806
- }
807
- const waiter = pendingQuestion.get(frame.callId);
808
- pendingQuestion.delete(frame.callId);
809
- if (!waiter) {
810
- return;
811
- }
812
- if (frame.message) {
813
- HarnessLog.warn('question failed', { callId: frame.callId, message: frame.message });
814
- }
815
- waiter.resolve(frame.answer || null);
816
- return;
817
- }
818
- if (frame.type === 'drive-result') {
819
- if (typeof frame.callId !== 'string') {
820
- return;
821
- }
822
- const waiter = pendingDrive.get(frame.callId);
823
- pendingDrive.delete(frame.callId);
824
- if (!waiter) {
825
- return;
826
- }
827
- if (frame.message) {
828
- return waiter.reject(new Error(frame.message));
829
- }
830
- waiter.resolve(frame.payload ?? {});
831
- return;
832
- }
833
- if (frame.type === 'pause') {
834
- controller.abort('paused');
835
- return;
836
- }
837
- if (frame.type === 'steer' || frame.type === 'follow-up') {
838
- void input.push({
839
- mode: frame.type,
840
- text: frame.messages?.[0]?.content ?? '',
841
- id: frame.callId || undefined
842
- });
843
- return;
844
- }
845
- if (frame.type === 'run-log-result') {
846
- if (typeof frame.callId !== 'string') {
847
- return;
848
- }
849
- const waiter = pendingRunLog.get(frame.callId);
850
- pendingRunLog.delete(frame.callId);
851
- if (!waiter) {
852
- return;
853
- }
854
- if (frame.message) {
855
- return waiter.reject(new Error(frame.message));
856
- }
857
- waiter.resolve();
858
- return;
859
- }
860
- if (started || (frame.type !== 'start' && frame.type !== 'invoke')) {
861
- return;
862
- }
863
- started = true;
864
- let startPayload;
865
- try {
866
- startPayload = startPayloadFrom(frame.payload);
867
- if (startPayload.goal) {
868
- checkGoal(startPayload.goal, frame.responseFormat);
869
- }
870
- assertEmptyIdentityMarkersMatchFrame(frame, startPayload.explicitEmptyIdentity ?? []);
871
- }
872
- catch (err) {
873
- events.push({ type: 'error', message: errorMessage(err) });
874
- events.push({ type: 'done' });
875
- events.end();
876
- return;
877
- }
878
- const explicitEmptyIdentity = new Set(startPayload.explicitEmptyIdentity ?? []);
879
- const runLog = startPayload.runLog;
880
- const resuming = startPayload.resume === true ||
881
- Boolean(isEngineBoot(runLog?.boot) && runLog.boot.metadata !== null);
882
- const requestDigestKey = runLog ? decodeDigestKey(runLog.digestKey) : undefined;
883
- const agent = normalizeAgentKnobs(frame.agent ?? {});
884
- if ((frame.agent?.id === null || frame.agent?.id === undefined) &&
885
- explicitEmptyIdentity.has('agent.id')) {
886
- agent.id = '';
887
- }
888
- if ((frame.agent?.name === null || frame.agent?.name === undefined) &&
889
- explicitEmptyIdentity.has('agent.name')) {
890
- agent.name = '';
891
- }
892
- if ((frame.agent?.bio === null || frame.agent?.bio === undefined) &&
893
- explicitEmptyIdentity.has('agent.bio')) {
894
- agent.bio = '';
895
- }
896
- const onStep = runLog
897
- ? (step) => {
898
- if (clientGone) {
899
- return Promise.reject(new HarnessError('CLIENT_GONE'));
900
- }
901
- return new Promise((resolve, reject) => {
902
- const callId = String(calls++);
903
- pendingRunLog.set(callId, { resolve, reject });
904
- events.push({ type: 'run-log-append', callId, payload: step });
905
- });
906
- }
907
- : undefined;
908
- const context = {
909
- runId: frame.runId || undefined,
910
- resume: resuming,
911
- recovery: startPayload.resolutions ?? undefined,
912
- boot: isEngineBoot(runLog?.boot) ? runLog.boot : undefined,
913
- onStep,
914
- requestDigestKey,
915
- hostAppendTimeoutMs: runLog?.hostAppendTimeoutMs,
916
- model: frame.model ?? '',
917
- agent,
918
- cacheKey: frame.cacheKey ?? (explicitEmptyIdentity.has('cacheKey') ? '' : undefined),
919
- session: frame.session ?? undefined,
920
- thinkingDefault: frame.thinkingDefault ?? (explicitEmptyIdentity.has('thinkingDefault') ? '' : undefined),
921
- generationParams: frame.generationParams ?? undefined,
922
- responseFormat: frame.responseFormat ?? undefined,
923
- captureInferenceCalls: frame.captureInferenceCalls ?? undefined,
924
- maxToolRounds: startPayload.maxToolRounds,
925
- typedText: startPayload.typedText,
926
- replaysContext: startPayload.replaysContext,
927
- modelRound: startPayload.modelRound ? rounds.port : undefined,
928
- mediaRound: startPayload.mediaRound ? media.port : undefined,
929
- roundCut: startPayload.roundCut ? rounds.roundCut : undefined,
930
- knowledge: startPayload.knowledge,
931
- planMode: startPayload.planMode,
932
- deferTools: startPayload.deferTools,
933
- parentRunId: startPayload.parentRunId,
934
- goal: startPayload.goal,
935
- messages: (frame.messages ?? []).map(({ role, content, attachments, toolCalls, toolCallId, name, id, context: added, sentAt }) => ({
936
- role,
937
- content,
938
- attachments: attachments?.length
939
- ? attachments.map(({ path: file }) => ({ path: file }))
940
- : undefined,
941
- toolCalls: toolCalls ?? undefined,
942
- toolCallId: toolCallId ?? undefined,
943
- name: name ?? undefined,
944
- id: id || undefined,
945
- context: added ?? undefined,
946
- sentAt: sentAt || undefined
947
- })),
948
- toolConfigs: frame.toolConfigs ?? undefined,
949
- grantedDirs: frame.grantedDirs ?? undefined,
950
- grantedDrives: frame.grantedDrives?.length
951
- ? frame.grantedDrives.map((drive) => ({
952
- key: drive.key,
953
- writable: drive.writable === true,
954
- search: drive.search === true
955
- }))
956
- : undefined,
957
- driveOp: frame.grantedDrives?.length
958
- ? (request) => controller.signal.aborted
959
- ? Promise.reject(new HarnessError('CLIENT_GONE'))
960
- : new Promise((resolve, reject) => {
961
- const callId = String(calls++);
962
- pendingDrive.set(callId, {
963
- resolve,
964
- reject,
965
- path: request.op === 'write' ? request.path : undefined
966
- });
967
- events.push({ type: 'drive-ask', callId, op: request.op, payload: request });
968
- })
969
- : undefined,
970
- grantedWriteDirs: frame.grantedWriteDirs ?? undefined,
971
- signal: controller.signal,
972
- input,
973
- approve: (call) => new Promise((resolve) => {
974
- const callId = String(calls++);
975
- pending.set(callId, resolve);
976
- const frame = {
977
- type: 'approval-ask',
978
- callId,
979
- name: call.name,
980
- arguments: call.arguments,
981
- resource: call.resource ?? undefined,
982
- effect: call.effect,
983
- intent: call.intent ?? undefined,
984
- display: call.display ?? undefined,
985
- question: call.quote ?? undefined
986
- };
987
- if (call.callId !== undefined || call.round !== undefined) {
988
- frame.payload = { callId: call.callId, round: call.round };
989
- }
990
- events.push(frame);
991
- }),
992
- attach: async (input) => {
993
- const staged = await stageFile('attach', input.bytes);
994
- if (controller.signal.aborted) {
995
- void fs.promises.unlink(staged).catch(noop);
996
- throw new HarnessError('CLIENT_GONE');
997
- }
998
- return new Promise((resolve, reject) => {
999
- const callId = String(calls++);
1000
- pendingAttach.set(callId, { resolve, reject, staged });
1001
- events.push({
1002
- type: 'attach-ask',
1003
- callId,
1004
- path: staged,
1005
- fileName: input.fileName,
1006
- mimeType: input.mimeType,
1007
- raw: input.raw ?? false
1008
- });
1009
- });
1010
- },
1011
- fetchAttachment: ({ attachmentId, meta } = {}) => controller.signal.aborted
1012
- ? Promise.reject(new HarnessError('CLIENT_GONE'))
1013
- : new Promise((resolve, reject) => {
1014
- const callId = String(calls++);
1015
- pendingFetch.set(callId, { resolve, reject });
1016
- events.push({
1017
- type: 'fetch-ask',
1018
- callId,
1019
- attachmentId,
1020
- meta: meta === true ? true : undefined
1021
- });
1022
- }),
1023
- showImage: startPayload.showImage
1024
- ? ({ attachmentId }) => controller.signal.aborted
1025
- ? Promise.reject(new HarnessError('CLIENT_GONE'))
1026
- : new Promise((resolve, reject) => {
1027
- const callId = String(calls++);
1028
- pendingShow.set(callId, { resolve, reject });
1029
- events.push({
1030
- type: 'fetch-ask',
1031
- callId,
1032
- attachmentId,
1033
- payload: { show: true }
1034
- });
1035
- })
1036
- : undefined,
1037
- progress: (update) => {
1038
- events.push(update
1039
- ? { type: 'progress', percentage: update.percentage }
1040
- : { type: 'progress', cleared: true });
1041
- },
1042
- askUser: (question) => controller.signal.aborted
1043
- ? Promise.resolve(null)
1044
- : new Promise((resolve, reject) => {
1045
- const callId = String(calls++);
1046
- pendingQuestion.set(callId, { resolve, reject });
1047
- events.push({
1048
- type: 'question-ask',
1049
- callId,
1050
- question: question.question,
1051
- options: question.options,
1052
- payload: question.form
1053
- });
1054
- })
1055
- };
1056
- if (resuming) {
1057
- for (const key of [
1058
- 'model',
1059
- 'agent',
1060
- 'messages',
1061
- 'cacheKey',
1062
- 'thinkingDefault',
1063
- 'generationParams',
1064
- 'responseFormat'
1065
- ]) {
1066
- const value = frame[key];
1067
- const explicitEmpty = (key === 'model' &&
1068
- (frame.model === null || frame.model === undefined) &&
1069
- explicitEmptyIdentity.has('model')) ||
1070
- (key === 'cacheKey' &&
1071
- (frame.cacheKey === null || frame.cacheKey === undefined) &&
1072
- explicitEmptyIdentity.has('cacheKey')) ||
1073
- (key === 'thinkingDefault' &&
1074
- (frame.thinkingDefault === null || frame.thinkingDefault === undefined) &&
1075
- explicitEmptyIdentity.has('thinkingDefault'));
1076
- if ((value === null || value === undefined || value === '') && !explicitEmpty) {
1077
- const mutableContext = context;
1078
- delete mutableContext[key];
1079
- }
1080
- }
1081
- }
1082
- void (async () => {
1083
- let produced = 0;
1084
- let frames = 0;
1085
- const textIdentity = {};
1086
- const text = new TextCoalescer((type, merged) => {
1087
- frames++;
1088
- return events.push({ type, text: merged, ...textIdentity });
1089
- }, { cap: TEXT_COALESCE_CAP, holdMs: TEXT_COALESCE_MS });
1090
- try {
1091
- if (runLog && !requestDigestKey) {
1092
- throw new Error('The host did not provide a valid run-log digest key');
1093
- }
1094
- if (runLog?.boot &&
1095
- (!isEngineBoot(runLog.boot) ||
1096
- (runLog.boot.metadata !== null && runLog.boot.metadata.runId !== frame.runId))) {
1097
- throw new Error('The host did not provide a valid run-log boot');
1098
- }
1099
- if (resuming && !onStep && !(await harness.capability?.())?.completionRecovery) {
1100
- throw new Error('This peer does not support persistent completion recovery');
1101
- }
1102
- for await (const event of runFrame(harness, frame, context)) {
1103
- produced++;
1104
- if (!startPayload.recoveryEvents &&
1105
- ['run-started', 'run-resumed', 'round-reset', 'recovery-required'].includes(event.type)) {
1106
- continue;
1107
- }
1108
- const wire = !startPayload.recoveryEvents && event.type === 'paused'
1109
- ? { type: 'aborted' }
1110
- : toWire(event);
1111
- if (await accumulateTextFrame(wire, textIdentity, text)) {
1112
- continue;
1113
- }
1114
- await text.flush();
1115
- frames++;
1116
- await events.push(wire);
1117
- }
1118
- await text.flush();
1119
- }
1120
- catch (err) {
1121
- await text.flush();
1122
- events.push({ type: 'error', message: errorMessage(err) });
1123
- }
1124
- input.end();
1125
- events.push({ type: 'done' });
1126
- HarnessLog.debug('wire end', { produced, frames });
1127
- events.end();
1128
- })();
1129
- });
1130
- for await (const event of events) {
1131
- try {
1132
- encode('@harness/completion-event', event);
1133
- }
1134
- catch (err) {
1135
- await waitForWriteTurn();
1136
- yield { type: 'error', message: `cannot encode ${event.type} event: ${errorMessage(err)}` };
1137
- await waitForWriteTurn();
1138
- yield { type: 'done' };
1139
- await waitForWriteTurn();
1140
- gone();
1141
- return;
1142
- }
1143
- await waitForWriteTurn();
1144
- yield event;
1145
- }
1146
- await waitForWriteTurn();
1147
- HarnessLog.info('wire handed off');
1148
- };
1149
- }
1150
- async function serveMedia(harness, payload, { signal, events }) {
1151
- let settled;
1152
- try {
1153
- if (!harness.serveMediaRound) {
1154
- throw new HarnessError('CAPABILITY_UNSUPPORTED', ['serveMediaRound']);
1155
- }
1156
- const result = await harness.serveMediaRound(await mediaRequestFrom(payload), {
1157
- signal,
1158
- tick: (tick) => void events.push({ type: 'media-round-tick', payload: tick })
1159
- });
1160
- if (signal.aborted) {
1161
- throw new AbortedError();
1162
- }
1163
- settled = { type: 'media-round-result', ...(await mediaResultWire(result)) };
1164
- }
1165
- catch (err) {
1166
- settled = { type: 'media-round-result', ...roundFailureWire(err) };
1167
- }
1168
- await events.push(settled);
1169
- await events.push({ type: 'done' });
1170
- events.end();
1171
- }
1172
- async function serveRound(harness, request, { signal, events }) {
1173
- let sent = Promise.resolve();
1174
- const queue = (step) => {
1175
- sent = sent.then(step).then(noop);
1176
- };
1177
- const text = new TextCoalescer((type, merged) => events.push({ type, text: merged }), {
1178
- cap: TEXT_COALESCE_CAP,
1179
- holdMs: TEXT_COALESCE_MS
1180
- });
1181
- const emit = (event) => queue(() => text.add(event.type, event.text));
1182
- const retake = () => {
1183
- queue(async () => {
1184
- await text.flush();
1185
- await events.push({ type: 'model-round-retake' });
1186
- });
1187
- return emit;
1188
- };
1189
- let settled;
1190
- try {
1191
- if (!harness.serveModelRound) {
1192
- throw new HarnessError('CAPABILITY_UNSUPPORTED', ['serveModelRound']);
1193
- }
1194
- const result = await harness.serveModelRound(roundRequestFrom(request), {
1195
- signal,
1196
- emit,
1197
- retake
1198
- });
1199
- settled = { type: 'model-round-result', result };
1200
- }
1201
- catch (err) {
1202
- settled = { type: 'model-round-result', ...roundFailureWire(err) };
1203
- }
1204
- queue(() => text.flush());
1205
- await sent;
1206
- events.push(settled);
1207
- events.push({ type: 'done' });
1208
- events.end();
1209
- }
1210
- function encodableDownloadEvent(wire) {
1211
- try {
1212
- encode('@harness/download-event', wire);
1213
- }
1214
- catch (err) {
1215
- throw new Error(`cannot encode ${wire.type} event: ${errorMessage(err)}`);
1216
- }
1217
- return wire;
1218
- }
1219
- async function accumulateTextFrame(wire, identity, text) {
1220
- if ((wire.type !== 'content' && wire.type !== 'thinking') || !wire.text) {
1221
- return false;
1222
- }
1223
- if (identity.runId !== wire.runId || identity.round !== wire.round) {
1224
- await text.flush();
1225
- }
1226
- identity.runId = wire.runId;
1227
- identity.round = wire.round;
1228
- await text.add(wire.type, wire.text);
1229
- return true;
1230
- }
1231
- function downloadStream(harness, req) {
1232
- const controller = new AbortController();
1233
- const stream = new Readable({
1234
- open(cb) {
1235
- void run();
1236
- cb(null);
1237
- },
1238
- destroy(cb) {
1239
- controller.abort('client gone');
1240
- cb(null);
1241
- }
1242
- });
1243
- const run = async () => {
1244
- if (!harness.download) {
1245
- stream.push({
1246
- type: 'error',
1247
- message: 'harness does not support download'
1248
- });
1249
- stream.push(null);
1250
- return;
1251
- }
1252
- let pendingProgress = null;
1253
- let lastProgressAt = 0;
1254
- const flushProgress = (at = Date.now()) => {
1255
- if (pendingProgress === null)
1256
- return;
1257
- stream.push(pendingProgress);
1258
- pendingProgress = null;
1259
- lastProgressAt = at;
1260
- };
1261
- const queueProgress = (wire) => {
1262
- const now = Date.now();
1263
- pendingProgress = wire;
1264
- if (lastProgressAt === 0 || now - lastProgressAt >= DOWNLOAD_PROGRESS_INTERVAL_MS) {
1265
- flushProgress(now);
1266
- }
1267
- };
1268
- try {
1269
- for await (const event of harness.download({
1270
- model: req.model,
1271
- addon: req.addon,
1272
- seed: req.seed,
1273
- signal: controller.signal
1274
- })) {
1275
- const wire = encodableDownloadEvent(toDownloadWire(event));
1276
- if (wire.type === 'progress') {
1277
- queueProgress(wire);
1278
- continue;
1279
- }
1280
- flushProgress();
1281
- stream.push(wire);
1282
- }
1283
- flushProgress();
1284
- }
1285
- catch (err) {
1286
- if (!controller.signal.aborted) {
1287
- flushProgress();
1288
- stream.push({ type: 'error', message: errorMessage(err) });
1289
- }
1290
- }
1291
- stream.push(null);
1292
- };
1293
- return stream;
1294
- }
1295
- function knowledgeGrant({ scopes, focus, k }) {
1296
- if (!isStrings(scopes) ||
1297
- (focus !== undefined && !isStrings(focus)) ||
1298
- (k !== undefined && !(typeof k === 'number' && Number.isSafeInteger(k) && k > 0))) {
1299
- throw new TypeError('Invalid knowledge grant');
1300
- }
1301
- return { scopes, focus, k };
1302
- }
1303
- function isStrings(value) {
1304
- return Array.isArray(value) && value.every((item) => typeof item === 'string');
246
+ export class HarnessServer {
247
+ static serve = serveHarness;
1305
248
  }