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

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 (145) hide show
  1. package/CHANGELOG.md +139 -2
  2. package/dist-lib/index.d.ts +6 -1
  3. package/dist-lib/index.js +17 -3
  4. package/dist-lib/lib/capabilities/completion-engine/actors/executing.d.ts +2 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +28 -3
  6. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +3 -0
  7. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.d.ts +1 -1
  8. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.js +13 -8
  9. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +6 -3
  10. package/dist-lib/lib/capabilities/completion-engine/actors/run-prepare.js +1 -1
  11. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +2 -2
  12. package/dist-lib/lib/capabilities/completion-engine/durable.d.ts +2 -1
  13. package/dist-lib/lib/capabilities/completion-engine/durable.js +7 -1
  14. package/dist-lib/lib/capabilities/completion-engine/engine.js +23 -39
  15. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +2 -1
  16. package/dist-lib/lib/capabilities/completion-engine/operations.js +28 -9
  17. package/dist-lib/lib/capabilities/completion-engine/ports.js +3 -2
  18. package/dist-lib/lib/capabilities/completion-engine/prepare-step.d.ts +3 -1
  19. package/dist-lib/lib/capabilities/completion-engine/session.d.ts +1 -0
  20. package/dist-lib/lib/capabilities/completion-engine/session.js +1 -0
  21. package/dist-lib/lib/capabilities/completion-engine/tool-execution.js +2 -1
  22. package/dist-lib/lib/capabilities/completion-engine/turns.js +5 -2
  23. package/dist-lib/lib/capabilities/enhance.js +3 -3
  24. package/dist-lib/lib/capabilities/sdk-tool.d.ts +1 -1
  25. package/dist-lib/lib/capabilities/sdk-tool.js +3 -2
  26. package/dist-lib/lib/capabilities/skill-entry.d.ts +9 -1
  27. package/dist-lib/lib/capabilities/skill-entry.js +11 -7
  28. package/dist-lib/lib/capabilities/tool-turns.d.ts +5 -0
  29. package/dist-lib/lib/capabilities/tool-turns.js +24 -27
  30. package/dist-lib/lib/client/index.js +3 -2
  31. package/dist-lib/lib/connect.d.ts +2 -0
  32. package/dist-lib/lib/connect.js +33 -3
  33. package/dist-lib/lib/contract/completion.d.ts +17 -0
  34. package/dist-lib/lib/contract/exec.d.ts +1 -0
  35. package/dist-lib/lib/contract/models.d.ts +1 -1
  36. package/dist-lib/lib/contract/ocr.d.ts +13 -0
  37. package/dist-lib/lib/contract/ocr.js +1 -0
  38. package/dist-lib/lib/contract/run.d.ts +8 -0
  39. package/dist-lib/lib/contract-types.d.ts +4 -1
  40. package/dist-lib/lib/guards.d.ts +2 -0
  41. package/dist-lib/lib/guards.js +7 -0
  42. package/dist-lib/lib/hardware/capability-probe.js +10 -7
  43. package/dist-lib/lib/hardware/gpu-probe-addon.js +26 -11
  44. package/dist-lib/lib/hardware/gpu-stats.native.cjs +17 -1
  45. package/dist-lib/lib/helpers/completion-params.d.ts +2 -1
  46. package/dist-lib/lib/helpers/completion-params.js +16 -1
  47. package/dist-lib/lib/helpers/control-tokens.d.ts +3 -0
  48. package/dist-lib/lib/helpers/control-tokens.js +25 -0
  49. package/dist-lib/lib/machine/completion/actions/completion.js +34 -5
  50. package/dist-lib/lib/machine/completion/actions/tools.js +4 -1
  51. package/dist-lib/lib/machine/completion/rules.d.ts +2 -0
  52. package/dist-lib/lib/machine/completion/rules.js +7 -0
  53. package/dist-lib/lib/machine/completion/types.d.ts +6 -0
  54. package/dist-lib/lib/machine/index.d.ts +2 -1
  55. package/dist-lib/lib/machine/index.js +2 -1
  56. package/dist-lib/lib/models/gpu-selection.d.ts +6 -1
  57. package/dist-lib/lib/models/gpu-selection.js +29 -5
  58. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -1
  59. package/dist-lib/lib/no-redirect-fetch-impl.js +13 -7
  60. package/dist-lib/lib/plugins/registry.d.ts +5 -0
  61. package/dist-lib/lib/plugins/registry.js +15 -1
  62. package/dist-lib/lib/plugins/require-bare.d.ts +1 -0
  63. package/dist-lib/lib/plugins/require-bare.js +13 -0
  64. package/dist-lib/lib/run-log/request-codec.js +2 -2
  65. package/dist-lib/lib/serve.js +43 -35
  66. package/dist-lib/lib/sidecar/index.js +2 -1
  67. package/dist-lib/lib/skills-host/index.js +7 -1
  68. package/dist-lib/lib/spawn.d.ts +3 -0
  69. package/dist-lib/lib/spawn.js +5 -3
  70. package/dist-lib/lib/tools/ask-user.d.ts +2 -0
  71. package/dist-lib/lib/tools/ask-user.js +137 -0
  72. package/dist-lib/lib/tools/attachments/delivered.d.ts +5 -0
  73. package/dist-lib/lib/tools/attachments/delivered.js +16 -0
  74. package/dist-lib/lib/tools/attachments/fetched-file.d.ts +32 -0
  75. package/dist-lib/lib/tools/attachments/fetched-file.js +134 -0
  76. package/dist-lib/lib/tools/exec.js +2 -1
  77. package/dist-lib/lib/tools/files/read-file.js +3 -3
  78. package/dist-lib/lib/tools/fs/document-text.d.ts +7 -1
  79. package/dist-lib/lib/tools/fs/document-text.js +4 -20
  80. package/dist-lib/lib/tools/http-request/request.d.ts +2 -2
  81. package/dist-lib/lib/tools/http-request/request.js +1 -1
  82. package/dist-lib/lib/tools/http-request.d.ts +1 -0
  83. package/dist-lib/lib/tools/http-request.js +54 -3
  84. package/dist-lib/lib/tools/index.d.ts +2 -1
  85. package/dist-lib/lib/tools/index.js +5 -1
  86. package/dist-lib/lib/tools/office.js +20 -12
  87. package/dist-lib/lib/tools/operations/builders.d.ts +4 -3
  88. package/dist-lib/lib/tools/operations/builders.js +41 -3
  89. package/dist-lib/lib/tools/operations/calendar-range.d.ts +16 -0
  90. package/dist-lib/lib/tools/operations/calendar-range.js +40 -0
  91. package/dist-lib/lib/tools/operations/compile.js +4 -2
  92. package/dist-lib/lib/tools/operations/manifest.d.ts +4 -0
  93. package/dist-lib/lib/tools/pdf/build.d.ts +11 -1
  94. package/dist-lib/lib/tools/pdf/build.js +52 -16
  95. package/dist-lib/lib/tools/pdf/pages.d.ts +12 -0
  96. package/dist-lib/lib/tools/pdf/pages.js +28 -0
  97. package/dist-lib/lib/tools/pdf/recognize.d.ts +13 -0
  98. package/dist-lib/lib/tools/pdf/recognize.js +58 -0
  99. package/dist-lib/lib/tools/pdf.js +42 -13
  100. package/dist-lib/lib/tools/skills/scope-key.d.ts +1 -0
  101. package/dist-lib/lib/tools/skills/scope-key.js +4 -0
  102. package/dist-lib/lib/tools/web-fetch.js +41 -130
  103. package/dist-lib/plugins/knowledge/index.js +3 -3
  104. package/dist-lib/plugins/mcp/call.js +5 -1
  105. package/dist-lib/plugins/mcp/protocol.d.ts +6 -1
  106. package/dist-lib/plugins/mcp/protocol.js +2 -2
  107. package/dist-lib/plugins/ocr/bmp.d.ts +2 -0
  108. package/dist-lib/plugins/ocr/bmp.js +27 -0
  109. package/dist-lib/plugins/ocr/index.d.ts +12 -0
  110. package/dist-lib/plugins/ocr/index.js +18 -0
  111. package/dist-lib/plugins/ocr/ocr-runtime.d.ts +23 -0
  112. package/dist-lib/plugins/ocr/ocr-runtime.js +82 -0
  113. package/dist-lib/plugins/ocr/reading-order.d.ts +5 -0
  114. package/dist-lib/plugins/ocr/reading-order.js +218 -0
  115. package/dist-lib/plugins/python/bare-floor.d.ts +1 -0
  116. package/dist-lib/plugins/python/bare-floor.js +2 -0
  117. package/dist-lib/plugins/python/index.d.ts +1 -0
  118. package/dist-lib/plugins/python/index.js +1 -0
  119. package/dist-lib/plugins/python/language.js +9 -8
  120. package/dist-lib/plugins/python/python-adapter.d.ts +4 -0
  121. package/dist-lib/plugins/python/python-adapter.js +26 -0
  122. package/dist-lib/plugins/python/worker/client.js +1 -1
  123. package/dist-lib/plugins/python/worker/entry.js +2 -8
  124. package/dist-lib/plugins/python/worker/preload.d.ts +1 -0
  125. package/dist-lib/plugins/python/worker/preload.js +2 -0
  126. package/dist-lib/plugins/python/worker/spawn.js +1 -1
  127. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  128. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  129. package/dist-lib/plugins/weather/lookup.js +1 -0
  130. package/dist-lib/schema/harness.js +17 -0
  131. package/dist-lib/spec/bind.js +3 -0
  132. package/dist-lib/spec/calls.js +1 -0
  133. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  134. package/dist-lib/spec/hrpc/index.js +15 -3
  135. package/dist-lib/spec/hrpc/messages.js +32 -0
  136. package/dist-lib/spec/hyperschema/index.js +32 -0
  137. package/dist-lib/spec/hyperschema/schema.json +40 -0
  138. package/dist-lib/spec/hyperschema/types.d.ts +12 -0
  139. package/package.json +26 -8
  140. package/scripts/addon-externals.cjs +3 -0
  141. package/worker/harness-sidecar.mjs +5 -0
  142. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +0 -20
  143. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +0 -110
  144. package/dist-lib/lib/helpers/input-budget.d.ts +0 -8
  145. package/dist-lib/lib/helpers/input-budget.js +0 -9
@@ -9,8 +9,6 @@ import { createCompletionActors, createInvokeTracker } from './actors.js';
9
9
  import { replayFinalRound, replaySuccessOutput } from './replay-output.js';
10
10
  import { AbortedError, rehydrateError, tagError } from '../../helpers/engine-error.js';
11
11
  import { turnText } from './turns.js';
12
- import { EventMailbox } from './event-mailbox.js';
13
- import { acceptsInput, inputBytes } from '../../helpers/input-budget.js';
14
12
  import { CompletionMachine } from '../../machine/index.js';
15
13
  function readRestoredSnapshot(value) {
16
14
  if (!isRecord(value) || Array.isArray(value))
@@ -115,7 +113,7 @@ export async function* runEngine(run, options = {}) {
115
113
  yield started(run);
116
114
  const invokes = createInvokeTracker();
117
115
  const boot = RunLog.boundaryBoot(journal);
118
- const mailbox = new EventMailbox();
116
+ const mailbox = createEventMailbox();
119
117
  const { ports, context } = await run.start({
120
118
  operations: createOperationPort(journal),
121
119
  invokes,
@@ -151,6 +149,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
151
149
  const pausedMs = run.resume && journal.snapshotSavedAt !== undefined
152
150
  ? Math.max(0, now() - journal.snapshotSavedAt)
153
151
  : 0;
152
+ const { queue } = mailbox;
154
153
  let detached = false;
155
154
  const detach = () => {
156
155
  detached = true;
@@ -165,17 +164,14 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
165
164
  wakeVersion++;
166
165
  wake();
167
166
  };
168
- let pause = () => { };
169
- let inputLimitNotified = false;
170
167
  mailbox.notify = notify;
171
- mailbox.onOverflow = () => queueMicrotask(pause);
172
168
  const { actor, persistence } = await RunLog.createPersistedActor(journal, machine, notify, now);
173
169
  actor.on('*', (event) => {
174
- mailbox.push(event);
170
+ queue.push(event);
175
171
  notify();
176
172
  });
177
173
  actor.subscribe({ next: notify, error: notify });
178
- pause = () => {
174
+ const pause = () => {
179
175
  if (actor.getSnapshot().status === 'active') {
180
176
  actor.send({ type: 'PAUSE' });
181
177
  }
@@ -193,30 +189,11 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
193
189
  return pumping;
194
190
  }
195
191
  if ('reason' in item) {
196
- mailbox.push({ type: 'input-rejected', runId, reason: item.reason });
192
+ queue.push({ type: 'input-rejected', runId, reason: item.reason });
197
193
  notify();
198
194
  }
199
195
  else {
200
- const pending = [
201
- ...actor.getSnapshot().context.steering,
202
- ...actor.getSnapshot().context.followUps
203
- ];
204
- const bytes = pending.reduce((total, queued) => total + inputBytes(queued), 0);
205
- if (!acceptsInput(pending.length, bytes, item)) {
206
- if (!inputLimitNotified) {
207
- inputLimitNotified = true;
208
- mailbox.push({
209
- type: 'input-rejected',
210
- runId,
211
- reason: 'Pending input limit exceeded; one or more inputs were rejected'
212
- });
213
- notify();
214
- }
215
- }
216
- else {
217
- inputLimitNotified = false;
218
- actor.send(inputMessage(item));
219
- }
196
+ actor.send(inputMessage(item));
220
197
  }
221
198
  return pumping;
222
199
  }).catch(noop);
@@ -248,11 +225,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
248
225
  if (journal.hasPendingFlush()) {
249
226
  await persistence.flush();
250
227
  }
251
- yield* drainQueue(mailbox);
252
- if (mailbox.failure) {
253
- const snapshot = actor.getSnapshot();
254
- return { status: 'error', snapshot, error: mailbox.failure };
255
- }
228
+ yield* drainQueue(queue);
256
229
  if (isActiveIdle(actor.getSnapshot()) && !signal?.aborted) {
257
230
  actor.send({ type: 'START' });
258
231
  }
@@ -268,7 +241,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
268
241
  ? await drainSettling({ actor, persistence, durable, detach })
269
242
  : undefined;
270
243
  if (settlingResult) {
271
- yield* drainQueue(mailbox);
244
+ yield* drainQueue(queue);
272
245
  return settlingResult;
273
246
  }
274
247
  if (isSettling) {
@@ -282,12 +255,12 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
282
255
  durable,
283
256
  detach,
284
257
  journal,
285
- queue: mailbox,
258
+ queue,
286
259
  runId
287
260
  });
288
261
  }
289
262
  const observedWakeVersion = wakeVersion;
290
- if (mailbox.size) {
263
+ if (queue.length) {
291
264
  continue;
292
265
  }
293
266
  await new Promise((resolve) => {
@@ -298,7 +271,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
298
271
  });
299
272
  }
300
273
  await persistence.flush();
301
- yield* drainQueue(mailbox);
274
+ yield* drainQueue(queue);
302
275
  return { status: 'done', snapshot: actor.getSnapshot() };
303
276
  }
304
277
  finally {
@@ -419,13 +392,24 @@ function settling(snapshot) {
419
392
  return value === 'pausing';
420
393
  }
421
394
  function* drainQueue(queue) {
422
- while (queue.size) {
395
+ while (queue.length) {
423
396
  const event = queue.shift();
424
397
  if (event) {
425
398
  yield event;
426
399
  }
427
400
  }
428
401
  }
402
+ function createEventMailbox() {
403
+ const mailbox = {
404
+ queue: [],
405
+ notify() { },
406
+ emit(event) {
407
+ mailbox.queue.push(event);
408
+ mailbox.notify();
409
+ }
410
+ };
411
+ return mailbox;
412
+ }
429
413
  function createOperationPort(journal) {
430
414
  return Object.freeze({
431
415
  flush: () => journal.flush(),
@@ -2,7 +2,7 @@ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  import type { RecoveryResolution } from '../../run-log/index.ts';
3
3
  import type { KnowledgeGrant } from '../../contract/knowledge.ts';
4
4
  import type { ToolCallDisplay } from '../../contract/index.ts';
5
- import type { AgentConfig, AccessPolicy, CompiledPolicy, CompletionEvent, ApproveFn, AskUserFn, AttachFn, DriveRoot, FetchAttachmentFn, LlmGenerationParams, Message, ProgressFn, ResponseFormat, RunBudget, RunGoal, RunInput, RoundModelLease, ToolDefinition, ToolExecuteContext } from '../../contract/index.ts';
5
+ import type { AgentConfig, AccessPolicy, CompiledPolicy, CompletionEvent, ApproveFn, AskUserFn, AttachFn, DriveRoot, FetchAttachmentFn, LlmGenerationParams, Message, ProgressFn, ResponseFormat, RunBudget, RunGoal, RunInput, RoundModelLease, ShowImageFn, ToolDefinition, ToolExecuteContext } from '../../contract/index.ts';
6
6
  import type { CompletionSkillEntry } from '../skill-entry.ts';
7
7
  import type { ModelRoundPort } from './model-round.ts';
8
8
  export interface CompletionArgs {
@@ -32,6 +32,7 @@ export interface CompletionArgs {
32
32
  approve?: ApproveFn;
33
33
  attach?: AttachFn;
34
34
  fetchAttachment?: FetchAttachmentFn;
35
+ showImage?: ShowImageFn;
35
36
  progress?: ProgressFn;
36
37
  askUser?: AskUserFn;
37
38
  signal?: BareAbortSignal;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'crypto';
2
2
  import { normalizeToolExecutionOutcome, writeResult } from '../../helpers/run-outcome.js';
3
3
  import { isMetadataMethod } from '../../helpers/mcp-methods.js';
4
- import { captureFacts, captureToolOperationFacts, restoreFacts } from './durable.js';
4
+ import { captureFacts, captureToolOperationFacts, laterDelivered, restoreFacts } from './durable.js';
5
5
  import { AbortedError } from '../../helpers/race-abort.js';
6
6
  import { isRecord } from '../../guards.js';
7
7
  import { detachJson } from '../../helpers/detach-json.js';
@@ -43,11 +43,13 @@ export function toolOperationFacts(value) {
43
43
  }
44
44
  const backends = value.backends.filter(isBackendUse);
45
45
  const runBudget = value.runBudget.outputBytesUsed;
46
+ const delivered = value.runBudget.delivered;
46
47
  const outcome = value.outcome;
47
48
  if (backends.length !== value.backends.length ||
48
49
  typeof runBudget !== 'number' ||
49
50
  !Number.isSafeInteger(runBudget) ||
50
51
  runBudget < 0 ||
52
+ (delivered !== undefined && !(Array.isArray(delivered) && delivered.every(isDeliveredFile))) ||
51
53
  !isRecord(outcome) ||
52
54
  !Array.isArray(outcome.confirmedWrites)) {
53
55
  throw new TypeError('Malformed tool operation facts');
@@ -56,7 +58,19 @@ export function toolOperationFacts(value) {
56
58
  if (confirmedWrites.length !== outcome.confirmedWrites.length) {
57
59
  throw new TypeError('Malformed tool operation facts');
58
60
  }
59
- return { backends, runBudget: { outputBytesUsed: runBudget }, outcome: { confirmedWrites } };
61
+ return {
62
+ backends,
63
+ runBudget: { outputBytesUsed: runBudget, delivered },
64
+ outcome: { confirmedWrites }
65
+ };
66
+ }
67
+ function isDeliveredFile(value) {
68
+ return (isRecord(value) &&
69
+ typeof value.name === 'string' &&
70
+ typeof value.sha256 === 'string' &&
71
+ typeof value.attachmentId === 'string' &&
72
+ typeof value.fileName === 'string' &&
73
+ typeof value.byteLength === 'number');
60
74
  }
61
75
  function runHookOperation({ deps, base, phase, id, name, payload, check, run }) {
62
76
  check();
@@ -71,8 +85,8 @@ function wrapHostCallback({ deps, check, prefix, stage, callId, name, effect, ca
71
85
  const release = deps.session.trackInvoke();
72
86
  try {
73
87
  check();
74
- const journalInput = detachHostCallbackInput(input);
75
- const callbackInput = detachHostCallbackInput(journalInput);
88
+ const journalInput = detachHostCallbackInput(input, digestBytes);
89
+ const callbackInput = detachHostCallbackInput(input, (bytes) => Uint8Array.from(bytes));
76
90
  return await deps.operations.operation({
77
91
  id: `${prefix}:${stage}:${callId}:host-${name}-${count++}`,
78
92
  name: `host:${name}`,
@@ -85,13 +99,17 @@ function wrapHostCallback({ deps, check, prefix, stage, callId, name, effect, ca
85
99
  }
86
100
  };
87
101
  }
88
- function detachHostCallbackInput(input) {
89
- const detached = detachJson(input);
90
- if (isRecord(input) && input.bytes instanceof Uint8Array) {
91
- Reflect.set(detached, 'bytes', Uint8Array.from(input.bytes));
102
+ function detachHostCallbackInput(input, bytesAs) {
103
+ if (!isRecord(input) || !(input.bytes instanceof Uint8Array)) {
104
+ return detachJson(input);
92
105
  }
106
+ const detached = detachJson({ ...input, bytes: null });
107
+ Reflect.set(detached, 'bytes', bytesAs(input.bytes));
93
108
  return detached;
94
109
  }
110
+ function digestBytes(bytes) {
111
+ return { byteLength: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex') };
112
+ }
95
113
  function plannedEffect(context, { stage, callId, name }) {
96
114
  if (context.execution && context.currentCall?.name === name) {
97
115
  return context.execution.effect;
@@ -146,7 +164,8 @@ export function bindOperations(deps, context, stage) {
146
164
  runBudget: {
147
165
  deadlineMs: current.runBudget.deadlineMs,
148
166
  totalMs: current.runBudget.totalMs,
149
- outputBytesUsed: Math.max(current.runBudget.outputBytesUsed, recorded.runBudget.outputBytesUsed)
167
+ outputBytesUsed: Math.max(current.runBudget.outputBytesUsed, recorded.runBudget.outputBytesUsed),
168
+ delivered: laterDelivered(current.runBudget.delivered, recorded.runBudget.delivered)
150
169
  },
151
170
  outcome: {
152
171
  ...current.outcome,
@@ -19,7 +19,7 @@ import { skillStep } from './actors/skill-step.js';
19
19
  import { streaming } from './actors/streaming.js';
20
20
  import { wrapUp } from './actors/wrap-up.js';
21
21
  import { toolContext } from './actors/execution-plan.js';
22
- import { capabilityPolicy, captureFacts, restoreFacts, schemaDigest } from './durable.js';
22
+ import { capabilityPolicy, captureFacts, laterDelivered, restoreFacts, schemaDigest } from './durable.js';
23
23
  import { bindOperations, toolOperationFacts } from './operations.js';
24
24
  import { loadedSkills } from './session.js';
25
25
  import { errorMessage, isRecord } from '../../guards.js';
@@ -79,7 +79,8 @@ export function completionPorts(deps) {
79
79
  backends: recorded.backends.length > currentBackends.length ? recorded.backends : currentBackends,
80
80
  runBudget: {
81
81
  ...currentBudget,
82
- outputBytesUsed: Math.max(typeof currentBudget.outputBytesUsed === 'number' ? currentBudget.outputBytesUsed : 0, recorded.runBudget.outputBytesUsed)
82
+ outputBytesUsed: Math.max(typeof currentBudget.outputBytesUsed === 'number' ? currentBudget.outputBytesUsed : 0, recorded.runBudget.outputBytesUsed),
83
+ delivered: laterDelivered(Array.isArray(currentBudget.delivered) ? currentBudget.delivered : undefined, recorded.runBudget.delivered)
83
84
  },
84
85
  outcome: {
85
86
  ...currentOutcome,
@@ -21,7 +21,9 @@ export interface PrepareStepSource {
21
21
  readonly label: string;
22
22
  propose(deps: CompletionDeps, agent: ResolvedAgent<CompletionSkillEntry>): PrepareCall | null;
23
23
  display(deps: CompletionDeps, step: PrepareStep): ToolCallDisplay;
24
- refusal?(deps: CompletionDeps, step: PrepareStep): string | null;
24
+ refusal?(deps: CompletionDeps, step: PrepareStep): {
25
+ readonly error: string;
26
+ } | null;
25
27
  settle(input: PrepareSettleInput): PrepareRunOutput;
26
28
  fail(input: PrepareFailInput): PrepareFailure;
27
29
  }
@@ -19,6 +19,7 @@ export interface Session extends InvokeTracker {
19
19
  outbound: OutboundGuard;
20
20
  enabled: ToolDefinition[];
21
21
  sdkTools: SdkTool[] | undefined;
22
+ grantable: ReadonlySet<string>;
22
23
  grantedOps: Map<string, CliValidator[]>;
23
24
  behaviorDigest: string;
24
25
  activation: SkillActivation;
@@ -37,6 +37,7 @@ export function createSession(args, options) {
37
37
  outbound,
38
38
  enabled: [],
39
39
  sdkTools: undefined,
40
+ grantable: new Set(),
40
41
  grantedOps: new Map(),
41
42
  behaviorDigest: createHash('sha256')
42
43
  .update(stableStringify((args.tools ?? [])
@@ -2,6 +2,7 @@ import { HookHalt, RecoveryRequired } from '../../helpers/engine-error.js';
2
2
  import { AbortedError, raceAbort } from '../../helpers/race-abort.js';
3
3
  import { errorCode, errorMessage, isRecord } from '../../guards.js';
4
4
  import { detachJson } from '../../helpers/detach-json.js';
5
+ import { mapStrings, restoreTemplateTokens } from '../../helpers/control-tokens.js';
5
6
  import { clipRawCall, normalizeToolArgs } from '../../helpers/tool-call-markup.js';
6
7
  import { INTENT_PARAM, takeToolIntent } from '../../helpers/tool-intent.js';
7
8
  import { withHookContext } from '../tool-turns.js';
@@ -228,7 +229,7 @@ export async function executeCall(tool, args, ctx, { runId, deniedMessage, appro
228
229
  }
229
230
  let output;
230
231
  let outcome = { kind: 'success' };
231
- const toolArgs = detachJson(args);
232
+ const toolArgs = mapStrings(detachJson(args), restoreTemplateTokens);
232
233
  try {
233
234
  output = await tool.execute(toolArgs, { ...ctx, signal, runId, callId, approval: decision });
234
235
  HarnessLog.debug('tool done', { tool: tool.name });
@@ -22,6 +22,9 @@ function originOfToolTurn(text) {
22
22
  return text.startsWith(`[Tool: ${Agent.SKILL_TOOL_NAME} (`) ? 'skill' : 'tool-result';
23
23
  }
24
24
  export function sanitizeTurn(turn, answered = false) {
25
+ if (turn.role === 'tool') {
26
+ return turn;
27
+ }
25
28
  const stripped = stripControlTokens(turn.content);
26
29
  const content = turn.role === 'assistant' && !answered ? stripToolCallMarkup(stripped) : stripped;
27
30
  return content === turn.content ? turn : { ...turn, content };
@@ -63,7 +66,7 @@ function preloadTurns({ messages, at, nudge, consumed }) {
63
66
  }
64
67
  return [
65
68
  { role: 'assistant', content: assistantToolTurn('', [call]) },
66
- sanitizeTurn({ role: 'tool', content: toolResultTurn(call.name, call.id, output) }),
69
+ { role: 'tool', content: toolResultTurn(call.name, call.id, output) },
67
70
  {
68
71
  role: 'user',
69
72
  content: typeof output.mention === 'string' ? skillMentionNudge(output.mention) : nudge
@@ -99,7 +102,7 @@ function modelTurn(turn, answered) {
99
102
  }
100
103
  if (isReplayedResult(turn)) {
101
104
  const content = replayedResult(turn.name, turn.toolCallId, turn.content);
102
- return sanitizeTurn({ role: 'tool', content });
105
+ return { role: 'tool', content };
103
106
  }
104
107
  return sanitizeTurn(turn, answered);
105
108
  }
@@ -1,3 +1,4 @@
1
+ import { completionParams } from '../helpers/completion-params.js';
1
2
  import { cleanAnswer } from '../helpers/clean-answer.js';
2
3
  import { raceAbort } from '../helpers/race-abort.js';
3
4
  import { withoutRepeatedReply } from '../helpers/repeated-reply.js';
@@ -23,15 +24,14 @@ export async function expandImagePrompt(sdk, prompt, options) {
23
24
  return { text, model: options.model, totalTokens: final.stats?.generatedTokens };
24
25
  }
25
26
  async function rewrite(sdk, prompt, { modelId, signal }) {
26
- const run = withoutRepeatedReply(sdk.completion({
27
+ const run = withoutRepeatedReply(sdk.completion(completionParams({
27
28
  modelId,
28
29
  history: [
29
30
  { role: 'system', content: SYSTEM },
30
31
  { role: 'user', content: prompt }
31
32
  ],
32
- stream: true,
33
33
  generationParams: { temp: 0.7, reasoning_budget: 0 }
34
- }));
34
+ })));
35
35
  try {
36
36
  return await raceAbort(run.final, signal);
37
37
  }
@@ -4,7 +4,7 @@ export declare const TOOL_SEARCH_TOOL_NAME: string;
4
4
  export declare function defers(tool: ToolDefinition): boolean;
5
5
  export declare function deferredForRun(tool: ToolDefinition): ToolDefinition;
6
6
  export declare function toSdkTool(tool: ToolDefinition): SdkTool;
7
- export declare function toSdkTools(tools: readonly ToolDefinition[]): SdkTool[] | undefined;
7
+ export declare function toSdkTools(tools: readonly ToolDefinition[], callable?: ReadonlySet<string>): SdkTool[] | undefined;
8
8
  export declare function renderedTools(tools: SdkTool[] | undefined, history: readonly CompletionHistoryEntry[]): SdkTool[] | undefined;
9
9
  export declare function loadedTools(history: readonly CompletionHistoryEntry[]): Set<string>;
10
10
  export declare function loadTurns(sent: readonly SdkTool[] | undefined, names: Iterable<string>, history: readonly CompletionHistoryEntry[]): Message[];
@@ -97,9 +97,10 @@ export function toSdkTool(tool) {
97
97
  const group = tool.group ?? tool.owningSkill ?? tool.toolset ?? undefined;
98
98
  return defers(tool) ? { ...sent, deferLoading: true, group } : sent;
99
99
  }
100
- export function toSdkTools(tools) {
100
+ export function toSdkTools(tools, callable) {
101
101
  const searching = tools.some(defers);
102
- const sent = tools.filter((tool) => !searching || tool.name !== TOOL_SEARCH_NAME);
102
+ const waits = (tool) => tool.skillGated === true && callable?.has(tool.name) === false;
103
+ const sent = tools.filter((tool) => (!searching || tool.name !== TOOL_SEARCH_NAME) && !waits(tool));
103
104
  return sent.length ? sent.map((tool) => toSdkTool(tool)) : undefined;
104
105
  }
105
106
  export function renderedTools(tools, history) {
@@ -6,7 +6,15 @@ export type CompletionSkillEntry = SkillCatalogEntry & {
6
6
  };
7
7
  export declare function skillInContext(entry: CompletionSkillEntry): boolean;
8
8
  export declare function unreadySkillState(name: string, catalog: readonly CompletionSkillEntry[]): SkillState | null;
9
- export declare function unreadySkillMessage(name: string, state: string): string;
9
+ export interface UnreadySkillSetup {
10
+ readonly skill: string;
11
+ readonly state: string;
12
+ }
13
+ export interface UnreadySkillRefusal {
14
+ readonly error: string;
15
+ readonly setup?: UnreadySkillSetup;
16
+ }
17
+ export declare function unreadySkillRefusal(name: string, state: string): UnreadySkillRefusal;
10
18
  export declare function fixableInSkills(entry: CompletionSkillEntry): boolean;
11
19
  export declare function promptSkill(entry: CompletionSkillEntry): PromptSkill;
12
20
  export declare function mentionHandle(entry: CompletionSkillEntry): string;
@@ -7,17 +7,21 @@ export function unreadySkillState(name, catalog) {
7
7
  const status = catalog.find((entry) => entry.name === name)?.status;
8
8
  return status !== undefined && !isAvailableState(status) ? status : null;
9
9
  }
10
- export function unreadySkillMessage(name, state) {
11
- if (state === SKILL_STATE.incompatibleModel) {
12
- return `skill "${name}" needs a larger model than the one loaded. Tell the user to pick a larger model to use it; do not retry.`;
13
- }
14
- return (`skill "${name}" is ${state} and cannot be used yet. Tell the user to ${unreadyRemedy(state)}, ` +
15
- `and do not do this task with another tool.`);
16
- }
17
10
  const FIXABLE_STATES = new Set([
18
11
  SKILL_STATE.disconnected,
19
12
  SKILL_STATE.needsSetup
20
13
  ]);
14
+ export function unreadySkillRefusal(name, state) {
15
+ const error = unreadySkillMessage(name, state);
16
+ return FIXABLE_STATES.has(state) ? { error, setup: { skill: name, state } } : { error };
17
+ }
18
+ function unreadySkillMessage(name, state) {
19
+ if (state === SKILL_STATE.incompatibleModel) {
20
+ return `skill "${name}" needs a larger model than the one loaded. Tell the user to pick a larger model to use it; do not retry.`;
21
+ }
22
+ return (`skill "${name}" is ${state} and cannot be used yet. Tell the user once, in one sentence, to ` +
23
+ `${unreadyRemedy(state)}. Name no other menu or settings path, and do not do this task with another tool.`);
24
+ }
21
25
  export function fixableInSkills(entry) {
22
26
  return entry.status !== undefined && FIXABLE_STATES.has(entry.status);
23
27
  }
@@ -42,6 +42,11 @@ export interface FailureTurn extends FailureResultValue {
42
42
  }
43
43
  export declare function redactFailureTurns(history: readonly SdkMessage[], failures: readonly FailureTurn[], redact: <Value>(value: Value) => Value): SdkMessage[];
44
44
  export declare function skillLoadedTurn(name: string, id?: string): string;
45
+ export interface AttachedFile {
46
+ attachmentId: string;
47
+ fileName: string;
48
+ }
49
+ export declare function attachedFiles(result: unknown): AttachedFile[];
45
50
  export declare function attachmentTurn(name: string, result: unknown): string | null;
46
51
  export declare function loadedSkillsFrom(messages: readonly Message[]): Set<string>;
47
52
  export declare function loadedSkillFilesFrom(messages: readonly Message[]): Map<string, Set<string>>;
@@ -4,6 +4,7 @@ import { headTail } from '../helpers/head-tail.js';
4
4
  import { MALFORMED_CALL_ID } from '../helpers/tool-call-markup.js';
5
5
  import { MAX_GOAL_CHECKS } from '../helpers/goal-check.js';
6
6
  import { compactContent } from '../context-window.js';
7
+ import { defuseTemplateTokens } from '../helpers/control-tokens.js';
7
8
  import { TOOL_SEARCH_TOOL_NAME } from './sdk-tool.js';
8
9
  import { isFailureResultReference, readFailureResult } from '../helpers/failure-result.js';
9
10
  import { TOOL_FAILED_NOTE } from './tool-failed-note.js';
@@ -166,10 +167,8 @@ export function redactFailureTurns(history, failures, redact) {
166
167
  const out = [...history];
167
168
  for (const { at, name, callId, result, compactedTo } of redact(failures)) {
168
169
  const content = toolResultTurn(name, callId, readFailureResult(result));
169
- out[at] = {
170
- role: 'tool',
171
- content: compactedTo === undefined ? content : compactContent(content, compactedTo)
172
- };
170
+ const sent = compactedTo === undefined ? content : compactContent(content, compactedTo);
171
+ out[at] = { role: 'tool', content: defuseTemplateTokens(sent) };
173
172
  }
174
173
  return out;
175
174
  }
@@ -179,41 +178,39 @@ export function skillLoadedTurn(name, id = DIRECT_CALL_ID) {
179
178
  content: `${name} was loaded in an earlier turn but its instructions are not in this context. Call the skill tool with this name again before doing its work.`
180
179
  });
181
180
  }
182
- function refFrom(value) {
183
- if (!value || typeof value !== 'object') {
181
+ function attachedFile(value) {
182
+ if (!isRecord(value) || typeof value.attachmentId !== 'string') {
184
183
  return null;
185
184
  }
186
- if (!('attachmentId' in value) || typeof value.attachmentId !== 'string') {
187
- return null;
185
+ const fileName = typeof value.fileName === 'string' ? value.fileName : '';
186
+ return { attachmentId: value.attachmentId, fileName };
187
+ }
188
+ export function attachedFiles(result) {
189
+ const direct = attachedFile(result);
190
+ if (direct) {
191
+ return [direct];
188
192
  }
189
- const ref = { attachmentId: value.attachmentId };
190
- const name = 'fileName' in value && typeof value.fileName === 'string' ? value.fileName : '';
191
- const dot = name.lastIndexOf('.');
193
+ const listed = isRecord(result) ? result.attachments : undefined;
194
+ return Array.isArray(listed) ? listed.flatMap((entry) => attachedFile(entry) ?? []) : [];
195
+ }
196
+ function refFrom({ attachmentId, fileName }) {
197
+ const ref = { attachmentId };
198
+ const dot = fileName.lastIndexOf('.');
192
199
  if (dot > 0) {
193
- ref.type = name.slice(dot + 1).toLowerCase();
200
+ ref.type = fileName.slice(dot + 1).toLowerCase();
194
201
  }
195
202
  return ref;
196
203
  }
197
204
  export function attachmentTurn(name, result) {
198
- const direct = refFrom(result);
205
+ const direct = attachedFile(result);
199
206
  if (direct) {
200
- return toolResultTurn(name, DIRECT_CALL_ID, direct);
201
- }
202
- const listed = isRecord(result) ? result.attachments : undefined;
203
- if (!Array.isArray(listed)) {
204
- return null;
205
- }
206
- const refs = [];
207
- for (const entry of listed) {
208
- const ref = refFrom(entry);
209
- if (ref) {
210
- refs.push(ref);
211
- }
207
+ return toolResultTurn(name, DIRECT_CALL_ID, refFrom(direct));
212
208
  }
213
- if (!refs.length) {
209
+ const files = attachedFiles(result);
210
+ if (!files.length) {
214
211
  return null;
215
212
  }
216
- return toolResultTurn(name, DIRECT_CALL_ID, { attachments: refs });
213
+ return toolResultTurn(name, DIRECT_CALL_ID, { attachments: files.map(refFrom) });
217
214
  }
218
215
  export function loadedSkillsFrom(messages) {
219
216
  const loaded = new Set();
@@ -1,7 +1,7 @@
1
1
  import { harnessClient } from '../../spec/calls.js';
2
2
  import HRPC from '../../spec/hrpc/index.js';
3
3
  import { encode } from '../../spec/hrpc/messages.js';
4
- import { errorMessage, isRecord } from '../guards.js';
4
+ import { errorMessage, isAskForm, isRecord } from '../guards.js';
5
5
  import { addonTaskType } from '../models/model-task.js';
6
6
  import { pushQueue } from '../queue.js';
7
7
  import { settleOnClose } from '../rpc-session.js';
@@ -234,7 +234,8 @@ function answerQuestion(event, askUser, send) {
234
234
  void Promise.resolve()
235
235
  .then(() => askUser({
236
236
  question: event.question ?? '',
237
- options: Array.isArray(event.options) ? event.options.map(String) : undefined
237
+ options: Array.isArray(event.options) ? event.options.map(String) : undefined,
238
+ form: isAskForm(event.payload) ? event.payload : undefined
238
239
  }))
239
240
  .then((answer) => send({ type: 'question-result', callId, answer: answer ?? '' }), (err) => send({ type: 'question-result', callId, message: errorMessage(err) }));
240
241
  }
@@ -1,6 +1,7 @@
1
1
  import EventEmitter from 'events';
2
2
  import { type Transport } from './rpc-session.ts';
3
3
  import { type KvCacheDeletionResult } from './capabilities/kv-cache.ts';
4
+ import type { OcrReadContext } from './contract/ocr.ts';
4
5
  import type { CustomModelEntry } from './models/model-catalog.ts';
5
6
  import { type ModelSourcePreview, type PreviewModelSourceContext } from './capabilities/preview-model-source.ts';
6
7
  import type { CapabilityInfo, CompletionContext, CredentialEntry, DetectedLanguage, DetectLanguageContext, DownloadContext, EmbedContext, HarnessContract, HarnessDiagnostics, HarnessEvent, HarnessInfo, HostContext, InfraModel, InvokeContext, ListModelsOptions, ModelInfo, ResolvedSkillCatalogEntry, SkillsOptions, SkillWriteResult, SpeakContext, SpeakResult, SpeakStreamContext, ToolCatalogEntry, TranscribeContext, LoadModelContext, LoadModelResult, MemoryUsage, UnloadModelContext, UnloadModelResult, WarmModelContext, DownloadsAllowedOptions } from './contract-types.ts';
@@ -39,6 +40,7 @@ export declare class RemoteHarness extends EventEmitter implements HarnessContra
39
40
  download(context: HostContext<DownloadContext>): AsyncIterable<HarnessEvent>;
40
41
  embed(context: HostContext<EmbedContext>): Promise<number[][]>;
41
42
  transcribe(context: HostContext<TranscribeContext>): Promise<string>;
43
+ ocrRead(context: HostContext<OcrReadContext>): Promise<string>;
42
44
  detectLanguage(context: DetectLanguageContext): Promise<DetectedLanguage[]>;
43
45
  speak(context: HostContext<SpeakContext>): Promise<SpeakResult>;
44
46
  speakStream(context: HostContext<SpeakStreamContext>): AsyncIterable<SpeakResult>;