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

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 (79) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +36 -6
  3. package/dist-lib/index.d.ts +1 -0
  4. package/dist-lib/index.js +2 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +20 -1
  6. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +1 -1
  7. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +10 -6
  8. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +2 -2
  9. package/dist-lib/lib/capabilities/completion-engine/actors/stream.d.ts +1 -1
  10. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +8 -0
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +6 -2
  12. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +10 -4
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +15 -0
  14. package/dist-lib/lib/capabilities/completion-engine/loop.js +2 -1
  15. package/dist-lib/lib/capabilities/completion-engine/operations.js +1 -0
  16. package/dist-lib/lib/capabilities/completion-engine/ports.js +1 -1
  17. package/dist-lib/lib/capabilities/completion-engine/round.js +16 -7
  18. package/dist-lib/lib/capabilities/completion-engine/session.d.ts +3 -3
  19. package/dist-lib/lib/capabilities/prompt-prefix.d.ts +2 -0
  20. package/dist-lib/lib/capabilities/prompt-prefix.js +8 -0
  21. package/dist-lib/lib/capabilities/sdk-tool.d.ts +1 -1
  22. package/dist-lib/lib/capabilities/sdk-tool.js +17 -2
  23. package/dist-lib/lib/capabilities/usage-breakdown.d.ts +1 -0
  24. package/dist-lib/lib/capabilities/usage-breakdown.js +4 -1
  25. package/dist-lib/lib/contract/completion.d.ts +3 -0
  26. package/dist-lib/lib/contract/run.d.ts +2 -0
  27. package/dist-lib/lib/helpers/goal-check.d.ts +26 -0
  28. package/dist-lib/lib/helpers/goal-check.js +248 -22
  29. package/dist-lib/lib/helpers/spawn-path.d.ts +1 -0
  30. package/dist-lib/lib/helpers/spawn-path.js +2 -1
  31. package/dist-lib/lib/machine/completion/actions/completion.d.ts +3 -2
  32. package/dist-lib/lib/machine/completion/actions/completion.js +65 -15
  33. package/dist-lib/lib/machine/completion/actions/tools.js +47 -6
  34. package/dist-lib/lib/machine/completion/context.js +5 -1
  35. package/dist-lib/lib/machine/completion/implementations.d.ts +1 -0
  36. package/dist-lib/lib/machine/completion/implementations.js +7 -0
  37. package/dist-lib/lib/machine/completion/machine.d.ts +4 -1
  38. package/dist-lib/lib/machine/completion/machine.js +10 -1
  39. package/dist-lib/lib/machine/completion/rules.d.ts +3 -1
  40. package/dist-lib/lib/machine/completion/rules.js +25 -4
  41. package/dist-lib/lib/machine/completion/types.d.ts +16 -0
  42. package/dist-lib/lib/machine/index.d.ts +6 -1
  43. package/dist-lib/lib/machine/index.js +2 -0
  44. package/dist-lib/lib/models/model-pool.js +1 -2
  45. package/dist-lib/lib/office/engine/pptx/presentation.js +10 -5
  46. package/dist-lib/lib/sidecar/index.js +1 -1
  47. package/dist-lib/lib/skills-host/index.d.ts +1 -1
  48. package/dist-lib/lib/skills-host/index.js +3 -2
  49. package/dist-lib/lib/tools/exec/runner.d.ts +4 -0
  50. package/dist-lib/lib/tools/exec/runner.js +20 -3
  51. package/dist-lib/lib/tools/office.js +1 -0
  52. package/dist-lib/lib/tools/skills/overlay-watch.d.ts +2 -2
  53. package/dist-lib/lib/tools/skills/overlay-watch.js +4 -3
  54. package/dist-lib/lib/wire.js +9 -3
  55. package/dist-lib/plugins/image/index.js +5 -5
  56. package/dist-lib/plugins/knowledge/index.d.ts +3 -0
  57. package/dist-lib/plugins/knowledge/index.js +4 -0
  58. package/dist-lib/plugins/knowledge/manifest.d.ts +28 -4
  59. package/dist-lib/plugins/knowledge/manifest.js +49 -4
  60. package/dist-lib/plugins/knowledge/store.d.ts +10 -1
  61. package/dist-lib/plugins/knowledge/store.js +127 -57
  62. package/dist-lib/plugins/music/index.js +4 -4
  63. package/dist-lib/plugins/obsidian/index.js +14 -4
  64. package/dist-lib/plugins/python/index.d.ts +3 -1
  65. package/dist-lib/plugins/python/index.js +4 -1
  66. package/dist-lib/plugins/python/python-adapter.d.ts +2 -1
  67. package/dist-lib/plugins/python/python-adapter.js +8 -1
  68. package/dist-lib/plugins/sandbox-linux/index.js +2 -2
  69. package/dist-lib/plugins/sandbox-macos/index.js +2 -2
  70. package/dist-lib/plugins/sandbox-vm/index.d.ts +2 -1
  71. package/dist-lib/plugins/sandbox-vm/index.js +2 -2
  72. package/dist-lib/plugins/sandbox-vm/vm-shell.d.ts +3 -1
  73. package/dist-lib/plugins/sandbox-vm/vm-shell.js +45 -16
  74. package/dist-lib/plugins/sandbox-windows/index.js +2 -2
  75. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  76. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  77. package/package.json +27 -22
  78. package/scripts/addon-externals.cjs +4 -1
  79. package/patches/localwatch@1.4.3.patch +0 -13
package/CHANGELOG.md CHANGED
@@ -461,6 +461,55 @@ breaking change is listed under Changed and Removed.
461
461
 
462
462
  ### Changed
463
463
 
464
+ - Importing `@qvac/harness/plugins/image` or `@qvac/harness/plugins/music` no
465
+ longer needs their peers; constructing `Image` or `Music` without them throws
466
+ the error naming the plugin and the missing packages. A sidecar host passing no
467
+ image or music model installs neither's peers.
468
+
469
+ - **Breaking:** a command that times out resolves instead of throwing.
470
+ `runCommand` (`lib/tools/exec/runner.ts`) and the `exec` tool result come
471
+ back as `{ stdout, stderr, exitCode: 124 }`: `stdout` and `stderr` hold what
472
+ the command printed before the kill, and a note goes at the end of `stderr`,
473
+ added after the head/tail cut so the cut never drops it. There is no `error`
474
+ field and no `COMMAND_TIMED_OUT`. This holds on the host shell and the Linux,
475
+ macOS and Windows sandboxes. An abort still rejects with `AbortedError`. The
476
+ Pyodide `python` language still throws `COMMAND_TIMED_OUT` and `quickjs` still
477
+ throws a plain error. (#742)
478
+
479
+ ```js
480
+ import { HarnessError } from '@qvac/harness/errors'
481
+ import { runCommand } from '@qvac/harness/lib/tools/exec/runner.ts'
482
+
483
+ // before
484
+ try {
485
+ await runCommand('npm test', { spawn, timeoutMs: 60_000 })
486
+ } catch (err) {
487
+ if (HarnessError.is(err, 'COMMAND_TIMED_OUT')) retry()
488
+ }
489
+ // after
490
+ const result = await runCommand('npm test', { spawn, timeoutMs: 60_000 })
491
+ if (result.exitCode === 124) retry(result.stdout)
492
+ ```
493
+
494
+ - Exec sets `PYTHONUNBUFFERED=1` (`EXEC_ENV_DEFAULTS` in
495
+ `lib/helpers/spawn-path.ts`), so a python child's output reaches the pipe
496
+ before a timeout's kill instead of dying in its block buffer. `execEnv`
497
+ always sets it, as it is not on the env allowlist. The Linux, macOS and
498
+ Windows sandboxes spread it first, so a policy `env` allowlist that leaves
499
+ it out still passes it, and an explicit value wins. (#742)
500
+
501
+ - The ask for checks of the model's own stops after two goal turns it ignored
502
+ on every goal, not only one whose host checks test behaviour. A goal with no
503
+ host checks is then met on its plan. A goal whose host checks only test that
504
+ a file exists stays open until a passing check runs or reads what they test,
505
+ and each goal turn asks for one; a passing test runner, test script or
506
+ assertion that runs it is held as a check even after the model named others.
507
+ A run no longer repeats the same ask until its time budget. (#721)
508
+
509
+ - A spawned harness that cannot open now fails its sidecar's start with the
510
+ harness's own error, instead of serving a harness whose every call fails. A
511
+ supervising host sees the boot fail and why. (core v1 follow-up H1)
512
+
464
513
  - A goal with host checks that test behaviour stops asking the model for checks
465
514
  of its own after two goal turns it ignored. From then on the plan and the host
466
515
  checks meet it, and a check the model names later still gates it. A goal with
@@ -468,6 +517,47 @@ breaking change is listed under Changed and Removed.
468
517
  file exists (`test -s`, `[ -f ... ]`), the ask stays until the model names a
469
518
  check or a passing test runner, test script or inline assertion proves the
470
519
  result; that run is held as a check of its own. (#686)
520
+ - Breaking for hosts that send only `test -s` checks: a goal whose host checks
521
+ all test only that a path exists is met only once its checks pass and one of
522
+ them names a path the host checks test (not with `cat`, `ls` or another
523
+ command that only shows or moves a file, nor a `test` with no comparison),
524
+ runs a script whose written text names one (a heredoc, a `>` line,
525
+ `write_file` or `edit_file`), or runs a test runner on no given script
526
+ (`npm test`, `pytest`). While every check passes and none does this, each
527
+ goal turn asks for such a check, and until one does, the checks the model
528
+ names are added, so a run that used to end `met` now goes on until one passes
529
+ or a budget runs out. Set `goal.checksProve: true` when the
530
+ checks prove the task. (#698) Once that holds, one goal turn asks the model
531
+ to list the task's requirements and to name a check for each one the checks
532
+ miss, and adds those checks. (#694) A check wrapped in `timeout`, `env`,
533
+ `nice` or `stdbuf` is read as the command it runs; `nohup` is not, as
534
+ `nohup X &` exits at once. (#700, #703) On every goal, a write to a script resets
535
+ the pass of each check that runs it, so a pass from before the rewrite never
536
+ counts. (#701)
537
+ - Breaking for hosts that pass a `goal`: on a run with a tool that takes a
538
+ `command`, plan and checks no longer meet a goal on their own. Once the model
539
+ writes a source file, known by its extension for the languages a run can be
540
+ read for (Python, JavaScript and TypeScript, shell, Ruby, Perl, PHP, Lua, R,
541
+ Julia, Go, Rust, C and C++, Java; not `.txt`, `.json`, `.csv` or `.md`), the
542
+ goal stays open until a later command that runs that code exits 0, and once
543
+ the checks pass each goal turn asks for that run. A run is the file run as a
544
+ program or by its interpreter (`go run`, `Rscript`, `julia`, `tsx`,
545
+ `ts-node`, `java X.java`, and through `npx` or `bunx`), a test suite or test
546
+ script, `go run .`, `cargo run` or a build then a run in one command, or a
547
+ passing check that runs a script or a test suite. A reader such as `cat` or
548
+ `grep`, also by its `/bin` or `/usr/bin` path after a build, a run after
549
+ `make clean`, `make -n` or a cmake clean target, a compile, lint or syntax
550
+ check, and a run piped or followed by `|| true` or `;` do not count. Every
551
+ goal, whatever its host checks and with `checksProve` set, then takes a
552
+ review turn that asks for each requirement with the command that proves it.
553
+ The `goal` event carries `proof`, the command that ran the edited code,
554
+ recorded as `goalProof` in the bench trial row. (#732, #735, #745) The review
555
+ reply answers it only when a line above its `Checks:` names, in backticks, a
556
+ passed check or the run that proved the code; a reply with no calls that
557
+ names none is asked again, at most twice in all. A goal met with more than
558
+ half of each budget left takes one turn on the cases the task names; the met
559
+ `goal` event then carries `cases: true`, recorded as `goalCases`, and
560
+ `RunBudget.totalMs` keeps the whole time budget. (#740)
471
561
  - A host reaches the drive protocol it serves, the skill catalog and the
472
562
  user-plugin import map through named entries: `@qvac/harness/drive`
473
563
  (`DriveRequest`, `DriveResponse`, `DriveEntry`, `GrantedDrive`, `DriveOpFn`,
package/README.md CHANGED
@@ -194,13 +194,43 @@ const delegate = Agent.delegateTool(harness, base, { targets })
194
194
  `plan: true` gives an agent `update_plan`, a checklist it sees after every round. A `goal` keeps the
195
195
  run going until every step is done or a budget runs out. A goal's `checks` are commands the result
196
196
  is judged by, and until they pass each goal turn names the check and the output of its failed run.
197
- On a run with a tool that takes a `command`, the model must also name its own checks under a
197
+ On a run with a tool that takes a `command`, the model is also asked to name its own checks under a
198
198
  `Checks:` line, and the goal is met only once every check, the host's and the model's, ran in a
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
201
- checks prove the task: the goal is met on them alone and the model is not asked for its own. It has
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
203
- checks need a tool that takes a `command`, or the goal runs to its budget.
199
+ call's `command` and exited 0. With no tool that takes a `command` and no host checks, the goal ends
200
+ when the plan is done; host checks need a tool that takes a `command`, or the goal runs to its
201
+ budget.
202
+
203
+ The ask stops after two goal turns the model ignores. From then on the plan and any host checks,
204
+ such as `npm test`, meet the goal once the gates below hold. When every host check only tests that a
205
+ path exists (`test -s out.txt`, `[ -f out.txt ]`), a passing test runner, test script or assertion
206
+ also counts as a check the model named. Such a goal is met only once its checks pass and one of them
207
+ names a path the host checks test, runs a script the model wrote that names one, or runs a test
208
+ runner on no given script, such as `npm test` or `pytest`. `cat`, `ls` and other commands that only
209
+ show or move a file do not count, nor does a `test` with no comparison. While every check passes and
210
+ none does this, each goal turn asks for such a check, and until one does, the checks the model names
211
+ are added. A check wrapped in `timeout`, `env`, `nice` or `stdbuf` counts as the command it runs.
212
+
213
+ On a run with a tool that takes a `command`, three more gates hold on every goal. Once the model
214
+ writes a source file, known by its extension (`.py`, `.js`, `.ts`, `.sh`, `.go`, `.rs`, `.c`,
215
+ `.java` and the like, not `.txt`, `.json`, `.csv` or `.md`), the goal is met only after a later
216
+ command runs that code and exits 0; once the checks pass, each goal turn asks for that run. A run
217
+ counts when it runs the file as a program or through its interpreter, runs a test suite (`pytest`,
218
+ `npm test`, `cargo test`, `go test`) or a test script, builds and runs the project (`go run .`,
219
+ `cargo run`, or a build then a run in one command), or is a passing check that runs a script or a
220
+ test suite. `cat`, `grep`, `diff` and other commands that only read a file do not count, nor does a
221
+ compile, lint or syntax check, nor a run piped or followed by `|| true` or `;`. Another write to a
222
+ source file needs a new run. Once the checks pass and the code ran, one goal turn asks the model to
223
+ list each requirement of the task with the command that proves it and the output it gave, then,
224
+ under a `Checks:` line, a command for each requirement nothing proved. The reply answers it only
225
+ when a line above its `Checks:` names, in backticks, a passed check or the run that proved the code;
226
+ otherwise the turn is asked again, at most twice in all. The commands it names under `Checks:` are
227
+ added. A goal met with more than half of each budget left (time, rounds, and the goal's tokens when
228
+ it caps them) then takes one turn on the cases the task names. `checksProve: true` says the host
229
+ checks prove the task: the goal skips the ask and the gate on the paths, and still takes the run
230
+ gate, the review turn and the cases turn. It has no effect without checks. On every goal,
231
+ `checksProve` included, a write to a script resets the pass of each check that runs it, so the check
232
+ must pass again.
233
+
204
234
  `planMode` refuses writes until the user approves the plan.
205
235
 
206
236
  ```ts
@@ -31,6 +31,7 @@ import type { ResolvedSkillCatalogEntry } from './lib/tools/skills/catalog.ts';
31
31
  import type { SkillSettingEntry } from './lib/tools/skills/skill-settings.ts';
32
32
  export type * from './lib/contract/index.ts';
33
33
  export { CompletionEngine, type CompletionArgs, type CompletionEngineOptions, type CompletionRun, type ModelRoundEvent, type ModelRoundIo, type ModelRoundPort, type ModelRoundRequest, type ModelRoundResult, ToolSets } from './lib/capabilities/completion-engine/index.ts';
34
+ export { renderedTools } from './lib/capabilities/sdk-tool.ts';
34
35
  export declare const CONTEXT_OVERFLOW_MESSAGE: string;
35
36
  export { imageSettingsFrom } from './lib/helpers/image-settings.ts';
36
37
  export { skillInContext, unreadySkillState, type CompletionSkillEntry } from './lib/capabilities/skill-entry.ts';
package/dist-lib/index.js CHANGED
@@ -40,6 +40,7 @@ import { runCommand } from './lib/tools/exec/runner.js';
40
40
  import { createLocalRoots } from './lib/tools/fs/local.js';
41
41
  import { createRemoteRoots } from './lib/tools/fs/remote.js';
42
42
  export { CompletionEngine, ToolSets } from './lib/capabilities/completion-engine/index.js';
43
+ export { renderedTools } from './lib/capabilities/sdk-tool.js';
43
44
  export const CONTEXT_OVERFLOW_MESSAGE = HarnessError.CONTEXT_OVERFLOW_MESSAGE;
44
45
  export { imageSettingsFrom } from './lib/helpers/image-settings.js';
45
46
  export { skillInContext, unreadySkillState } from './lib/capabilities/skill-entry.js';
@@ -156,7 +157,7 @@ export class Harness extends ReadyResource {
156
157
  },
157
158
  statusChanged: () => this._residency.invalidateStatus(),
158
159
  teardown: async () => {
159
- this._skills.close();
160
+ await this._skills.close();
160
161
  await this._teardownPlugins();
161
162
  }
162
163
  });
@@ -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 { provesResult, runsCheck } from '../../../helpers/goal-check.js';
14
+ import { namesPath, provesResult, runsCheck, writtenTexts } 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;
@@ -56,6 +56,8 @@ export const executing = async function executing(input) {
56
56
  durationMs: settled.durationMs,
57
57
  checked: settled.checked,
58
58
  proved: settled.proved,
59
+ wrote: settled.wrote,
60
+ ran: settled.ran,
59
61
  plan: planned ? Agent.planSteps(callArgs) : undefined,
60
62
  leftPlanMode: planned && context.planMode && call.leavesPlan ? true : undefined
61
63
  };
@@ -209,6 +211,12 @@ export function settleCall({ input: { session }, context }, { ran, direct, emit
209
211
  proved: executed.executed && succeeded && context.goal
210
212
  ? proofRun(callArgs.command, executed.output)
211
213
  : undefined,
214
+ wrote: executed.executed && outcome.kind === 'success'
215
+ ? writtenScripts(context, callArgs)
216
+ : undefined,
217
+ ran: executed.executed && succeeded && context.goal && typeof callArgs.command === 'string'
218
+ ? callArgs.command
219
+ : undefined,
212
220
  entry: toolResultHistoryEntry({
213
221
  name: call.name,
214
222
  id: resultTurnId,
@@ -226,6 +234,17 @@ function checksRun({ goal }, { command, passed, output }) {
226
234
  }
227
235
  return ran.map(({ name }) => ({ name, passed, output: outputTail(output) }));
228
236
  }
237
+ function writtenScripts({ goal }, args) {
238
+ if (!goal) {
239
+ return undefined;
240
+ }
241
+ const { deliverable } = goal;
242
+ const fragment = typeof args.content !== 'string' && typeof args.new === 'string';
243
+ const wrote = writtenTexts(args).map(([path, text]) => deliverable
244
+ ? { path, proving: namesPath(text, deliverable) || (fragment ? undefined : false) }
245
+ : { path });
246
+ return wrote.length ? wrote : undefined;
247
+ }
229
248
  function proofRun(command, output) {
230
249
  const name = typeof command === 'string' ? provesResult(command) : undefined;
231
250
  return name ? { name, passed: true, output: outputTail(output) } : undefined;
@@ -82,7 +82,7 @@ export async function loadSkill({ emit, input: deps, context }, plan) {
82
82
  else {
83
83
  session.loadedFilesThisTurn.add(fileKey);
84
84
  }
85
- session.reselectTools?.(new Set([...loadedSkills(context, session), skillName]));
85
+ session.reselectTools?.(new Set([...loadedSkills(context, session), skillName]), context.history);
86
86
  const skill = session.inContextSkills.find(({ name }) => name === skillName);
87
87
  const loads = skillLoadTurns(skill, {
88
88
  sent: session.sdkTools,
@@ -116,8 +116,6 @@ async function prepare({ input, context, reconstruct, source, emit }) {
116
116
  const { skillsSelected } = activation;
117
117
  const sent = reconstruct ? context.history[0] : undefined;
118
118
  let systemContent = sent && 'role' in sent && sent.role === 'system' ? sent.content : system.text;
119
- const promptPrefix = promptPrefixHash({ system: systemContent, tools: renderedTools(sdkTools) });
120
- const promptParts = promptUsageParts({ system, toolSchemas: renderedTools(sdkTools) });
121
119
  const logSelection = (prefix) => {
122
120
  logToolPrompt({
123
121
  promptPrefix: prefix,
@@ -136,25 +134,26 @@ async function prepare({ input, context, reconstruct, source, emit }) {
136
134
  toolOps: session.grantedOps
137
135
  });
138
136
  };
139
- session.reselectTools = (loaded) => {
137
+ session.reselectTools = (loaded, history) => {
140
138
  const reselected = callable(loaded);
141
139
  const names = reselected.map((tool) => tool.name).join();
142
140
  const changed = names !== session.enabled.map((tool) => tool.name).join();
143
141
  if (changed) {
144
142
  session.enabled = reselected;
145
143
  }
146
- const prefix = promptPrefixHash({ system: systemContent, tools: renderedTools(sdkTools) });
144
+ const tools = renderedTools(sdkTools, history);
145
+ const prefix = promptPrefixHash({ system: systemContent, tools });
147
146
  if (changed) {
148
147
  logSelection(prefix);
149
148
  }
150
149
  return prefix;
151
150
  };
152
- session.preloadSystem = (skill) => {
151
+ session.preloadSystem = (skill, history) => {
153
152
  const systemParts = resolved.systemFor(new Set([...loadedSkills, skill]));
154
153
  systemContent = systemParts.text;
155
154
  session.promptParts = promptUsageParts({
156
155
  system: systemParts,
157
- toolSchemas: renderedTools(sdkTools)
156
+ toolSchemas: renderedTools(sdkTools, history)
158
157
  });
159
158
  return systemContent;
160
159
  };
@@ -168,6 +167,11 @@ async function prepare({ input, context, reconstruct, source, emit }) {
168
167
  const history = firstTurn
169
168
  ? withSystem([...withTurnContext(messages, { time, ...added }), ...checks])
170
169
  : [...context.history];
170
+ const promptPrefix = promptPrefixHash({
171
+ system: systemContent,
172
+ tools: renderedTools(sdkTools, history)
173
+ });
174
+ const promptParts = promptUsageParts({ system, toolSchemas: renderedTools(sdkTools, history) });
171
175
  if (firstTurn && !reconstruct && messages.some((turn) => turn.role === 'user')) {
172
176
  const sources = hits.length ? knowledgeSources(hits) : undefined;
173
177
  emit({ type: 'context', context: { time, ...added }, sources, round: context.round });
@@ -60,8 +60,8 @@ export const skillStep = {
60
60
  const content = String(result.content);
61
61
  session.loadedThisTurn.add(name);
62
62
  session.skillIcon = skillEmojiFrom(session.inContextSkills, name) ?? session.skillIcon;
63
- const typed = withSystem(annotateCompletionHistoryLastUserTime(context.history, new Date(session.startedAt)), session.preloadSystem?.(name));
64
- session.reselectTools?.(new Set([...loadedSkills(context, session), name]));
63
+ const typed = withSystem(annotateCompletionHistoryLastUserTime(context.history, new Date(session.startedAt)), session.preloadSystem?.(name, context.history));
64
+ session.reselectTools?.(new Set([...loadedSkills(context, session), name]), context.history);
65
65
  const called = directToolHistory(typed, {
66
66
  tool: step.tool,
67
67
  id: step.id,
@@ -12,7 +12,7 @@ interface RunRoundOptions {
12
12
  agent?: AgentConfig | undefined;
13
13
  kind: RoundKind;
14
14
  args: Omit<RoundArgs, 'live' | 'knownTools'>;
15
- session: Pick<Session, 'liveRound' | 'enabled' | 'runId'>;
15
+ session: Pick<Session, 'liveRound' | 'enabled' | 'runId' | 'promptParts'>;
16
16
  emit: (event: CompletionEvent) => void;
17
17
  }
18
18
  export interface AssembleAnswerOptions {
@@ -3,6 +3,8 @@ import { inferenceCall, recordWholeRound, runRecoveredRound } from '../round.js'
3
3
  import { ModelRound } from '../model-round.js';
4
4
  import { ToolSets } from '../tool-sets.js';
5
5
  import { AbortedError } from '../../../helpers/race-abort.js';
6
+ import { renderedTools } from '../../sdk-tool.js';
7
+ import { toolSchemaChars } from '../../usage-breakdown.js';
6
8
  export async function forwardStream({ stream, emit }) {
7
9
  try {
8
10
  while (true) {
@@ -37,6 +39,12 @@ export async function runRound({ sdk, modelRound, agent, kind, args, session, em
37
39
  emit
38
40
  });
39
41
  session.liveRound = null;
42
+ if (session.promptParts) {
43
+ session.promptParts = {
44
+ ...session.promptParts,
45
+ toolSchemas: toolSchemaChars(renderedTools(args.tools, round.history))
46
+ };
47
+ }
40
48
  return round;
41
49
  }
42
50
  catch (error) {
@@ -7,6 +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 { requestPromptPrefix } from '../../prompt-prefix.js';
10
11
  import { FILE_DELIVERED_NUDGE, GOAL_CONTINUATION_NUDGE, TOOL_CONTINUATION_NUDGE, WRAP_UP_NUDGE } from '../../tool-turns.js';
11
12
  import { HarnessLog } from '../../../log.js';
12
13
  import { toolDialectFor } from '../../../models/model-catalog.js';
@@ -94,7 +95,10 @@ async function generateStreamingRound({ sdk, args, session, operations, context,
94
95
  session.runBudget.responseRoomChars = responseRoomChars(recovered.ctxSize ?? args.ctxSize, recovered.final.stats?.cacheTokens);
95
96
  const durationMs = Date.now() - prepared.startedAt;
96
97
  logRoundStats({ round: context.round, durationMs, recovered });
97
- return { recovered, promptPrefix: prepared.promptPrefix, thinkingText, durationMs };
98
+ const promptPrefix = recovered.history
99
+ ? requestPromptPrefix(recovered.history, session.sdkTools)
100
+ : prepared.promptPrefix;
101
+ return { recovered, promptPrefix, thinkingText, durationMs };
98
102
  }
99
103
  function logRoundStats({ round, durationMs, recovered }) {
100
104
  HarnessLog.debug('round stats', Object.assign({ round, wallMs: durationMs }, recovered.final.stats));
@@ -106,7 +110,7 @@ function prepareStreamingRound({ args, session, operations, context }) {
106
110
  : (context.cacheKey ?? undefined);
107
111
  const model = args.model;
108
112
  const toolDialect = model ? toolDialectFor(model) : undefined;
109
- const promptPrefix = session.reselectTools?.(loadedSkills(context, session)) ?? context.promptPrefix;
113
+ const promptPrefix = session.reselectTools?.(loadedSkills(context, session), context.history) ?? context.promptPrefix;
110
114
  HarnessLog.debug('round start', {
111
115
  round: context.round,
112
116
  turns: context.history.length,
@@ -5,6 +5,7 @@ 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
7
  import { materializeCompletionHistory } from '../../tool-turns.js';
8
+ import { requestPromptPrefix } from '../../prompt-prefix.js';
8
9
  import { toolDialectFor } from '../../../models/model-catalog.js';
9
10
  import { loadedSkills } from '../session.js';
10
11
  import { CompletionMachine } from '../../../machine/index.js';
@@ -14,7 +15,7 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
14
15
  const cacheKey = !args.replaysContext && carriesRunOnlyText(context.history)
15
16
  ? undefined
16
17
  : (context.cacheKey ?? undefined);
17
- const promptPrefix = session.reselectTools?.(loadedSkills(context, session)) ?? context.promptPrefix;
18
+ const promptPrefix = session.reselectTools?.(loadedSkills(context, session), context.history) ?? context.promptPrefix;
18
19
  const startedAt = Date.now();
19
20
  const recovered = await runRound({
20
21
  sdk,
@@ -32,7 +33,7 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
32
33
  goalNudge: context.policy.goalNudge,
33
34
  wrapUpNudge: context.policy.wrapUpNudge,
34
35
  tools: session.sdkTools,
35
- generationParams: wrapUpParams(session.generationParams),
36
+ generationParams: wrapUpParams(session.generationParams, context.outcome === 'time-capped'),
36
37
  toolDialect: args.model ? toolDialectFor(args.model) : undefined,
37
38
  cacheKey,
38
39
  signal,
@@ -60,7 +61,9 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
60
61
  return {
61
62
  contentText,
62
63
  thinkingText: '',
63
- promptPrefix,
64
+ promptPrefix: recovered.history
65
+ ? requestPromptPrefix(recovered.history, session.sdkTools)
66
+ : promptPrefix,
64
67
  toolCalls: [],
65
68
  stats: recovered.final.stats,
66
69
  stopReason: recovered.final.stopReason,
@@ -75,7 +78,10 @@ export const wrapUp = async function wrapUp({ emit, input: { sdk, args, session,
75
78
  response: replay || contentText || fallbackResponse
76
79
  };
77
80
  };
78
- function wrapUpParams(params) {
81
+ function wrapUpParams(params, timeUp) {
82
+ if (timeUp) {
83
+ return { ...params, reasoning_budget: 0, predict: WRAP_UP_PREDICT, tool_choice: 'none' };
84
+ }
79
85
  if (!params) {
80
86
  return { tool_choice: 'none' };
81
87
  }
@@ -79,6 +79,20 @@ async function* submittedInput(input, pipeline, { runId, agentId }) {
79
79
  yield submitted.context === undefined ? item : { ...item, notes: submitted.context };
80
80
  }
81
81
  }
82
+ function* cutGoal(context, runId) {
83
+ const { goal } = context;
84
+ if (goal?.status !== 'open') {
85
+ return;
86
+ }
87
+ yield {
88
+ type: 'goal',
89
+ runId,
90
+ status: CompletionMachine.goalStatus(context),
91
+ turn: goal.turns,
92
+ round: context.round,
93
+ proof: goal.proof
94
+ };
95
+ }
82
96
  function hookManifest(hooks) {
83
97
  const ordinals = new Map();
84
98
  return hooks.map((hook) => {
@@ -616,6 +630,7 @@ export async function* driveCompletion(args, runtime, options) {
616
630
  'tag' in result.error &&
617
631
  result.error.tag === 'aborted') {
618
632
  reachedPause = true;
633
+ yield* cutGoal(snapshot.context, runId);
619
634
  yield* runMetrics(cancelledRound(completionState.session?.liveRound));
620
635
  throw new AbortedError();
621
636
  }
@@ -25,7 +25,8 @@ const RUN_WALL_CLOCK_BUDGET_MS = 30 * 60_000;
25
25
  export function createRunBudget(startedAt, ms) {
26
26
  const override = Number(process.env.QVAC_RUN_BUDGET_MS);
27
27
  const fallback = Number.isFinite(override) && override > 0 ? override : RUN_WALL_CLOCK_BUDGET_MS;
28
- return { deadlineMs: startedAt + (ms ?? fallback), outputBytesUsed: 0 };
28
+ const totalMs = ms ?? fallback;
29
+ return { deadlineMs: startedAt + totalMs, totalMs, outputBytesUsed: 0 };
29
30
  }
30
31
  export function runToolContext(args, runBudget) {
31
32
  const { agent, attach, fetchAttachment, progress, askUser, signal } = args;
@@ -145,6 +145,7 @@ export function bindOperations(deps, context, stage) {
145
145
  : current.backends,
146
146
  runBudget: {
147
147
  deadlineMs: current.runBudget.deadlineMs,
148
+ totalMs: current.runBudget.totalMs,
148
149
  outputBytesUsed: Math.max(current.runBudget.outputBytesUsed, recorded.runBudget.outputBytesUsed)
149
150
  },
150
151
  outcome: {
@@ -226,7 +226,7 @@ async function rebuildSession(deps, cx) {
226
226
  restoreFacts(invocation.input, durable);
227
227
  }
228
228
  const session = deps.session;
229
- session.reselectTools?.(loadedSkills(context, session));
229
+ session.reselectTools?.(loadedSkills(context, session), context.history);
230
230
  const missing = context.availableTools.filter((name) => !session.enabled.some((tool) => tool.name === name));
231
231
  const changed = durable?.tools
232
232
  .filter((saved) => {
@@ -17,8 +17,10 @@ import { stableStringify } from '../../helpers/stable-stringify.js';
17
17
  import { detachJson } from '../../helpers/detach-json.js';
18
18
  import { isSkillMentionNudge, materializeCompletionHistory } from '../tool-turns.js';
19
19
  import { completionParams } from '../../helpers/completion-params.js';
20
+ import { requestPromptPrefix } from '../prompt-prefix.js';
21
+ import { renderedTools } from '../sdk-tool.js';
20
22
  import { isFailureResultReference } from '../../helpers/failure-result.js';
21
- import { GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../helpers/goal-check.js';
23
+ import { GOAL_CHECKS_ASK, GOAL_PROOF_ASK, GOAL_REVIEW_ASK } from '../../helpers/goal-check.js';
22
24
  import { Fold } from '../../fold/index.js';
23
25
  import { CompletionMachine } from '../../machine/index.js';
24
26
  import { modelTurns } from './turns.js';
@@ -224,11 +226,18 @@ export function foldTokens(stats, cacheable) {
224
226
  function slotStats(stats, previous) {
225
227
  if (!stats)
226
228
  return undefined;
227
- const { cacheTokens: _summed, ...rest } = stats;
228
- if (previous === undefined || stats.promptTokens === undefined) {
229
+ const { cacheTokens: _summed, promptTokensPerSecond: _scheduler, ...own } = stats;
230
+ const { promptTokens, timeToFirstToken } = stats;
231
+ const rest = promptTokens !== undefined &&
232
+ promptTokens > 0 &&
233
+ timeToFirstToken !== undefined &&
234
+ timeToFirstToken > 0
235
+ ? { ...own, promptTokensPerSecond: (promptTokens / timeToFirstToken) * 1000 }
236
+ : own;
237
+ if (previous === undefined || promptTokens === undefined) {
229
238
  return rest;
230
239
  }
231
- return { ...rest, cacheTokens: previous + stats.promptTokens + (stats.generatedTokens ?? 0) };
240
+ return { ...rest, cacheTokens: previous + promptTokens + (stats.generatedTokens ?? 0) };
232
241
  }
233
242
  function boundaryStats(final, predict) {
234
243
  const stats = copy(final.stats);
@@ -390,7 +399,7 @@ function harnessTurns(args, history) {
390
399
  }
391
400
  function goalTurns(args) {
392
401
  const goal = args.goalNudge === undefined ? [] : [args.goalNudge];
393
- return [...goal, GOAL_CHECKS_ASK, GOAL_PROOF_ASK];
402
+ return [...goal, GOAL_CHECKS_ASK, GOAL_PROOF_ASK, GOAL_REVIEW_ASK];
394
403
  }
395
404
  async function foldRounds(send, history) {
396
405
  const { sdk, args, ctxSize } = send;
@@ -751,12 +760,12 @@ export function inferenceCall({ args, droppedTurns, modelId, params, cacheKey })
751
760
  droppedTurns,
752
761
  modelId,
753
762
  messages: params.history,
754
- tools: params.tools,
763
+ tools: renderedTools(params.tools, params.history),
755
764
  generationParams: params.generationParams,
756
765
  responseFormat: params.responseFormat,
757
766
  toolDialect: params.toolDialect,
758
767
  cacheKey,
759
- promptPrefix: args.promptPrefix
768
+ promptPrefix: requestPromptPrefix(params.history, params.tools)
760
769
  }
761
770
  };
762
771
  }
@@ -1,7 +1,7 @@
1
1
  import type { Tool as SdkTool } from '@qvac/inference';
2
2
  import type { HookPipeline } from '../../hooks/index.ts';
3
3
  import { type RunOutcomeTracker } from '../../helpers/run-outcome.ts';
4
- import type { AgentPolicy, AgentPorts, CompletionEvent, CliValidator, CompiledPolicy, CompletionSdk, DriveRoot, LlmGenerationParams, OutboundGuard, RunBackendUse, RunBudget, SkillActivation, ToolDefinition } from '../../contract/index.ts';
4
+ import type { AgentPolicy, AgentPorts, CompletionEvent, CliValidator, CompiledPolicy, CompletionHistoryEntry, CompletionSdk, DriveRoot, LlmGenerationParams, OutboundGuard, RunBackendUse, RunBudget, SkillActivation, ToolDefinition } from '../../contract/index.ts';
5
5
  import type { CompletionArgs, ToolContextFactory } from './loop.ts';
6
6
  import type { CompletionSkillEntry } from '../skill-entry.ts';
7
7
  import type { PromptUsageChars } from '../usage-breakdown.ts';
@@ -49,8 +49,8 @@ export interface Session extends InvokeTracker {
49
49
  startedAt: number;
50
50
  now: () => number;
51
51
  wallStart: number;
52
- reselectTools: ((loadedSkills: ReadonlySet<string>) => string) | null;
53
- preloadSystem: ((skill: string) => string) | null;
52
+ reselectTools: ((loadedSkills: ReadonlySet<string>, history: readonly CompletionHistoryEntry[]) => string) | null;
53
+ preloadSystem: ((skill: string, history: readonly CompletionHistoryEntry[]) => string) | null;
54
54
  liveRound: LiveRound | null;
55
55
  }
56
56
  export interface CompletionDeps {
@@ -1,6 +1,8 @@
1
1
  import type { Tool as SdkTool } from '@qvac/inference';
2
+ import type { CompletionHistoryEntry } from '../contract/index.ts';
2
3
  export interface PromptPrefix {
3
4
  system: string | null;
4
5
  tools: ReadonlyArray<SdkTool> | undefined;
5
6
  }
6
7
  export declare function promptPrefixHash({ system, tools }: PromptPrefix): string;
8
+ export declare function requestPromptPrefix(history: readonly CompletionHistoryEntry[], tools: SdkTool[] | undefined): string;
@@ -1,4 +1,5 @@
1
1
  import crypto from 'crypto';
2
+ import { renderedTools } from './sdk-tool.js';
2
3
  export function promptPrefixHash({ system, tools }) {
3
4
  const hash = crypto.createHash('sha256');
4
5
  hash.update(system ?? '');
@@ -8,3 +9,10 @@ export function promptPrefixHash({ system, tools }) {
8
9
  }
9
10
  return hash.digest('hex').slice(0, 12);
10
11
  }
12
+ export function requestPromptPrefix(history, tools) {
13
+ const system = history.find((entry) => 'role' in entry && entry.role === 'system');
14
+ return promptPrefixHash({
15
+ system: system && 'content' in system ? system.content : null,
16
+ tools: renderedTools(tools, history)
17
+ });
18
+ }
@@ -5,7 +5,7 @@ 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
7
  export declare function toSdkTools(tools: readonly ToolDefinition[]): SdkTool[] | undefined;
8
- export declare function renderedTools(tools: SdkTool[] | undefined): SdkTool[] | undefined;
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[];
11
11
  interface SkillLoad {
@@ -102,12 +102,27 @@ export function toSdkTools(tools) {
102
102
  const sent = tools.filter((tool) => !searching || tool.name !== TOOL_SEARCH_NAME);
103
103
  return sent.length ? sent.map((tool) => toSdkTool(tool)) : undefined;
104
104
  }
105
- export function renderedTools(tools) {
105
+ export function renderedTools(tools, history) {
106
106
  const deferred = tools?.filter((tool) => tool.deferLoading === true) ?? [];
107
107
  if (!tools || !deferred.length) {
108
108
  return tools;
109
109
  }
110
- return [...tools.filter((tool) => tool.deferLoading !== true), buildToolSearchTool(deferred)];
110
+ const whole = tools.filter((tool) => tool.deferLoading !== true);
111
+ const ruleName = (name) => name.replace(/[^A-Za-z0-9-]+/g, '-');
112
+ const taken = new Set([...whole.map(({ name }) => name), TOOL_SEARCH_NAME].map(ruleName));
113
+ const selectable = deferred.filter(({ name }) => {
114
+ const rule = ruleName(name);
115
+ if (['', 'auto', 'none', 'required'].includes(name) || taken.has(rule)) {
116
+ return false;
117
+ }
118
+ taken.add(rule);
119
+ return true;
120
+ });
121
+ const loaded = loadedTools(history);
122
+ const declared = selectable
123
+ .filter(({ name }) => loaded.has(name))
124
+ .map(({ deferLoading: _deferLoading, group: _group, ...wire }) => wire);
125
+ return [...whole, buildToolSearchTool(selectable), ...declared];
111
126
  }
112
127
  export function loadedTools(history) {
113
128
  return loadedToolNames(history.filter((entry) => !isFailureResultReference(entry)));
@@ -24,4 +24,5 @@ export interface PromptUsagePartsInput {
24
24
  toolSchemas?: ReadonlyArray<unknown> | undefined;
25
25
  }
26
26
  export declare function promptUsageParts({ system, toolSchemas }: PromptUsagePartsInput): PromptUsageChars;
27
+ export declare function toolSchemaChars(toolSchemas?: ReadonlyArray<unknown>): number;
27
28
  export declare function usageBreakdown(chars: PromptUsageChars, totalTokens?: number | null, modelName?: string | null): UsageBreakdown | null;