@qvac/harness 1.0.0-rc.12 → 1.0.0-rc.13

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 (74) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -1
  3. package/dist-lib/index.js +0 -1
  4. package/dist-lib/lib/agent/follow.js +9 -2
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +13 -3
  6. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +11 -6
  7. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.d.ts +2 -1
  8. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +19 -11
  9. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +3 -0
  10. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +10 -2
  11. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +3 -0
  12. package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
  13. package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
  14. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
  15. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
  16. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  17. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +2 -0
  18. package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
  19. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -0
  20. package/dist-lib/lib/capabilities/completion-engine/round.js +38 -19
  21. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
  22. package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
  23. package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
  24. package/dist-lib/lib/capabilities/tool-turns.js +1 -0
  25. package/dist-lib/lib/connect.js +4 -2
  26. package/dist-lib/lib/contract/completion.d.ts +2 -1
  27. package/dist-lib/lib/contract/knowledge.d.ts +10 -0
  28. package/dist-lib/lib/fold/index.d.ts +3 -2
  29. package/dist-lib/lib/fold/index.js +7 -6
  30. package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
  31. package/dist-lib/lib/helpers/goal-check.js +89 -7
  32. package/dist-lib/lib/helpers/html-helpers.js +9 -6
  33. package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
  34. package/dist-lib/lib/helpers/input-budget.js +9 -0
  35. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  36. package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
  37. package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
  38. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  39. package/dist-lib/lib/machine/completion/rules.js +14 -5
  40. package/dist-lib/lib/machine/completion/types.d.ts +3 -0
  41. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  42. package/dist-lib/lib/plugins/registry.js +49 -10
  43. package/dist-lib/lib/residency/index.js +2 -0
  44. package/dist-lib/lib/serve.js +56 -15
  45. package/dist-lib/lib/tools/files/glob.js +2 -2
  46. package/dist-lib/lib/tools/files/read-file.js +134 -15
  47. package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
  48. package/dist-lib/lib/tools/fs/walk.js +2 -1
  49. package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
  50. package/dist-lib/lib/tools/http-request.js +28 -11
  51. package/dist-lib/lib/tools/office.d.ts +1 -1
  52. package/dist-lib/lib/tools/office.js +34 -12
  53. package/dist-lib/lib/wire.js +23 -3
  54. package/dist-lib/plugins/knowledge/index.js +1 -0
  55. package/dist-lib/plugins/knowledge/manifest.d.ts +29 -0
  56. package/dist-lib/plugins/knowledge/manifest.js +41 -0
  57. package/dist-lib/plugins/knowledge/search-tool.js +8 -8
  58. package/dist-lib/plugins/knowledge/store.d.ts +35 -7
  59. package/dist-lib/plugins/knowledge/store.js +335 -143
  60. package/dist-lib/plugins/mcp/call.js +10 -3
  61. package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
  62. package/dist-lib/plugins/mcp/protocol.js +11 -10
  63. package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
  64. package/dist-lib/plugins/mcp/tool-listing.js +97 -0
  65. package/dist-lib/plugins/music/generate-music.js +2 -2
  66. package/dist-lib/plugins/python/language.js +2 -2
  67. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  68. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  69. package/dist-lib/schema/harness.js +4 -2
  70. package/dist-lib/spec/hrpc/messages.js +19 -4
  71. package/dist-lib/spec/hyperschema/index.js +19 -4
  72. package/dist-lib/spec/hyperschema/schema.json +12 -1
  73. package/dist-lib/spec/hyperschema/types.d.ts +2 -0
  74. package/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -461,6 +461,13 @@ breaking change is listed under Changed and Removed.
461
461
 
462
462
  ### Changed
463
463
 
464
+ - A goal with host checks that test behaviour stops asking the model for checks
465
+ of its own after two goal turns it ignored. From then on the plan and the host
466
+ checks meet it, and a check the model names later still gates it. A goal with
467
+ no host checks keeps asking. (#682) When every host check only tests that a
468
+ file exists (`test -s`, `[ -f ... ]`), the ask stays until the model names a
469
+ check or a passing test runner, test script or inline assertion proves the
470
+ result; that run is held as a check of its own. (#686)
464
471
  - A host reaches the drive protocol it serves, the skill catalog and the
465
472
  user-plugin import map through named entries: `@qvac/harness/drive`
466
473
  (`DriveRequest`, `DriveResponse`, `DriveEntry`, `GrantedDrive`, `DriveOpFn`,
@@ -1080,6 +1087,28 @@ breaking change is listed under Changed and Removed.
1080
1087
 
1081
1088
  ### Fixed
1082
1089
 
1090
+ - `tools/list` through `mcp_call` comes back as a line per tool, with each
1091
+ argument's type and allowed values, and `params.names` gives the tools named
1092
+ whole. Asana's 52 tools were 148 KB, so the model saw 5 of them cut or waited
1093
+ minutes for the whole listing on every round; the summary is 14 KB. See
1094
+ [the decision record](./docs/decisions/2026-10-29-mcp-call-lists-a-servers-tools-a-line-each.md).
1095
+ (QVAC-21896)
1096
+ - An MCP response, from `mcp_call` or a named server tool, is cut to the same
1097
+ share of the context window as an `http_request` body, and a cut carries the
1098
+ same `truncated` field, instead of a fixed 8 KB with a marker. The cut keeps
1099
+ JSON parseable and keeps the fields after a bulky one, and the body is no
1100
+ longer re-indented before it is measured. Asana's `tools/list` came back as
1101
+ 5 of its tools and a task as its custom fields without its name, so the
1102
+ asana skill guessed arguments for 8 to 11 calls and often never answered.
1103
+ (QVAC-21896)
1104
+ - A cut string inside a JSON response is measured as it serializes, so a body
1105
+ of escaped text (newlines, quotes) stays within the room instead of coming
1106
+ back at up to twice the budget while `truncated.keptChars` reported the
1107
+ budget, and a short field after it still fits.
1108
+ - The last tool round pushes `WRAP_UP_NUDGE` (a host's `wording.wrapUp`), which asks for a
1109
+ plain-text answer, instead of the nudge that offers "the next tool": with the grammar off
1110
+ Qwen3.5-2B wrote that call as text and answered "I ran out of steps" (24 → 1 of 396 runs).
1111
+ - The runaway cap also counts tool markup in think blocks, closed or not.
1083
1112
  - A tool call whose arguments a model wrote as something other than an object, such as a
1084
1113
  string, no longer fails the run with a raw `TypeError`. The call is answered with an error
1085
1114
  the model reads, and the tool never runs.
package/README.md CHANGED
@@ -22,6 +22,7 @@
22
22
  <a href="#plugins">Plugins</a> &middot;
23
23
  <a href="#examples">Examples</a> &middot;
24
24
  <a href="#host-it">Host it</a> &middot;
25
+ <a href="docs/runtime-support.md">Runtime support</a> &middot;
25
26
  <a href="#development">Development</a>
26
27
  </p>
27
28
 
@@ -195,7 +196,8 @@ run going until every step is done or a budget runs out. A goal's `checks` are c
195
196
  is judged by, and until they pass each goal turn names the check and the output of its failed run.
196
197
  On a run with a tool that takes a `command`, the model must also name its own checks under a
197
198
  `Checks:` line, and the goal is met only once every check, the host's and the model's, ran in a
198
- call's `command` and exited 0, so host checks alone never meet it. `checksProve: true` says the host
199
+ call's `command` and exited 0. With host checks, the ask stops after two goal turns the model
200
+ ignores, and from then on the plan and the host checks meet the goal. `checksProve: true` says the host
199
201
  checks prove the task: the goal is met on them alone and the model is not asked for its own. It has
200
202
  no effect without checks. With no tool that takes a `command` and no host checks, the goal ends when the plan is done; host
201
203
  checks need a tool that takes a `command`, or the goal runs to its budget.
package/dist-lib/index.js CHANGED
@@ -3,7 +3,6 @@ import { platform, totalmem } from 'os';
3
3
  import process from 'process';
4
4
  import ReadyResource from 'ready-resource';
5
5
  import { HarnessError } from './lib/errors.js';
6
- import { androidCpuPlacement } from './lib/hardware/cpu-placement.js';
7
6
  import { probeGpuStats } from './lib/hardware/gpu-probe.js';
8
7
  import { probeCapabilityProfile } from './lib/hardware/capability-probe.js';
9
8
  import { Lifecycle } from './lib/lifecycle/index.js';
@@ -150,9 +150,16 @@ function resumedHop(runId, agents) {
150
150
  ? { index: Number(match[2]), id: match[3], root: match[1] }
151
151
  : null;
152
152
  }
153
- const TRANSFER_NOTE = /\n\n\[Transferred from [^\]\n]*: [^\n]*\]$/;
153
+ const TRANSFER_NOTE = '\n\n[Transferred from ';
154
154
  export function untransferred(text) {
155
- return text.replace(TRANSFER_NOTE, '');
155
+ const at = text.lastIndexOf(TRANSFER_NOTE);
156
+ return at !== -1 && text.endsWith(']') && isNote(text.slice(at + TRANSFER_NOTE.length, -1))
157
+ ? text.slice(0, at)
158
+ : text;
159
+ }
160
+ function isNote(note) {
161
+ const colon = note.indexOf(': ');
162
+ return colon !== -1 && !note.slice(0, colon).includes(']') && !note.includes('\n');
156
163
  }
157
164
  function noted(messages, note) {
158
165
  const last = messages.findLastIndex((message) => message.role === 'user');
@@ -11,7 +11,7 @@ import { runToolCall } from './execute.js';
11
11
  import { toolCaller } from '../tool-caller.js';
12
12
  import { loadSkill } from './loading-skill.js';
13
13
  import { failureResultRef, storeFailureResult } from '../../../helpers/failure-result.js';
14
- import { runsCheck } from '../../../helpers/goal-check.js';
14
+ import { provesResult, runsCheck } from '../../../helpers/goal-check.js';
15
15
  const CHECK_OUTPUT_CHARS = 2000;
16
16
  export const executing = async function executing(input) {
17
17
  const { emit, input: deps, context } = input;
@@ -55,6 +55,7 @@ export const executing = async function executing(input) {
55
55
  endedRun: succeeded && plan.resolved.tool.endsRun === true ? true : undefined,
56
56
  durationMs: settled.durationMs,
57
57
  checked: settled.checked,
58
+ proved: settled.proved,
58
59
  plan: planned ? Agent.planSteps(callArgs) : undefined,
59
60
  leftPlanMode: planned && context.planMode && call.leavesPlan ? true : undefined
60
61
  };
@@ -205,6 +206,9 @@ export function settleCall({ input: { session }, context }, { ran, direct, emit
205
206
  output: executed.output
206
207
  })
207
208
  : undefined,
209
+ proved: executed.executed && succeeded && context.goal
210
+ ? proofRun(callArgs.command, executed.output)
211
+ : undefined,
208
212
  entry: toolResultHistoryEntry({
209
213
  name: call.name,
210
214
  id: resultTurnId,
@@ -220,6 +224,12 @@ function checksRun({ goal }, { command, passed, output }) {
220
224
  if (!ran.length) {
221
225
  return undefined;
222
226
  }
223
- const tail = textsOf(historyPayload(output)).join('\n').trim().slice(-CHECK_OUTPUT_CHARS);
224
- return ran.map(({ name }) => ({ name, passed, output: tail }));
227
+ return ran.map(({ name }) => ({ name, passed, output: outputTail(output) }));
228
+ }
229
+ function proofRun(command, output) {
230
+ const name = typeof command === 'string' ? provesResult(command) : undefined;
231
+ return name ? { name, passed: true, output: outputTail(output) } : undefined;
232
+ }
233
+ function outputTail(output) {
234
+ return textsOf(historyPayload(output)).join('\n').trim().slice(-CHECK_OUTPUT_CHARS);
225
235
  }
@@ -2,7 +2,7 @@ import { Agent } from '../../../agent/index.js';
2
2
  import { spliceFrom } from '../splice.js';
3
3
  import { AbortedError } from '../../../helpers/race-abort.js';
4
4
  import { currentTimeAnnotation, lastUserContent } from '../../../prompt.js';
5
- import { explicitWebSearchQuery, lastUserImages, modelTurns, withTurnContext } from '../turns.js';
5
+ import { explicitWebSearchQuery, knowledgeExcerpt, knowledgeSources, lastUserImages, modelTurns, withTurnContext } from '../turns.js';
6
6
  import { HookHalt } from '../../../helpers/engine-error.js';
7
7
  import { stripControlTokens } from '../../../helpers/control-tokens.js';
8
8
  import { fixableInSkills, skillInContext } from '../../skill-entry.js';
@@ -15,7 +15,7 @@ import { logToolPrompt } from '../../tool-prompt-log.js';
15
15
  import { toolContext } from './execution-plan.js';
16
16
  import { knowledgeSearch } from './retrieving.js';
17
17
  import { detachJson } from '../../../helpers/detach-json.js';
18
- import { GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../../helpers/goal-check.js';
18
+ import { asksChecks, GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../../helpers/goal-check.js';
19
19
  function offeredTools(tools, model) {
20
20
  const profile = model ? modelNameToCapabilityProfile(model) : undefined;
21
21
  return tools.filter(({ minCapabilityProfile: min }) => !min || (profile !== undefined && meetsMinCapabilityProfile(profile, min)));
@@ -38,7 +38,7 @@ function takesCommand(tools) {
38
38
  return tools.some((tool) => 'command' in tool.parameters.properties);
39
39
  }
40
40
  function checksAsk({ goal }, checkable) {
41
- if (!goal || !checkable || goal.named) {
41
+ if (!goal || !asksChecks({ ...goal, checkable })) {
42
42
  return [];
43
43
  }
44
44
  return [{ role: 'user', content: goal.checks.length ? GOAL_PROOF_ASK : GOAL_CHECKS_ASK }];
@@ -169,7 +169,8 @@ async function prepare({ input, context, reconstruct, source, emit }) {
169
169
  ? withSystem([...withTurnContext(messages, { time, ...added }), ...checks])
170
170
  : [...context.history];
171
171
  if (firstTurn && !reconstruct && messages.some((turn) => turn.role === 'user')) {
172
- emit({ type: 'context', context: { time, ...added }, round: context.round });
172
+ const sources = hits.length ? knowledgeSources(hits) : undefined;
173
+ emit({ type: 'context', context: { time, ...added }, sources, round: context.round });
173
174
  }
174
175
  const sources = firstTurn
175
176
  ? hits.map((hit) => session.outbound.facts('tool-result', hit.text))
@@ -234,7 +235,7 @@ function bareTurn(messages) {
234
235
  function addedContext(hits, notes) {
235
236
  const added = {};
236
237
  if (hits.length > 0) {
237
- added.excerpts = hits.map((hit) => hit.text);
238
+ added.excerpts = hits.map(knowledgeExcerpt);
238
239
  }
239
240
  if (notes !== undefined) {
240
241
  added.notes = notes;
@@ -245,9 +246,13 @@ function knowledgeHits(deps, context, messages) {
245
246
  if (context.round > 0 || context.directSearchDone) {
246
247
  return Promise.resolve([]);
247
248
  }
249
+ const { typedText } = deps.args;
248
250
  return knowledgeSearch(deps, {
249
251
  id: `${context.runId}:round-${context.round}:prepare:knowledge`,
250
- text: Agent.untransferred(lastUserContent(messages))
252
+ focus: deps.args.knowledge?.focus,
253
+ text: typedText === undefined
254
+ ? Agent.untransferred(lastUserContent(messages))
255
+ : stripControlTokens(typedText)
251
256
  });
252
257
  }
253
258
  function prepareSession(session, prepared) {
@@ -5,6 +5,7 @@ export declare const retrieving: CompletionActor<RetrievingOutput>;
5
5
  interface KnowledgeSearch {
6
6
  id: string;
7
7
  text: string;
8
+ focus?: readonly string[] | undefined;
8
9
  }
9
- export declare function knowledgeSearch({ args, services, operations }: CompletionDeps, { id, text }: KnowledgeSearch): Promise<KnowledgeHit[]>;
10
+ export declare function knowledgeSearch({ args, services, operations }: CompletionDeps, { id, text, focus }: KnowledgeSearch): Promise<KnowledgeHit[]>;
10
11
  export {};
@@ -1,27 +1,34 @@
1
1
  import { AbortedError } from '../../../helpers/race-abort.js';
2
+ import { stripControlTokens } from '../../../helpers/control-tokens.js';
2
3
  import { isFailureResultReference } from '../../../helpers/failure-result.js';
3
4
  import { HarnessLog } from '../../../log.js';
4
5
  import { errorMessage } from '../../../guards.js';
5
6
  import { spliceFrom } from '../splice.js';
6
- import { turnText } from '../turns.js';
7
+ import { knowledgeExcerpt, knowledgeSources, turnText } from '../turns.js';
7
8
  export const retrieving = async function retrieving({ input, context, emit }) {
8
9
  const { history, edgeInputs } = context;
9
10
  const at = history.findLastIndex((entry) => !isFailureResultReference(entry) && entry.role === 'user');
10
11
  const turn = history[at];
12
+ const typed = edgeInputs.at(-1)?.text;
11
13
  const hits = turn && !isFailureResultReference(turn)
12
14
  ? await knowledgeSearch(input, {
13
15
  id: `${context.runId}:round-${context.round}:input:knowledge`,
14
- text: turn.content
16
+ text: typed === undefined ? turn.content : stripControlTokens(typed)
15
17
  })
16
18
  : [];
17
- const excerpts = hits.map((hit) => hit.text);
19
+ const excerpts = hits.map(knowledgeExcerpt);
18
20
  for (const [index, queued] of edgeInputs.entries()) {
19
- const added = index === edgeInputs.length - 1 && excerpts.length ? { excerpts } : {};
20
- const turnContext = { ...queued.context, ...added };
21
+ const found = index === edgeInputs.length - 1 && excerpts.length > 0;
22
+ const turnContext = found ? { ...queued.context, excerpts } : { ...queued.context };
21
23
  if (Object.keys(turnContext).length > 0) {
22
- emit(queued.id === undefined
23
- ? { type: 'context', context: turnContext, round: context.round }
24
- : { type: 'context', id: queued.id, context: turnContext, round: context.round });
24
+ const sources = found ? knowledgeSources(hits) : undefined;
25
+ const event = {
26
+ type: 'context',
27
+ context: turnContext,
28
+ sources,
29
+ round: context.round
30
+ };
31
+ emit(queued.id === undefined ? event : { ...event, id: queued.id });
25
32
  }
26
33
  }
27
34
  if (!turn || isFailureResultReference(turn) || hits.length === 0) {
@@ -34,9 +41,10 @@ export const retrieving = async function retrieving({ input, context, emit }) {
34
41
  sources: hits.map((hit) => input.session.outbound.facts('tool-result', hit.text))
35
42
  };
36
43
  };
37
- export function knowledgeSearch({ args, services, operations }, { id, text }) {
44
+ export function knowledgeSearch({ args, services, operations }, { id, text, focus }) {
38
45
  const knowledge = services?.knowledge;
39
46
  const scopes = args.knowledge?.scopes ?? [];
47
+ const k = args.knowledge?.k;
40
48
  const query = text.trim();
41
49
  if (!knowledge ||
42
50
  scopes.length === 0 ||
@@ -46,7 +54,7 @@ export function knowledgeSearch({ args, services, operations }, { id, text }) {
46
54
  }
47
55
  const search = async () => {
48
56
  try {
49
- return await knowledge.search({ text: query, scopes, signal: args.signal });
57
+ return await knowledge.search({ text: query, scopes, focus, k, signal: args.signal });
50
58
  }
51
59
  catch (error) {
52
60
  if (args.signal?.aborted || error instanceof AbortedError) {
@@ -59,7 +67,7 @@ export function knowledgeSearch({ args, services, operations }, { id, text }) {
59
67
  return operations.operation({
60
68
  id,
61
69
  name: 'knowledge:search',
62
- args: { scopes: [...scopes].sort() },
70
+ args: { scopes: [...scopes].sort(), focus: focus && [...focus].sort(), k },
63
71
  effect: 'read'
64
72
  }, search, undefined, args.signal);
65
73
  }
@@ -79,6 +79,8 @@ async function remoteRound({ port, agent, kind, args, runId, emit }) {
79
79
  promptPrefix: args.promptPrefix,
80
80
  continuationNudge: args.continuationNudge,
81
81
  deliveredNudge: args.deliveredNudge,
82
+ goalNudge: args.goalNudge,
83
+ wrapUpNudge: args.wrapUpNudge,
82
84
  unforced: args.unforced
83
85
  }, { signal: args.signal, emit });
84
86
  return {
@@ -86,6 +88,7 @@ async function remoteRound({ port, agent, kind, args, runId, emit }) {
86
88
  final: result.final,
87
89
  history: args.history,
88
90
  cacheable: true,
91
+ keyed: args.cacheKey !== undefined,
89
92
  unproven: result.unproven ?? null,
90
93
  replay: result.replay ?? null,
91
94
  reasoningDeltas: result.reasoningDeltas,
@@ -7,7 +7,7 @@ import { clipRawCall, recoverMarkupToolCalls, recoverPrintedSkillLoad, recoverSk
7
7
  import { unquoteArg } from '../../../helpers/model-args.js';
8
8
  import { Agent } from '../../../agent/index.js';
9
9
  import { loadedTools } from '../../sdk-tool.js';
10
- import { FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE, TOOL_CONTINUATION_NUDGE } from '../../tool-turns.js';
10
+ import { FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE, TOOL_CONTINUATION_NUDGE, WRAP_UP_NUDGE } from '../../tool-turns.js';
11
11
  import { HarnessLog } from '../../../log.js';
12
12
  import { toolDialectFor } from '../../../models/model-catalog.js';
13
13
  import { loadedSkills } from '../session.js';
@@ -45,6 +45,7 @@ export const streaming = async function streaming({ emit, input: { sdk, args, se
45
45
  replay: recovered.replay,
46
46
  history: recovered.history ? spliceFrom(context.history, recovered.history) : undefined,
47
47
  cacheable: recovered.cacheable,
48
+ keyed: recovered.keyed,
48
49
  cut: recovered.cut
49
50
  };
50
51
  };
@@ -121,6 +122,8 @@ function prepareStreamingRound({ args, session, operations, context }) {
121
122
  failureResults: context.failureResults,
122
123
  continuationNudge: context.policy.continuationNudge,
123
124
  deliveredNudge: context.policy.deliveredNudge,
125
+ goalNudge: context.policy.goalNudge,
126
+ wrapUpNudge: context.policy.wrapUpNudge,
124
127
  tools: session.sdkTools,
125
128
  ...roundGenerationParams(context, session, responseFormat),
126
129
  responseFormat,
@@ -175,7 +178,12 @@ function planned(context, params) {
175
178
  }
176
179
  return plans(context.history) ? params : { ...params, reasoning_budget: 0 };
177
180
  }
178
- const NUDGES = new Set([TOOL_CONTINUATION_NUDGE, FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE]);
181
+ const NUDGES = new Set([
182
+ TOOL_CONTINUATION_NUDGE,
183
+ FILE_DELIVERED_NUDGE,
184
+ WRAP_UP_NUDGE,
185
+ GOAL_CONTINUATION_NUDGE
186
+ ]);
179
187
  const FAILED_RESULT = /"error"\s*:|"exitCode"\s*:\s*[1-9]/;
180
188
  function plans(history) {
181
189
  for (const entry of [...history].reverse()) {
@@ -29,6 +29,8 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
29
29
  failureResults: context.failureResults,
30
30
  continuationNudge: context.policy.continuationNudge,
31
31
  deliveredNudge: context.policy.deliveredNudge,
32
+ goalNudge: context.policy.goalNudge,
33
+ wrapUpNudge: context.policy.wrapUpNudge,
32
34
  tools: session.sdkTools,
33
35
  generationParams: wrapUpParams(session.generationParams),
34
36
  toolDialect: args.model ? toolDialectFor(args.model) : undefined,
@@ -69,6 +71,7 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
69
71
  replay,
70
72
  history: recovered.history ? spliceFrom(context.history, recovered.history) : undefined,
71
73
  cacheable: recovered.cacheable,
74
+ keyed: recovered.keyed,
72
75
  response: replay || contentText || fallbackResponse
73
76
  };
74
77
  };
@@ -9,7 +9,7 @@ import { runEngine } from './engine.js';
9
9
  import { didDrainTimeOut, raceDrain } from '../../helpers/drain.js';
10
10
  import { RunLog } from '../../run-log/index.js';
11
11
  import { stableStringify } from '../../helpers/stable-stringify.js';
12
- import { checkGoal, checkMaxToolRounds, FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE, GOAL_STALLED_NUDGE, GOAL_ROUNDS, MAX_TOOL_ROUNDS, TOOL_CONTEXT_BOUNDARY_MESSAGE, TOOL_CONTINUATION_NUDGE, TOOL_CUT_OFF_MESSAGE, TOOL_DENIED_MESSAGE, TOOL_REPEATED_MESSAGE, TOOL_ROUND_CUT_MESSAGE, TOOL_UNCHANGED_MESSAGE } from '../tool-turns.js';
12
+ import { checkGoal, checkMaxToolRounds, FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE, GOAL_STALLED_NUDGE, GOAL_ROUNDS, MAX_TOOL_ROUNDS, TOOL_CONTEXT_BOUNDARY_MESSAGE, TOOL_CONTINUATION_NUDGE, WRAP_UP_NUDGE, TOOL_CUT_OFF_MESSAGE, TOOL_DENIED_MESSAGE, TOOL_REPEATED_MESSAGE, TOOL_ROUND_CUT_MESSAGE, TOOL_UNCHANGED_MESSAGE } from '../tool-turns.js';
13
13
  import { createSession } from './session.js';
14
14
  import { captureFacts } from './durable.js';
15
15
  import { completionPorts } from './ports.js';
@@ -355,6 +355,7 @@ function runPolicy({ maxToolRounds, goal, wording }) {
355
355
  maxToolRounds: checkMaxToolRounds(goal?.rounds ?? maxToolRounds ?? (goal ? GOAL_ROUNDS : MAX_TOOL_ROUNDS)),
356
356
  continuationNudge: wording?.toolContinuation ?? TOOL_CONTINUATION_NUDGE,
357
357
  deliveredNudge: wording?.fileDelivered ?? FILE_DELIVERED_NUDGE,
358
+ wrapUpNudge: wording?.wrapUp ?? WRAP_UP_NUDGE,
358
359
  deniedMessage: wording?.toolDenied ?? TOOL_DENIED_MESSAGE,
359
360
  cutOffMessage: wording?.toolCutOff ?? TOOL_CUT_OFF_MESSAGE,
360
361
  contextBoundaryMessage: wording?.toolContextBoundary ?? TOOL_CONTEXT_BOUNDARY_MESSAGE,
@@ -9,6 +9,8 @@ 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';
12
14
  import { CompletionMachine } from '../../machine/index.js';
13
15
  function readRestoredSnapshot(value) {
14
16
  if (!isRecord(value) || Array.isArray(value))
@@ -113,7 +115,7 @@ export async function* runEngine(run, options = {}) {
113
115
  yield started(run);
114
116
  const invokes = createInvokeTracker();
115
117
  const boot = RunLog.boundaryBoot(journal);
116
- const mailbox = createEventMailbox();
118
+ const mailbox = new EventMailbox();
117
119
  const { ports, context } = await run.start({
118
120
  operations: createOperationPort(journal),
119
121
  invokes,
@@ -149,7 +151,6 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
149
151
  const pausedMs = run.resume && journal.snapshotSavedAt !== undefined
150
152
  ? Math.max(0, now() - journal.snapshotSavedAt)
151
153
  : 0;
152
- const { queue } = mailbox;
153
154
  let detached = false;
154
155
  const detach = () => {
155
156
  detached = true;
@@ -164,14 +165,17 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
164
165
  wakeVersion++;
165
166
  wake();
166
167
  };
168
+ let pause = () => { };
169
+ let inputLimitNotified = false;
167
170
  mailbox.notify = notify;
171
+ mailbox.onOverflow = () => queueMicrotask(pause);
168
172
  const { actor, persistence } = await RunLog.createPersistedActor(journal, machine, notify, now);
169
173
  actor.on('*', (event) => {
170
- queue.push(event);
174
+ mailbox.push(event);
171
175
  notify();
172
176
  });
173
177
  actor.subscribe({ next: notify, error: notify });
174
- const pause = () => {
178
+ pause = () => {
175
179
  if (actor.getSnapshot().status === 'active') {
176
180
  actor.send({ type: 'PAUSE' });
177
181
  }
@@ -189,11 +193,30 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
189
193
  return pumping;
190
194
  }
191
195
  if ('reason' in item) {
192
- queue.push({ type: 'input-rejected', runId, reason: item.reason });
196
+ mailbox.push({ type: 'input-rejected', runId, reason: item.reason });
193
197
  notify();
194
198
  }
195
199
  else {
196
- actor.send(inputMessage(item));
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
+ }
197
220
  }
198
221
  return pumping;
199
222
  }).catch(noop);
@@ -225,7 +248,11 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
225
248
  if (journal.hasPendingFlush()) {
226
249
  await persistence.flush();
227
250
  }
228
- yield* drainQueue(queue);
251
+ yield* drainQueue(mailbox);
252
+ if (mailbox.failure) {
253
+ const snapshot = actor.getSnapshot();
254
+ return { status: 'error', snapshot, error: mailbox.failure };
255
+ }
229
256
  if (isActiveIdle(actor.getSnapshot()) && !signal?.aborted) {
230
257
  actor.send({ type: 'START' });
231
258
  }
@@ -241,7 +268,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
241
268
  ? await drainSettling({ actor, persistence, durable, detach })
242
269
  : undefined;
243
270
  if (settlingResult) {
244
- yield* drainQueue(queue);
271
+ yield* drainQueue(mailbox);
245
272
  return settlingResult;
246
273
  }
247
274
  if (isSettling) {
@@ -255,12 +282,12 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
255
282
  durable,
256
283
  detach,
257
284
  journal,
258
- queue,
285
+ queue: mailbox,
259
286
  runId
260
287
  });
261
288
  }
262
289
  const observedWakeVersion = wakeVersion;
263
- if (queue.length) {
290
+ if (mailbox.size) {
264
291
  continue;
265
292
  }
266
293
  await new Promise((resolve) => {
@@ -271,7 +298,7 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
271
298
  });
272
299
  }
273
300
  await persistence.flush();
274
- yield* drainQueue(queue);
301
+ yield* drainQueue(mailbox);
275
302
  return { status: 'done', snapshot: actor.getSnapshot() };
276
303
  }
277
304
  finally {
@@ -392,24 +419,13 @@ function settling(snapshot) {
392
419
  return value === 'pausing';
393
420
  }
394
421
  function* drainQueue(queue) {
395
- while (queue.length) {
422
+ while (queue.size) {
396
423
  const event = queue.shift();
397
424
  if (event) {
398
425
  yield event;
399
426
  }
400
427
  }
401
428
  }
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
- }
413
429
  function createOperationPort(journal) {
414
430
  return Object.freeze({
415
431
  flush: () => journal.flush(),
@@ -0,0 +1,20 @@
1
+ import type { EngineEvent } from '../../machine/index.ts';
2
+ export declare const EVENT_MAILBOX_MAX_EVENTS = 512;
3
+ export declare const EVENT_MAILBOX_MAX_BYTES: number;
4
+ export declare const EVENT_MAILBOX_TEXT_CHUNK = 8192;
5
+ export declare class EventMailbox {
6
+ notify(): void;
7
+ onOverflow(): void;
8
+ private readonly _events;
9
+ private _head;
10
+ private _bytes;
11
+ private _failure;
12
+ get size(): number;
13
+ get failure(): Error | null;
14
+ get bytes(): number;
15
+ push(event: EngineEvent): boolean;
16
+ private pushText;
17
+ private pushEvent;
18
+ emit(event: EngineEvent): void;
19
+ shift(): EngineEvent | undefined;
20
+ }
@@ -0,0 +1,110 @@
1
+ import b4a from 'b4a';
2
+ export const EVENT_MAILBOX_MAX_EVENTS = 512;
3
+ export const EVENT_MAILBOX_MAX_BYTES = 1024 * 1024;
4
+ export const EVENT_MAILBOX_TEXT_CHUNK = 8192;
5
+ export class EventMailbox {
6
+ notify() { }
7
+ onOverflow() { }
8
+ _events = [];
9
+ _head = 0;
10
+ _bytes = 0;
11
+ _failure = null;
12
+ get size() {
13
+ return this._events.length - this._head;
14
+ }
15
+ get failure() {
16
+ return this._failure;
17
+ }
18
+ get bytes() {
19
+ return this._bytes;
20
+ }
21
+ push(event) {
22
+ if (this._failure) {
23
+ return false;
24
+ }
25
+ if (isLongText(event)) {
26
+ return this.pushText(event);
27
+ }
28
+ return this.pushEvent(event);
29
+ }
30
+ pushText(event) {
31
+ let offset = 0;
32
+ while (offset < event.text.length) {
33
+ let end = Math.min(offset + EVENT_MAILBOX_TEXT_CHUNK, event.text.length);
34
+ if (end < event.text.length && isHighSurrogate(event.text.charCodeAt(end - 1))) {
35
+ end--;
36
+ }
37
+ if (!this.pushEvent({ ...event, text: event.text.slice(offset, end) })) {
38
+ return false;
39
+ }
40
+ offset = end;
41
+ }
42
+ return true;
43
+ }
44
+ pushEvent(event) {
45
+ if (this._failure) {
46
+ return false;
47
+ }
48
+ const tail = this.size ? this._events[this._events.length - 1] : undefined;
49
+ if (tail && canCoalesce(tail, event)) {
50
+ const joined = `${tail.text ?? ''}${event.text ?? ''}`;
51
+ if (joined.length <= EVENT_MAILBOX_TEXT_CHUNK) {
52
+ const nextBytes = this._bytes - eventBytes(tail) + eventBytes({ ...tail, text: joined });
53
+ if (nextBytes <= EVENT_MAILBOX_MAX_BYTES) {
54
+ this._events[this._events.length - 1] = { ...tail, text: joined };
55
+ this._bytes = nextBytes;
56
+ return true;
57
+ }
58
+ }
59
+ }
60
+ const bytes = eventBytes(event);
61
+ if (this.size >= EVENT_MAILBOX_MAX_EVENTS || this._bytes + bytes > EVENT_MAILBOX_MAX_BYTES) {
62
+ this._failure = new Error('Completion output buffer limit exceeded');
63
+ this.onOverflow();
64
+ return false;
65
+ }
66
+ this._events.push(event);
67
+ this._bytes += bytes;
68
+ return true;
69
+ }
70
+ emit(event) {
71
+ this.push(event);
72
+ this.notify();
73
+ }
74
+ shift() {
75
+ if (this._head === this._events.length) {
76
+ return undefined;
77
+ }
78
+ const event = this._events[this._head++];
79
+ this._bytes -= eventBytes(event);
80
+ if (this._head === this._events.length) {
81
+ this._events.length = 0;
82
+ this._head = 0;
83
+ return event;
84
+ }
85
+ if (this._head >= 128 && this._head * 2 >= this._events.length) {
86
+ this._events.splice(0, this._head);
87
+ this._head = 0;
88
+ }
89
+ return event;
90
+ }
91
+ }
92
+ function isLongText(event) {
93
+ return ((event.type === 'content' || event.type === 'thinking') &&
94
+ typeof event.text === 'string' &&
95
+ event.text.length > EVENT_MAILBOX_TEXT_CHUNK);
96
+ }
97
+ function isHighSurrogate(code) {
98
+ return code >= 0xd800 && code <= 0xdbff;
99
+ }
100
+ function canCoalesce(left, right) {
101
+ return ((left.type === 'content' || left.type === 'thinking') &&
102
+ left.type === right.type &&
103
+ left.runId === right.runId &&
104
+ left.round === right.round &&
105
+ typeof left.text === 'string' &&
106
+ typeof right.text === 'string');
107
+ }
108
+ function eventBytes(event) {
109
+ return b4a.byteLength(JSON.stringify(event), 'utf8');
110
+ }
@@ -53,6 +53,7 @@ export interface CompletionArgs {
53
53
  wording?: {
54
54
  toolContinuation?: string;
55
55
  fileDelivered?: string;
56
+ wrapUp?: string;
56
57
  toolDenied?: string;
57
58
  toolCutOff?: string;
58
59
  toolRoundCut?: string;