@qvac/harness 1.0.0-rc.5 → 1.0.0-rc.7

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 (123) hide show
  1. package/CHANGELOG.md +245 -23
  2. package/README.md +19 -7
  3. package/dist-lib/index.d.ts +5 -3
  4. package/dist-lib/index.js +43 -2
  5. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.js +13 -3
  6. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +8 -1
  7. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +21 -19
  8. package/dist-lib/lib/capabilities/completion-engine/actors/resolving.js +11 -4
  9. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +10 -1
  10. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +9 -3
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +36 -19
  12. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.d.ts +1 -1
  13. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +9 -11
  14. package/dist-lib/lib/capabilities/completion-engine/driver.js +3 -0
  15. package/dist-lib/lib/capabilities/completion-engine/index.d.ts +4 -1
  16. package/dist-lib/lib/capabilities/completion-engine/index.js +3 -0
  17. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +15 -1
  18. package/dist-lib/lib/capabilities/completion-engine/model-round.js +52 -0
  19. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -3
  20. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -2
  21. package/dist-lib/lib/capabilities/completion-engine/tool-sets.d.ts +24 -0
  22. package/dist-lib/lib/capabilities/completion-engine/tool-sets.js +15 -0
  23. package/dist-lib/lib/capabilities/completion-engine/turns.js +14 -4
  24. package/dist-lib/lib/capabilities/detect-language.d.ts +2 -1
  25. package/dist-lib/lib/capabilities/detect-language.js +14 -2
  26. package/dist-lib/lib/capabilities/sdk-tool.d.ts +9 -1
  27. package/dist-lib/lib/capabilities/sdk-tool.js +21 -2
  28. package/dist-lib/lib/capabilities/tool-plan.d.ts +4 -0
  29. package/dist-lib/lib/capabilities/tool-plan.js +15 -0
  30. package/dist-lib/lib/connect.d.ts +2 -0
  31. package/dist-lib/lib/connect.js +79 -3
  32. package/dist-lib/lib/contract/run.d.ts +2 -0
  33. package/dist-lib/lib/contract-types.d.ts +5 -0
  34. package/dist-lib/lib/errors.d.ts +4 -0
  35. package/dist-lib/lib/errors.js +6 -0
  36. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  37. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  38. package/dist-lib/lib/helpers/goal-check.d.ts +2 -0
  39. package/dist-lib/lib/helpers/goal-check.js +18 -0
  40. package/dist-lib/lib/helpers/require-peers.d.ts +3 -0
  41. package/dist-lib/lib/helpers/require-peers.js +23 -0
  42. package/dist-lib/lib/machine/completion/actions/completion.js +30 -11
  43. package/dist-lib/lib/machine/completion/context.js +2 -1
  44. package/dist-lib/lib/machine/completion/rules.d.ts +1 -1
  45. package/dist-lib/lib/machine/completion/rules.js +7 -8
  46. package/dist-lib/lib/machine/completion/types.d.ts +1 -0
  47. package/dist-lib/lib/models/llm-presets.d.ts +1 -0
  48. package/dist-lib/lib/models/model-catalog.js +1 -1
  49. package/dist-lib/lib/models/model-pool.d.ts +4 -0
  50. package/dist-lib/lib/models/model-pool.js +4 -1
  51. package/dist-lib/lib/models/opencl-cache.js +2 -2
  52. package/dist-lib/lib/plugins/registry.d.ts +2 -0
  53. package/dist-lib/lib/plugins/registry.js +4 -0
  54. package/dist-lib/lib/prompt.d.ts +2 -1
  55. package/dist-lib/lib/prompt.js +12 -12
  56. package/dist-lib/lib/residency/completion-runtime.d.ts +9 -1
  57. package/dist-lib/lib/residency/completion-runtime.js +29 -26
  58. package/dist-lib/lib/residency/index.d.ts +4 -0
  59. package/dist-lib/lib/residency/index.js +6 -1
  60. package/dist-lib/lib/round-host.d.ts +12 -0
  61. package/dist-lib/lib/round-host.js +57 -0
  62. package/dist-lib/lib/round-port.d.ts +24 -0
  63. package/dist-lib/lib/round-port.js +81 -0
  64. package/dist-lib/lib/sdk-loader.d.ts +1 -1
  65. package/dist-lib/lib/sdk-loader.js +30 -6
  66. package/dist-lib/lib/sdk-storage.d.ts +1 -0
  67. package/dist-lib/lib/sdk-storage.js +18 -2
  68. package/dist-lib/lib/serve.js +68 -6
  69. package/dist-lib/lib/sidecar/index.d.ts +10 -0
  70. package/dist-lib/lib/sidecar/index.js +35 -3
  71. package/dist-lib/lib/sidecar/user-plugins.d.ts +1 -0
  72. package/dist-lib/lib/sidecar/user-plugins.js +1 -1
  73. package/dist-lib/lib/tools/files/grep.js +113 -15
  74. package/dist-lib/lib/tools/fs/edit-match.js +75 -7
  75. package/dist-lib/lib/tools/fs/search.d.ts +1 -1
  76. package/dist-lib/lib/tools/fs/search.js +2 -1
  77. package/dist-lib/lib/tools/http-request.js +1 -0
  78. package/dist-lib/lib/tools/index.d.ts +2 -1
  79. package/dist-lib/lib/tools/index.js +2 -2
  80. package/dist-lib/lib/tools/skills/skill-state-constants.d.ts +1 -0
  81. package/dist-lib/lib/tools/skills/skill-state-constants.js +4 -0
  82. package/dist-lib/lib/wire.d.ts +13 -0
  83. package/dist-lib/lib/wire.js +44 -1
  84. package/dist-lib/plugins/coding/read-only.d.ts +1 -0
  85. package/dist-lib/plugins/coding/read-only.js +264 -0
  86. package/dist-lib/plugins/coding/session.d.ts +3 -1
  87. package/dist-lib/plugins/coding/session.js +19 -2
  88. package/dist-lib/plugins/egress-proxy/index.d.ts +2 -2
  89. package/dist-lib/plugins/egress-proxy/index.js +5 -3
  90. package/dist-lib/plugins/image/index.js +7 -2
  91. package/dist-lib/plugins/language-hint/index.js +4 -1
  92. package/dist-lib/plugins/mcp/server.js +1 -1
  93. package/dist-lib/plugins/music/index.js +6 -2
  94. package/dist-lib/plugins/obsidian/readiness.js +2 -2
  95. package/dist-lib/plugins/obsidian/vault-read.js +17 -16
  96. package/dist-lib/plugins/python/index.js +1 -0
  97. package/dist-lib/plugins/python/loader.d.ts +1 -0
  98. package/dist-lib/plugins/python/loader.js +8 -0
  99. package/dist-lib/plugins/quickjs/index.js +4 -0
  100. package/dist-lib/plugins/quickjs/runtime.js +8 -3
  101. package/dist-lib/plugins/run-report/index.js +6 -2
  102. package/dist-lib/plugins/run-report/layout.js +1 -1
  103. package/dist-lib/plugins/sandbox-vm/index.js +3 -0
  104. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  105. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  106. package/dist-lib/plugins/speech/audio-resample.js +2 -1
  107. package/dist-lib/plugins/speech/index.d.ts +1 -0
  108. package/dist-lib/plugins/speech/index.js +8 -1
  109. package/dist-lib/plugins/speech/speech-runtime.js +3 -3
  110. package/dist-lib/plugins/translation/index.d.ts +1 -1
  111. package/dist-lib/plugins/translation/index.js +7 -3
  112. package/dist-lib/plugins/translation/translate.d.ts +2 -2
  113. package/dist-lib/plugins/translation/translate.js +7 -8
  114. package/dist-lib/plugins/walkie-talkie/index.d.ts +2 -2
  115. package/dist-lib/plugins/walkie-talkie/index.js +13 -5
  116. package/dist-lib/plugins/walkie-talkie/wire.d.ts +5 -0
  117. package/dist-lib/plugins/walkie-talkie/wire.js +6 -5
  118. package/dist-lib/schema/harness.js +12 -2
  119. package/dist-lib/spec/hrpc/messages.js +208 -150
  120. package/dist-lib/spec/hyperschema/index.js +208 -150
  121. package/dist-lib/spec/hyperschema/schema.json +125 -84
  122. package/dist-lib/spec/hyperschema/types.d.ts +4 -3
  123. package/package.json +150 -25
@@ -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 } from '../../../helpers/goal-check.js';
18
+ import { 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,9 +38,10 @@ function takesCommand(tools) {
38
38
  return tools.some((tool) => 'command' in tool.parameters.properties);
39
39
  }
40
40
  function checksAsk({ goal }, checkable) {
41
- return goal && checkable && !goal.checks.length
42
- ? [{ role: 'user', content: GOAL_CHECKS_ASK }]
43
- : [];
41
+ if (!goal || !checkable || goal.named) {
42
+ return [];
43
+ }
44
+ return [{ role: 'user', content: goal.checks.length ? GOAL_PROOF_ASK : GOAL_CHECKS_ASK }];
44
45
  }
45
46
  export function preparing(source) {
46
47
  return ({ input, context, reconstruct, emit }) => prepare({ input, context, reconstruct, source, emit });
@@ -98,12 +99,16 @@ async function prepare({ input, context, reconstruct, source, emit }) {
98
99
  policy: session.access
99
100
  }, deferTools ? promptForWholeTools(session.agentPorts, tools) : session.agentPorts);
100
101
  const { system, activation, activeSkills, mention, grantedOps } = resolved;
101
- const enabled = withToolSearch(resolved.enabled);
102
- const sdkTools = toSdkTools(enabled);
102
+ const catalog = withToolSearch(resolved.select(new Set(activeSkills.map(({ name }) => name))));
103
+ const callable = (loaded) => {
104
+ const names = new Set(resolved.select(loaded).map(({ name }) => name));
105
+ return catalog.filter(({ name }) => name === TOOL_SEARCH_TOOL_NAME || names.has(name));
106
+ };
107
+ const enabled = callable(loadedSkills);
108
+ const sdkTools = toSdkTools(catalog);
103
109
  const { skillsSelected } = activation;
104
110
  const sent = reconstruct ? context.history[0] : undefined;
105
111
  let systemContent = sent && 'role' in sent && sent.role === 'system' ? sent.content : system.text;
106
- let systemParts = system;
107
112
  const promptPrefix = promptPrefixHash({ system: systemContent, tools: renderedTools(sdkTools) });
108
113
  const promptParts = promptUsageParts({ system, toolSchemas: renderedTools(sdkTools) });
109
114
  const logSelection = (prefix) => {
@@ -125,34 +130,31 @@ async function prepare({ input, context, reconstruct, source, emit }) {
125
130
  });
126
131
  };
127
132
  session.reselectTools = (loaded) => {
128
- const reselected = withToolSearch(resolved.select(loaded));
133
+ const reselected = callable(loaded);
129
134
  const names = reselected.map((tool) => tool.name).join();
130
135
  const changed = names !== session.enabled.map((tool) => tool.name).join();
131
136
  if (changed) {
132
137
  session.enabled = reselected;
133
- session.sdkTools = toSdkTools(reselected);
134
- session.promptParts = promptUsageParts({
135
- system: systemParts,
136
- toolSchemas: renderedTools(session.sdkTools)
137
- });
138
138
  }
139
- const prefix = promptPrefixHash({
140
- system: systemContent,
141
- tools: renderedTools(session.sdkTools)
142
- });
139
+ const prefix = promptPrefixHash({ system: systemContent, tools: renderedTools(sdkTools) });
143
140
  if (changed) {
144
141
  logSelection(prefix);
145
142
  }
146
143
  return prefix;
147
144
  };
148
145
  session.preloadSystem = (skill) => {
149
- systemParts = resolved.systemFor(new Set([...loadedSkills, skill]));
146
+ const systemParts = resolved.systemFor(new Set([...loadedSkills, skill]));
150
147
  systemContent = systemParts.text;
148
+ session.promptParts = promptUsageParts({
149
+ system: systemParts,
150
+ toolSchemas: renderedTools(sdkTools)
151
+ });
151
152
  return systemContent;
152
153
  };
153
154
  const firstTurn = context.round === 0 && !context.directSearchDone;
154
155
  const added = addedContext(hits, promptContext);
155
- const time = currentTimeAnnotation(new Date(session.startedAt));
156
+ const sentAt = storedMessages.findLast((turn) => turn.role === 'user')?.sentAt;
157
+ const time = currentTimeAnnotation(new Date(sentAt || session.startedAt));
156
158
  const withSystem = (turns) => systemContent ? [{ role: 'system', content: systemContent }, ...turns] : turns;
157
159
  const checks = checksAsk(context, takesCommand(enabled));
158
160
  const initialHistory = withSystem([...withTurnContext(messages, added), ...checks]);
@@ -4,10 +4,11 @@ import { AbortedError } from '../../../helpers/race-abort.js';
4
4
  import { HarnessLog } from '../../../log.js';
5
5
  import { MALFORMED_CALL_ID, stripToolCallMarkup } from '../../../helpers/tool-call-markup.js';
6
6
  import { toolResultTurn } from '../../tool-turns.js';
7
- import { unloadedTools } from '../../sdk-tool.js';
7
+ import { loadTurns, unloadedTools } from '../../sdk-tool.js';
8
8
  import { assistantToolTurn } from '../turns.js';
9
9
  import { resolveToolCalls } from '../tool-execution.js';
10
10
  import { toolContext } from './execution-plan.js';
11
+ import { withCatalogSkillName } from '../../tool-plan.js';
11
12
  import { detachJson } from '../../../helpers/detach-json.js';
12
13
  import { CompletionMachine } from '../../../machine/index.js';
13
14
  const REISSUE_HINT = 'Re-issue the tool call with complete, valid markup.';
@@ -29,7 +30,8 @@ function narratedIntent(spoken) {
29
30
  export const resolving = async function resolving({ input: deps, context }) {
30
31
  const { args, session } = deps;
31
32
  const round = context.lastRound;
32
- const toolCalls = firstOfEach(round.toolCalls, session).map((call) => ({
33
+ const named = round.toolCalls.map((call) => withCatalogSkillName(call, args.skillCatalog ?? []));
34
+ const toolCalls = firstOfEach(named, session).map((call) => ({
33
35
  id: call.id,
34
36
  name: call.name,
35
37
  arguments: call.arguments,
@@ -127,12 +129,17 @@ function resolvedOutput({ context, round, resolved, repeated, deps }) {
127
129
  const { session } = deps;
128
130
  const cutId = cutCallId(round);
129
131
  const cutTail = CompletionMachine.cutShort(round) && Boolean(round.toolErrors?.length);
130
- const history = [
132
+ const asked = [
131
133
  ...context.history,
132
134
  {
133
135
  role: 'assistant',
134
136
  content: assistantToolTurn(round.contentText, resolved.map(({ call, args: callArgs }) => ({ name: call.name, arguments: callArgs })))
135
- },
137
+ }
138
+ ];
139
+ const loads = loadTurns(session.sdkTools, resolved.map(({ call }) => call.name), asked);
140
+ const history = [
141
+ ...asked,
142
+ ...loads,
136
143
  ...(cutTail ? [cutTailTurn(context, round)] : []),
137
144
  ...(repeated ? [repeatedCallTurn(context)] : [])
138
145
  ];
@@ -3,6 +3,7 @@ import { annotateCompletionHistoryLastUserTime, directToolHistory, withLastUserN
3
3
  import { labelOf, skillEmojiFrom } from '../loop.js';
4
4
  import { loadedSkills } from '../session.js';
5
5
  import { PRELOAD_ID_PREFIX } from '../../tool-turns.js';
6
+ import { skillLoadTurns } from '../../sdk-tool.js';
6
7
  import { Agent } from '../../../agent/index.js';
7
8
  import { errorMessage, isRecord } from '../../../guards.js';
8
9
  import { isFailureResultReference } from '../../../helpers/failure-result.js';
@@ -41,13 +42,21 @@ export const skillStep = {
41
42
  session.skillIcon = skillEmojiFrom(session.inContextSkills, name) ?? session.skillIcon;
42
43
  const typed = withSystem(annotateCompletionHistoryLastUserTime(context.history, new Date(session.startedAt)), session.preloadSystem?.(name));
43
44
  session.reselectTools?.(new Set([...loadedSkills(context, session), name]));
44
- const history = directToolHistory(typed, {
45
+ const called = directToolHistory(typed, {
45
46
  tool: step.tool,
46
47
  id: step.id,
47
48
  args: step.args,
48
49
  output: result,
49
50
  nudge: context.policy.continuationNudge
50
51
  });
52
+ const loaded = called.slice(0, -1);
53
+ const skill = session.inContextSkills.find((entry) => entry.name === name);
54
+ const loads = skillLoadTurns(skill, {
55
+ sent: session.sdkTools,
56
+ enabled: session.enabled,
57
+ history: loaded
58
+ });
59
+ const history = [...loaded, ...loads, ...called.slice(-1)];
51
60
  return {
52
61
  history: spliceFrom(context.history, history),
53
62
  source: session.outbound.facts('skill', content),
@@ -1,6 +1,7 @@
1
1
  import { reportUnnamedWrites } from '../loop.js';
2
2
  import { recordWholeRound, runRecoveredRound } from '../round.js';
3
3
  import { ModelRound } from '../model-round.js';
4
+ import { ToolSets } from '../tool-sets.js';
4
5
  import { AbortedError } from '../../../helpers/race-abort.js';
5
6
  import { HarnessLog } from '../../../log.js';
6
7
  const BOUNDARY_UNFLAGGED = "length stop without contextBoundary: the host's @qvac/inference patch lacks the contextBoundary hunk";
@@ -59,21 +60,26 @@ async function remoteRound({ port, kind, args, runId, emit }) {
59
60
  modelId: params.modelId,
60
61
  history: params.history,
61
62
  tools: params.tools,
63
+ toolSet: params.tools && ToolSets.hash(params.tools),
62
64
  generationParams: params.generationParams,
63
65
  responseFormat: params.responseFormat,
64
66
  toolDialect: params.toolDialect,
65
67
  cacheKey: args.cacheKey,
66
68
  promptPrefix: args.promptPrefix,
67
69
  continuationNudge: args.continuationNudge,
68
- deliveredNudge: args.deliveredNudge
70
+ deliveredNudge: args.deliveredNudge,
71
+ unforced: args.unforced
69
72
  }, { signal: args.signal, emit });
70
73
  return {
71
74
  contentText: result.contentText,
72
75
  final: result.final,
73
76
  history: args.history,
74
77
  cacheable: true,
75
- unproven: null,
76
- replay: null,
78
+ unproven: result.unproven ?? null,
79
+ replay: result.replay ?? null,
80
+ reasoningDeltas: result.reasoningDeltas,
81
+ ctxSize: result.ctxSize,
82
+ overflows: result.overflows,
77
83
  cut: result.cut
78
84
  };
79
85
  }
@@ -6,7 +6,8 @@ import { truncateAtControlToken } from '../../../helpers/control-tokens.js';
6
6
  import { clipRawCall, recoverMarkupToolCalls, recoverPrintedSkillLoad, recoverSkillNamedCall, stripToolResponseBlocks } from '../../../helpers/tool-call-markup.js';
7
7
  import { unquoteArg } from '../../../helpers/model-args.js';
8
8
  import { Agent } from '../../../agent/index.js';
9
- import { loadedTools, unloadedTools } from '../../sdk-tool.js';
9
+ import { loadedTools } from '../../sdk-tool.js';
10
+ import { FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE, TOOL_CONTINUATION_NUDGE } from '../../tool-turns.js';
10
11
  import { HarnessLog } from '../../../log.js';
11
12
  import { toolDialectFor } from '../../../models/model-catalog.js';
12
13
  import { loadedSkills } from '../session.js';
@@ -47,28 +48,17 @@ export const streaming = async function streaming({ emit, input: { sdk, args, se
47
48
  };
48
49
  };
49
50
  function roundCalls({ recovered, session, context }) {
50
- const unloaded = unloadedTools(session.enabled, recovered.history ?? context.history);
51
51
  const calls = recoverToolCalls({ recovered, session, round: context.round });
52
- const callable = calls.filter((call) => !unloaded.has(call.name));
53
- const refused = calls.filter((call) => unloaded.has(call.name)).map(notLoaded);
54
- const toolCalls = identifyToolCalls(callable, session.runId, context.round);
52
+ const toolCalls = identifyToolCalls(calls, session.runId, context.round);
55
53
  const sdkErrors = recovered.final.toolErrors ?? [];
56
- if (!callable.length) {
57
- return { toolCalls, toolErrors: roundToolErrors([...sdkErrors, ...refused]) };
54
+ if (!calls.length) {
55
+ return { toolCalls, toolErrors: roundToolErrors(sdkErrors) };
58
56
  }
59
57
  const cut = CompletionMachine.cutShort({
60
58
  stopReason: recovered.final.stopReason,
61
59
  cut: recovered.cut
62
60
  });
63
- const tail = calls.at(-1);
64
- const unloadedTail = !sdkErrors.length && tail && unloaded.has(tail.name) ? [notLoaded(tail)] : [];
65
- return {
66
- toolCalls,
67
- toolErrors: cut ? roundToolErrors([...sdkErrors, ...unloadedTail]) : undefined
68
- };
69
- }
70
- function notLoaded(call) {
71
- return { code: 'UNKNOWN_TOOL', message: `Tool "${call.name}" is not loaded`, raw: call.raw };
61
+ return { toolCalls, toolErrors: cut ? roundToolErrors(sdkErrors) : undefined };
72
62
  }
73
63
  function roundToolErrors(errors) {
74
64
  if (!errors.length)
@@ -163,18 +153,45 @@ export function roundFold(args, session, context) {
163
153
  };
164
154
  }
165
155
  function roundGenerationParams(context, session, responseFormat) {
156
+ const params = planned(context, session.generationParams);
166
157
  const owesCall = context.narrated || (context.malformed && context.lastRound?.stopReason !== 'length');
167
158
  if (!owesCall ||
168
159
  !session.sdkTools?.length ||
169
160
  responseFormat ||
170
161
  loadedTools(context.history).size > 0) {
171
- return { generationParams: session.generationParams };
162
+ return { generationParams: params };
172
163
  }
173
164
  return {
174
- generationParams: { ...session.generationParams, reasoning_budget: 0, tool_choice: 'required' },
175
- unforced: { generationParams: session.generationParams }
165
+ generationParams: { ...params, reasoning_budget: 0, tool_choice: 'required' },
166
+ unforced: { generationParams: params }
176
167
  };
177
168
  }
169
+ function planned(context, params) {
170
+ if (params?.reasoning_rounds !== 'plan') {
171
+ return params;
172
+ }
173
+ return plans(context.history) ? params : { ...params, reasoning_budget: 0 };
174
+ }
175
+ const NUDGES = new Set([TOOL_CONTINUATION_NUDGE, FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE]);
176
+ const FAILED_RESULT = /"error"\s*:|"exitCode"\s*:\s*[1-9]/;
177
+ function plans(history) {
178
+ for (const entry of [...history].reverse()) {
179
+ if (!('role' in entry)) {
180
+ return true;
181
+ }
182
+ if (entry.role === 'assistant') {
183
+ return false;
184
+ }
185
+ const text = typeof entry.content === 'string' ? entry.content : null;
186
+ if (entry.role === 'user' && (text === null || !NUDGES.has(text))) {
187
+ return true;
188
+ }
189
+ if (entry.role === 'tool' && text !== null && FAILED_RESULT.test(text)) {
190
+ return true;
191
+ }
192
+ }
193
+ return true;
194
+ }
178
195
  function recoverToolCalls({ recovered, session, round }) {
179
196
  const markup = stripToolResponseBlocks(truncateAtControlToken(recovered.final.raw.fullText) || recovered.unproven || '');
180
197
  let calls = recovered.final.toolCalls?.length
@@ -1,4 +1,4 @@
1
- import type { CompletionActor } from '../session.ts';
1
+ import { type CompletionActor } from '../session.ts';
2
2
  import type { RoundDonePayload } from '../stages.ts';
3
3
  export declare const WRAP_UP_PREDICT = 4096;
4
4
  interface WrapUpOutput extends RoundDonePayload {
@@ -4,17 +4,17 @@ import { runRound } from './stream.js';
4
4
  import { roundFold } from './streaming.js';
5
5
  import { degenerateAnswer } from '../../../helpers/run-outcome.js';
6
6
  import { stripToolCallMarkup } from '../../../helpers/tool-call-markup.js';
7
- import { promptPrefixHash } from '../../prompt-prefix.js';
8
7
  import { materializeCompletionHistory } from '../../tool-turns.js';
8
+ import { toolDialectFor } from '../../../models/model-catalog.js';
9
+ import { loadedSkills } from '../session.js';
9
10
  import { CompletionMachine } from '../../../machine/index.js';
10
- import { isFailureResultReference } from '../../../helpers/failure-result.js';
11
11
  export const WRAP_UP_PREDICT = 4096;
12
12
  export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session, operations }, context }) {
13
13
  const { modelId, acquireRound, signal } = args;
14
14
  const cacheKey = !args.replaysContext && carriesRunOnlyText(context.history)
15
15
  ? undefined
16
16
  : (context.cacheKey ?? undefined);
17
- const promptPrefix = promptPrefixHash({ system: systemMessage(context), tools: undefined });
17
+ const promptPrefix = session.reselectTools?.(loadedSkills(context, session)) ?? context.promptPrefix;
18
18
  const startedAt = Date.now();
19
19
  const recovered = await runRound({
20
20
  sdk,
@@ -28,8 +28,9 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
28
28
  failureResults: context.failureResults,
29
29
  continuationNudge: context.policy.continuationNudge,
30
30
  deliveredNudge: context.policy.deliveredNudge,
31
- tools: undefined,
31
+ tools: session.sdkTools,
32
32
  generationParams: wrapUpParams(session.generationParams),
33
+ toolDialect: args.model ? toolDialectFor(args.model) : undefined,
33
34
  cacheKey,
34
35
  signal,
35
36
  round: context.roundsSent,
@@ -71,10 +72,11 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
71
72
  };
72
73
  };
73
74
  function wrapUpParams(params) {
74
- if (!params)
75
- return undefined;
75
+ if (!params) {
76
+ return { tool_choice: 'none' };
77
+ }
76
78
  const reasoning = Math.max(params.reasoning_budget ?? 0, 0);
77
- return { predict: reasoning + WRAP_UP_PREDICT, ...params };
79
+ return { predict: reasoning + WRAP_UP_PREDICT, ...params, tool_choice: 'none' };
78
80
  }
79
81
  function previewFinishedRound(state) {
80
82
  return {
@@ -82,10 +84,6 @@ function previewFinishedRound(state) {
82
84
  confirmedWrites: state.confirmedWrites
83
85
  };
84
86
  }
85
- function systemMessage(context) {
86
- const first = context.history[0];
87
- return first && !isFailureResultReference(first) && first.role === 'system' ? first.content : null;
88
- }
89
87
  function wrapOutcome(ctx) {
90
88
  if (ctx.outcome === 'mute' ||
91
89
  ctx.outcome === 'exhausted' ||
@@ -307,6 +307,9 @@ function isGenerationParams(value) {
307
307
  return (isRecord(value) &&
308
308
  (value.reasoning_budget === undefined ||
309
309
  (Number.isInteger(value.reasoning_budget) && Number(value.reasoning_budget) >= -1)) &&
310
+ (value.reasoning_rounds === undefined ||
311
+ value.reasoning_rounds === 'every' ||
312
+ value.reasoning_rounds === 'plan') &&
310
313
  [
311
314
  'temp',
312
315
  'top_p',
@@ -3,6 +3,7 @@ import { type EngineBoot, type EngineStep } from '../../run-log/index.ts';
3
3
  import type { CompletionSkillEntry } from '../skill-entry.ts';
4
4
  import { type CompletionRun, type CompletionRuntime } from './driver.ts';
5
5
  import type { CompletionArgs } from './loop.ts';
6
+ import { ModelRound } from './model-round.ts';
6
7
  export interface CompletionEngineOptions {
7
8
  hooks?: readonly HarnessHook[];
8
9
  outbound?: OutboundGuard;
@@ -17,6 +18,7 @@ export interface CompletionEngineOptions {
17
18
  }
18
19
  export declare class CompletionEngine {
19
20
  static WRAP_UP_PREDICT: number;
21
+ static serveModelRound: typeof ModelRound.serve;
20
22
  runtime: CompletionRuntime;
21
23
  hooks: readonly HarnessHook[];
22
24
  outbound: OutboundGuard;
@@ -28,4 +30,5 @@ export declare class CompletionEngine {
28
30
  }
29
31
  export type { CompletionArgs } from './loop.ts';
30
32
  export type { CompletionRun, CompletionRuntime } from './driver.ts';
31
- export type { ModelRoundEvent, ModelRoundIo, ModelRoundPort, ModelRoundRequest, ModelRoundResult } from './model-round.ts';
33
+ export type { ModelRoundEvent, ModelRoundIo, ModelRoundPort, ModelRoundRequest, ModelRoundResult, ModelRoundServeOptions } from './model-round.ts';
34
+ export { ToolSets } from './tool-sets.ts';
@@ -5,8 +5,10 @@ import { outboundGuard } from '../../tools/outbound-guard.js';
5
5
  import { defaultAgentPorts } from '../agent-ports.js';
6
6
  import { driveCompletion } from './driver.js';
7
7
  import { WRAP_UP_PREDICT } from './actors/wrap-up.js';
8
+ import { ModelRound } from './model-round.js';
8
9
  export class CompletionEngine {
9
10
  static WRAP_UP_PREDICT = WRAP_UP_PREDICT;
11
+ static serveModelRound = ModelRound.serve;
10
12
  runtime;
11
13
  hooks;
12
14
  outbound;
@@ -42,3 +44,4 @@ export class CompletionEngine {
42
44
  return new CompletionEngine(sdk, opts).run(args);
43
45
  }
44
46
  }
47
+ export { ToolSets } from './tool-sets.js';
@@ -1,7 +1,7 @@
1
1
  import type { CompletionFinal, Tool as SdkTool, ToolDialect } from '@qvac/sdk';
2
2
  import { type AbortSignal as BareAbortSignal } from 'bare-abort-controller';
3
3
  import type { TextEvent } from '../../helpers/thinking.ts';
4
- import type { LlmGenerationParams, Message, ResponseFormat, RunLifecycleEvent } from '../../contract/index.ts';
4
+ import type { CompletionSdk, LlmGenerationParams, Message, ResponseFormat, RoundModelLease, RunLifecycleEvent } from '../../contract/index.ts';
5
5
  export interface ModelRoundRequest {
6
6
  runId: string;
7
7
  round: number;
@@ -10,6 +10,7 @@ export interface ModelRoundRequest {
10
10
  modelId: string;
11
11
  history: Message[];
12
12
  tools?: SdkTool[] | undefined;
13
+ toolSet?: string | undefined;
13
14
  generationParams?: Partial<LlmGenerationParams> | undefined;
14
15
  responseFormat?: ResponseFormat | undefined;
15
16
  toolDialect?: ToolDialect | undefined;
@@ -17,11 +18,19 @@ export interface ModelRoundRequest {
17
18
  promptPrefix: string;
18
19
  continuationNudge: string;
19
20
  deliveredNudge: string;
21
+ unforced?: {
22
+ generationParams?: Partial<LlmGenerationParams> | undefined;
23
+ } | undefined;
20
24
  }
21
25
  export interface ModelRoundResult {
22
26
  contentText: string;
23
27
  final: CompletionFinal;
24
28
  cut?: string | undefined;
29
+ unproven?: string | null | undefined;
30
+ replay?: string | null | undefined;
31
+ reasoningDeltas?: number | undefined;
32
+ ctxSize?: number | undefined;
33
+ overflows?: number | undefined;
25
34
  }
26
35
  export type ModelRoundEvent = TextEvent;
27
36
  type RoundReset = Extract<RunLifecycleEvent, {
@@ -37,10 +46,15 @@ interface RunOptions {
37
46
  signal?: BareAbortSignal | undefined;
38
47
  emit(event: ModelRoundEvent | RoundReset): void;
39
48
  }
49
+ export interface ModelRoundServeOptions {
50
+ sdk?: CompletionSdk | undefined;
51
+ acquireRound?: ((signal?: BareAbortSignal) => Promise<RoundModelLease>) | undefined;
52
+ }
40
53
  export declare class ModelRound {
41
54
  port: ModelRoundPort;
42
55
  constructor(port: ModelRoundPort);
43
56
  run(request: ModelRoundRequest, options: RunOptions): Promise<ModelRoundResult>;
44
57
  static run(port: ModelRoundPort, request: ModelRoundRequest, { signal, emit }: RunOptions): Promise<ModelRoundResult>;
58
+ static serve(request: ModelRoundRequest, io: ModelRoundIo, { sdk, acquireRound }: ModelRoundServeOptions): Promise<ModelRoundResult>;
45
59
  }
46
60
  export {};
@@ -1,5 +1,6 @@
1
1
  import { AbortController } from 'bare-abort-controller';
2
2
  import { raceAbort } from '../../helpers/race-abort.js';
3
+ import { runRecoveredRound } from './round.js';
3
4
  export class ModelRound {
4
5
  port;
5
6
  constructor(port) {
@@ -41,5 +42,56 @@ export class ModelRound {
41
42
  open = false;
42
43
  }
43
44
  }
45
+ static async serve(request, io, { sdk, acquireRound }) {
46
+ const rounds = runRecoveredRound(sdk, servedArgs(request, io.signal, acquireRound));
47
+ let emit = io.emit;
48
+ for await (const event of served(rounds)) {
49
+ if (event.type === 'served') {
50
+ return result(event.round);
51
+ }
52
+ if (event.type === 'content' || event.type === 'thinking') {
53
+ emit(event);
54
+ }
55
+ else if (event.type === 'round-reset') {
56
+ emit = io.retake();
57
+ }
58
+ }
59
+ throw new Error('A served round ended without its result');
60
+ }
61
+ }
62
+ function servedArgs(request, signal, acquireRound) {
63
+ return {
64
+ modelId: request.modelId,
65
+ acquireRound,
66
+ history: request.history,
67
+ failureResults: {},
68
+ continuationNudge: request.continuationNudge,
69
+ deliveredNudge: request.deliveredNudge,
70
+ tools: request.tools,
71
+ generationParams: request.generationParams,
72
+ responseFormat: request.responseFormat,
73
+ toolDialect: request.toolDialect,
74
+ cacheKey: request.cacheKey,
75
+ signal,
76
+ round: request.round,
77
+ runId: request.runId,
78
+ promptPrefix: request.promptPrefix,
79
+ capture: false,
80
+ knownTools: request.tools,
81
+ unforced: request.unforced,
82
+ live: {
83
+ round: request.round,
84
+ kind: request.kind,
85
+ startedAt: Date.now(),
86
+ rawChars: 0,
87
+ reasoningDeltas: 0
88
+ }
89
+ };
90
+ }
91
+ async function* served(rounds) {
92
+ yield { type: 'served', round: yield* rounds };
93
+ }
94
+ function result({ contentText, final, cut, unproven, replay, reasoningDeltas, ctxSize, overflows }) {
95
+ return { contentText, final, cut, unproven, replay, reasoningDeltas, ctxSize, overflows };
44
96
  }
45
97
  const noop = () => { };
@@ -30,7 +30,7 @@ export interface RoundArgs {
30
30
  continuationNudge: string;
31
31
  deliveredNudge: string;
32
32
  tools?: SdkTool[] | undefined;
33
- generationParams?: LlmGenerationParams | undefined;
33
+ generationParams?: Partial<LlmGenerationParams> | undefined;
34
34
  responseFormat?: ResponseFormat | undefined;
35
35
  toolDialect?: ToolDialect | undefined;
36
36
  cacheKey?: string | undefined;
@@ -41,7 +41,7 @@ export interface RoundArgs {
41
41
  capture: boolean;
42
42
  knownTools?: ReadonlyArray<KnownTool> | undefined;
43
43
  unforced?: {
44
- generationParams: LlmGenerationParams | undefined;
44
+ generationParams?: Partial<LlmGenerationParams> | undefined;
45
45
  } | undefined;
46
46
  recordRequest?: ((request: ModelRequest, failures: readonly FailureTurn[]) => Promise<void>) | undefined;
47
47
  fold?: RoundFold | undefined;
@@ -67,7 +67,7 @@ export interface RoundFold {
67
67
  type RoundReset = Extract<RunLifecycleEvent, {
68
68
  type: 'round-reset';
69
69
  }>;
70
- type RoundEvent = TextEvent | InferenceCallEvent | InferenceSentEvent | RoundReset | FoldEvent;
70
+ export type RoundEvent = TextEvent | InferenceCallEvent | InferenceSentEvent | RoundReset | FoldEvent;
71
71
  export declare function runRecoveredRound(sdk: CompletionSdk | undefined, args: RoundArgs): AsyncGenerator<RoundEvent, RecoveredRound>;
72
72
  export declare function recordWholeRound(args: RoundArgs): Promise<CompletionParams>;
73
73
  export {};
@@ -698,8 +698,11 @@ function inferenceParams({ args, modelId, history, cacheable }) {
698
698
  });
699
699
  }
700
700
  function generationParams(args) {
701
- const host = args.generationParams ? detachJson(args.generationParams) : undefined;
702
- return args.tools?.length ? { parallel_tool_calls: true, ...host } : host;
701
+ const { reasoning_rounds: _rounds, ...host } = args.generationParams
702
+ ? detachJson(args.generationParams)
703
+ : {};
704
+ const sent = args.generationParams ? host : undefined;
705
+ return args.tools?.length ? { parallel_tool_calls: true, ...sent } : sent;
703
706
  }
704
707
  function inferenceCall({ args, candidate, modelId, params, cacheKey }) {
705
708
  return {
@@ -0,0 +1,24 @@
1
+ import type { Tool as SdkTool } from '@qvac/sdk';
2
+ export declare class ToolSets {
3
+ sets: Map<string, {
4
+ type: "function";
5
+ name: string;
6
+ description: string;
7
+ deferLoading?: boolean | undefined;
8
+ group?: string | undefined;
9
+ parameters: {
10
+ [x: string]: unknown;
11
+ type: "object";
12
+ properties: Record<string, {
13
+ [x: string]: unknown;
14
+ type?: "array" | "boolean" | "integer" | "null" | "number" | "object" | "string" | ("array" | "boolean" | "integer" | "null" | "number" | "object" | "string")[] | undefined;
15
+ description?: string | undefined;
16
+ enum?: (string | number | boolean | null)[] | undefined;
17
+ }>;
18
+ required?: string[] | undefined;
19
+ };
20
+ }[]>;
21
+ add(tools: SdkTool[]): string;
22
+ resolve(hash: string): SdkTool[] | undefined;
23
+ static hash(tools: readonly SdkTool[]): string;
24
+ }
@@ -0,0 +1,15 @@
1
+ import crypto from 'crypto';
2
+ export class ToolSets {
3
+ sets = new Map();
4
+ add(tools) {
5
+ const hash = ToolSets.hash(tools);
6
+ this.sets.set(hash, tools);
7
+ return hash;
8
+ }
9
+ resolve(hash) {
10
+ return this.sets.get(hash);
11
+ }
12
+ static hash(tools) {
13
+ return crypto.createHash('sha256').update(JSON.stringify(tools)).digest('hex');
14
+ }
15
+ }