@qvac/harness 1.0.0-rc.4 → 1.0.0-rc.6

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 (73) hide show
  1. package/CHANGELOG.md +115 -18
  2. package/dist-lib/index.d.ts +4 -1
  3. package/dist-lib/index.js +42 -1
  4. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.js +13 -3
  5. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +8 -1
  6. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +62 -36
  7. package/dist-lib/lib/capabilities/completion-engine/actors/resolving.js +11 -4
  8. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +20 -11
  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 +7 -3
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +8 -17
  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 +12 -12
  14. package/dist-lib/lib/capabilities/completion-engine/driver.js +1 -2
  15. package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -1
  16. package/dist-lib/lib/capabilities/completion-engine/engine.js +14 -1
  17. package/dist-lib/lib/capabilities/completion-engine/index.d.ts +3 -1
  18. package/dist-lib/lib/capabilities/completion-engine/index.js +2 -0
  19. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  20. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +14 -1
  21. package/dist-lib/lib/capabilities/completion-engine/model-round.js +52 -0
  22. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -3
  23. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -5
  24. package/dist-lib/lib/capabilities/completion-engine/turns.js +29 -25
  25. package/dist-lib/lib/capabilities/sdk-tool.d.ts +9 -1
  26. package/dist-lib/lib/capabilities/sdk-tool.js +21 -2
  27. package/dist-lib/lib/capabilities/tool-plan.d.ts +4 -0
  28. package/dist-lib/lib/capabilities/tool-plan.js +15 -0
  29. package/dist-lib/lib/connect.js +16 -2
  30. package/dist-lib/lib/contract/completion.d.ts +8 -2
  31. package/dist-lib/lib/contract/drive.d.ts +4 -0
  32. package/dist-lib/lib/contract/drive.js +1 -0
  33. package/dist-lib/lib/contract/index.d.ts +2 -0
  34. package/dist-lib/lib/contract/managed-skills.d.ts +1 -0
  35. package/dist-lib/lib/contract/managed-skills.js +1 -0
  36. package/dist-lib/lib/contract/run.d.ts +8 -0
  37. package/dist-lib/lib/contract-types.d.ts +4 -1
  38. package/dist-lib/lib/errors.d.ts +4 -0
  39. package/dist-lib/lib/errors.js +6 -0
  40. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  41. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  42. package/dist-lib/lib/helpers/goal-check.d.ts +2 -0
  43. package/dist-lib/lib/helpers/goal-check.js +18 -0
  44. package/dist-lib/lib/machine/completion/actions/completion.js +33 -13
  45. package/dist-lib/lib/machine/completion/context.js +3 -1
  46. package/dist-lib/lib/machine/completion/implementations.js +16 -4
  47. package/dist-lib/lib/machine/completion/machine.d.ts +2 -0
  48. package/dist-lib/lib/machine/completion/rules.d.ts +1 -1
  49. package/dist-lib/lib/machine/completion/rules.js +7 -8
  50. package/dist-lib/lib/machine/completion/types.d.ts +8 -1
  51. package/dist-lib/lib/machine/index.d.ts +2 -0
  52. package/dist-lib/lib/models/model-pool.d.ts +4 -0
  53. package/dist-lib/lib/models/model-pool.js +4 -1
  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/serve.js +12 -5
  61. package/dist-lib/lib/tools/http-request.js +1 -0
  62. package/dist-lib/lib/wire.js +5 -0
  63. package/dist-lib/plugins/mcp/server.js +1 -1
  64. package/dist-lib/plugins/obsidian/readiness.js +2 -2
  65. package/dist-lib/plugins/obsidian/vault-read.js +17 -16
  66. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  67. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  68. package/dist-lib/schema/harness.js +5 -2
  69. package/dist-lib/spec/hrpc/messages.js +19 -5
  70. package/dist-lib/spec/hyperschema/index.js +19 -5
  71. package/dist-lib/spec/hyperschema/schema.json +14 -0
  72. package/dist-lib/spec/hyperschema/types.d.ts +3 -1
  73. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -28,11 +28,32 @@ breaking change is listed under Changed and Removed.
28
28
  A run started with it pauses for it on resume. A paused or cancelled round,
29
29
  local or remote, now ends at once even when the model sends nothing. See the
30
30
  [decision record](docs/decisions/2026-10-19-a-remote-host-serves-the-model-round.md).
31
- (#493)
31
+ A sidecar from `spawnHarness` or `connectHarness` refuses `modelRound` and
32
+ `roundCut` with `CAPABILITY_UNSUPPORTED` instead of running locally.
33
+ (#493, #542)
32
34
  - `ModelRoundIo.retake()` restarts a remote round when another host takes it:
33
35
  the run emits `round-reset` for the round and the returned emitter carries
34
36
  the new taker's chunks, while the earlier taker's late chunks are dropped.
35
37
  The port resolves with the new taker's result. (#497)
38
+ - `harness.serveModelRound(request, io)` serves a model round on the model
39
+ host, in process: it leases `request.modelId` and runs the same round a local
40
+ run does, with the context ladder and the forced-call fallback, and is
41
+ refused with `HARNESS_SUSPENDED` while suspended. Core sends it the
42
+ `ModelRoundRequest` whole. A remote round now answers an unclosed think from
43
+ the host's replay, and its request carries `unforced`. See the
44
+ [decision record](docs/decisions/2026-10-19-a-remote-host-serves-the-model-round.md).
45
+ (#541)
46
+ - A turn's context is data the host can replay. A run reports what it added to
47
+ each user turn (its time, the knowledge it retrieved, a `promptSubmit` hook's
48
+ context) once, as a `context` event. A host stores it and sends it back as
49
+ that message's `context`, and the harness renders the turn byte for byte as
50
+ it was sent. With `replaysContext: true` such a run keeps its `cacheKey`. A
51
+ steer's or follow-up's `input` event now carries the words as typed (#494).
52
+
53
+ ```js
54
+ { role: 'user', content: 'How cold is it?', context: event.context }
55
+ ```
56
+
36
57
  - The `HarnessLog` class is the log's API, through statics:
37
58
  `HarnessLog.warn('unload failed')`, `HarnessLog.setSink(sink)`,
38
59
  `HarnessLog.setLevel('warn')`. The root names `hlog`, `harnessLog`,
@@ -219,6 +240,9 @@ breaking change is listed under Changed and Removed.
219
240
  `goal: { objective, rounds?, ms?, tokens? }` keeps a run going until every
220
241
  step is done, emitting `goal` events whose `text` the host stores as a turn.
221
242
  See [Plans and goals](README.md#plans-and-goals). (#234, #240)
243
+ - `RunGoal.checksProve`. A host whose `checks` prove the goal sets it, and the
244
+ goal is met once the plan is done and those checks pass, without asking the
245
+ model for a check of its own. Without `checks` it has no effect. (#599)
222
246
  - Steering. `CompletionContext.input` sends `steer` and `follow-up` turns to a
223
247
  running run, single or chained; each delivery emits an `input` event. See
224
248
  [Steer a run while it works](README.md#steer-a-run-while-it-works). (#186,
@@ -338,9 +362,27 @@ breaking change is listed under Changed and Removed.
338
362
 
339
363
  - A Node lane: `bun run test:node` runs the brittle suite under Node, and CI
340
364
  runs it beside the Bare lane. (#535)
365
+ - The types a host needs to serve a granted drive and to manage skills are
366
+ exported from `@qvac/harness`: `GrantedDrive`, `DriveOpFn`, `DriveRequest`
367
+ and each request it unions, `DriveResponse`, `DriveEntry`, `DriveDir` and
368
+ `SearchHit`, and `ManagedSkill`, `SkillFileContent`, `CopyBaseResult` and
369
+ `DeleteOverlayResult`. The contract already takes or returns each of them,
370
+ but a host could only reach them through `./lib/tools/*`, which 1.0 no
371
+ longer exports. (#591)
372
+
373
+ ```ts
374
+ import type { DriveOpFn, GrantedDrive, ManagedSkill } from '@qvac/harness'
375
+ ```
341
376
 
342
377
  ### Changed
343
378
 
379
+ - Every skill-gated tool (`docx`, `pptx`, `xlsx`, `pdf`, `generate_image`, …),
380
+ `http_request` and every MCP server's tools are deferred behind
381
+ `tool_search`. The sent tool set is fixed per chat, so a skill load no longer
382
+ re-primes the prompt cache: it appends the loads of the tools it grants. A
383
+ direct call to a deferred tool loads it and runs in the same round instead of
384
+ being refused. An MCP server sets `defer: false` to send its schemas whole.
385
+ `skill-eval` gains `--defer`. (#566)
344
386
  - **Breaking** for a TypeScript host that reads it: `inference-sent` no longer
345
387
  carries `messages`. `@qvac/inference` 0.22 does not report the slice it
346
388
  pushed, so the field was always empty; a prompt inspector reads the payload
@@ -457,6 +499,11 @@ breaking change is listed under Changed and Removed.
457
499
  goal's checks in `checks` once it has some, the bench bridge's done frame
458
500
  carries them in `goal.checks`, and the Terminal-Bench trial row keeps them as
459
501
  `checks`. (#550)
502
+ - Breaking for hosts that send `checks`: passing host checks alone no longer
503
+ meet a checkable goal. The model must name a check of its own under a
504
+ `Checks:` line, and one that repeats a host check does not count. A host
505
+ whose checks do prove the task, such as qvac-core, sets
506
+ `goal.checksProve: true` (#599). (#595)
460
507
  - A round of unchanged calls counts once toward the stop for runs with no new
461
508
  result, not once per call. Three such rounds in a row end the run, so one
462
509
  sweep of re-checks with nothing new no longer ends a goal run as `stalled`. (#509)
@@ -834,22 +881,13 @@ breaking change is listed under Changed and Removed.
834
881
 
835
882
  ### Fixed
836
883
 
837
- - A `pptx`, `docx` or `xlsx` call that builds a new file without `output` is
838
- saved and attached instead of refused. The file is named after
839
- `create.title` (`Climate Change` → `climate_change.docx`), or
840
- `presentation.pptx`, `document.docx` or `workbook.xlsx` without one, the way
841
- the `pdf` tool names a new PDF. A 2B model often left `output` off, and the
842
- refusal sent it guessing attachment ids until the turn ended with no file.
843
- A call whose ops only read (`read`, `sheets`, `paragraphStyles`, …) returns
844
- their results and saves nothing, so it never attaches a blank file.
845
- (QVAC-26944)
846
- - A new Word document takes two more of a small model's slips instead of
847
- refusing the whole call: a block position past the end of what the call has
848
- built so far lands at the end, and `appendParagraphs` with an `at` inserts
849
- the paragraphs there. An attached document keeps the strict checks. In any
850
- `pptx`, `docx` or `xlsx` call, an `{ "op": "output", … }` entry is dropped
851
- instead of refused, and a file name in it names the file unless `output` is
852
- already set. (QVAC-26944)
884
+ - The wrap-up round a run ends on keeps the tool block in the prompt and
885
+ forbids a call with `tool_choice: "none"`, instead of dropping the block.
886
+ Under `@qvac/sdk` 0.22 the dropped block rewrote the chat's one cache file,
887
+ so that round and the next turn each re-read the whole chat (19.6 s to first
888
+ token on Qwen3.5-2B after a 12-turn chat). (#605)
889
+ - A `skill` call that names a skill by its display name, in another case, or by
890
+ the one tool it grants (`pptx`) loads that skill. (#528)
853
891
  - On Node, the Python plugin finds pyodide and the vendored wheels without
854
892
  `import.meta.asset`: it resolves both with `import.meta.resolve`. (#535)
855
893
  - A skill's tools are reselected on the turn the skill loads, so a run
@@ -901,6 +939,64 @@ breaking change is listed under Changed and Removed.
901
939
  - A `FAIL` sent while a run was finishing no longer runs the finishing step and
902
940
  its `runEnd` hook again. (#167)
903
941
 
942
+ ## [0.8.12] - 2026-10-21
943
+
944
+ ### Added
945
+
946
+ - A custom GGUF the catalog does not know is sized by the engine fitter from
947
+ its header and tensor list, so its preview gives a fit verdict instead of
948
+ "Fit unknown". Split models stay unknown. (#562)
949
+
950
+ ### Changed
951
+
952
+ - `http_request`, `mcp_call` and every skill-gated tool (`docx`, `pptx`,
953
+ `xlsx`, `pdf`, `generate_image`, `weather_lookup`, compiled skill operations,
954
+ …) are deferred behind `tool_search`: their schemas stay out of the prompt
955
+ until searched, called or loaded with their skill. The tool set is fixed per
956
+ chat, so a skill load no longer re-primes the prompt cache. `skill-eval`
957
+ gains `--defer`. (#566)
958
+ - `@qvac/sdk` and `@qvac/inference` move to `^0.22.0`. Loads are sized on the
959
+ fitter's `floorBytes`, so more models fit under a memory cap before one is
960
+ unloaded. (#564)
961
+
962
+ ### Fixed
963
+
964
+ - A model name that is not an exact catalog or registry name never resolves
965
+ to a vision projector (`QVAC_MODEL=Qwen3.5-4B` loaded the `mmproj` file and
966
+ failed to initialize). (#551)
967
+ - The device `thinkingDefault` reaches the Qwen3.5 presets, so turning
968
+ thinking off works for 2B and 4B when the agent inherits. (#548)
969
+ - A GGUF header read that drops its connection, or gets a 408, 429 or 5xx, is
970
+ retried up to 3 times, and each failure is logged with its host and cause.
971
+ Add no longer fails after a good preview on a flaky CDN. (#561)
972
+ - A GGUF that names no architecture is no longer offered as a chat model: in
973
+ an `sd.cpp` repo it reads as image generation, otherwise it is refused as
974
+ `not-a-model`. (#529)
975
+ - Small models read an attached PDF with `pdf` instead of `web_fetch` on a
976
+ made-up link, and a text-less page the host already rendered as an image is
977
+ pointed at that image instead of "no OCR here". (#525)
978
+ - A `pptx`, `docx` or `xlsx` call that builds a new file without `output` is
979
+ saved and attached instead of refused. The file is named after
980
+ `create.title` (`Climate Change` → `climate_change.docx`), or
981
+ `presentation.pptx`, `document.docx` or `workbook.xlsx` without one, the way
982
+ the `pdf` tool names a new PDF. A 2B model often left `output` off, and the
983
+ refusal sent it guessing attachment ids until the turn ended with no file.
984
+ A call whose ops only read (`read`, `sheets`, `paragraphStyles`, …) returns
985
+ their results and saves nothing, so it never attaches a blank file.
986
+ (QVAC-26944)
987
+ - A new Word document takes two more of a small model's slips instead of
988
+ refusing the whole call: a block position past the end of what the call has
989
+ built so far lands at the end, and `appendParagraphs` with an `at` inserts
990
+ the paragraphs there. An attached document keeps the strict checks. In any
991
+ `pptx`, `docx` or `xlsx` call, an `{ "op": "output", … }` entry is dropped
992
+ instead of refused, and a file name in it names the file unless `output` is
993
+ already set. (QVAC-26944)
994
+ - In Obsidian vault folder mode, "what's in my vault" lists the notes with
995
+ `obsidian files` instead of passing the vault folder to `read` or guessing
996
+ commands, and a `read` that still names a folder is told to list it with
997
+ `obsidian files` instead of failing with a raw file system error.
998
+ (QVAC-27069)
999
+
904
1000
  ## [0.8.11] - 2026-10-16
905
1001
 
906
1002
  ### Fixed
@@ -2971,7 +3067,8 @@ Install 0.2.12 or later to get them.
2971
3067
  - Every dependency installs from the public npm registry: GPU stats are read
2972
3068
  through `bare-gpu-info`. (#12)
2973
3069
 
2974
- [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v0.8.11...HEAD
3070
+ [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v0.8.12...HEAD
3071
+ [0.8.12]: https://github.com/tetherto/qvac-harness/compare/v0.8.11...v0.8.12
2975
3072
  [0.8.11]: https://github.com/tetherto/qvac-harness/compare/v0.8.10...v0.8.11
2976
3073
  [0.8.10]: https://github.com/tetherto/qvac-harness/compare/v0.8.9...v0.8.10
2977
3074
  [0.8.9]: https://github.com/tetherto/qvac-harness/compare/v0.8.8...v0.8.9
@@ -2,7 +2,7 @@ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  import ReadyResource from 'ready-resource';
3
3
  import { Policy } from './lib/policy/index.ts';
4
4
  import type { EngineBoot, EngineStep, RecoveryResolution } from './lib/run-log/index.ts';
5
- import { type ModelRoundPort } from './lib/capabilities/completion-engine/index.ts';
5
+ import { type ModelRoundIo, type ModelRoundPort, type ModelRoundRequest, type ModelRoundResult } from './lib/capabilities/completion-engine/index.ts';
6
6
  import type { AccessPolicy, AgentConfig, ApproveFn, AskUserFn, AttachFn, CompletionEvent, FetchAttachmentFn, Message, ProgressFn, ResponseFormat, RunGoal, RunInput, ToolDefinition, ToolExecuteContext } from './lib/contract/index.ts';
7
7
  import { type DetectLanguageContext, type DetectedLanguage } from './lib/capabilities/detect-language.ts';
8
8
  import { type Capability } from './lib/capabilities/invoke.ts';
@@ -148,6 +148,7 @@ export interface CompletionContext {
148
148
  messages: Message[];
149
149
  typedText?: string;
150
150
  cacheKey?: string;
151
+ replaysContext?: boolean;
151
152
  session?: string;
152
153
  thinkingDefault?: string;
153
154
  toolConfigs?: Record<string, Record<string, unknown>>;
@@ -310,6 +311,8 @@ export declare class Harness extends ReadyResource {
310
311
  invoke(context: InvokeContext): AsyncGenerator<CompletionEvent>;
311
312
  private _invoke;
312
313
  completion(context: CompletionContext | ResumeCompletionContext): AsyncGenerator<CompletionEvent>;
314
+ serveModelRound(request: ModelRoundRequest, io: ModelRoundIo): Promise<ModelRoundResult>;
315
+ private _servedRoundFailed;
313
316
  private _completion;
314
317
  private _runCompletion;
315
318
  private _access;
package/dist-lib/index.js CHANGED
@@ -3,6 +3,7 @@ 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';
6
7
  import { probeGpuStats } from './lib/hardware/gpu-probe.js';
7
8
  import { probeCapabilityProfile } from './lib/hardware/capability-probe.js';
8
9
  import { Lifecycle } from './lib/lifecycle/index.js';
@@ -76,6 +77,7 @@ export const PLUGIN_API_VERSION = PluginRegistry.API_VERSION;
76
77
  const SUSPEND_SETTLE_MS = 500;
77
78
  const SPEECH_PLUGIN_MISSING = 'speech needs the speech plugin';
78
79
  const KNOWLEDGE_PLUGIN_MISSING = 'knowledge needs the knowledge plugin';
80
+ const UNLOAD_FAILED = 'Runtime unload failed; close the harness before loading models again';
79
81
  const HOST_SHELL = { name: 'host' };
80
82
  function execOptions(exec) {
81
83
  if (!exec)
@@ -841,13 +843,52 @@ export class Harness extends ReadyResource {
841
843
  }
842
844
  return Agent.follow({ completion: (hop) => this._completion(hop) }, { ...context, goal: undefined });
843
845
  }
846
+ async serveModelRound(request, io) {
847
+ if (!this.opened)
848
+ await this.ready();
849
+ this._lifecycle.assertNotClosing();
850
+ if (this.suspended || this._lifecycle.draining) {
851
+ throw new HarnessError('HARNESS_SUSPENDED');
852
+ }
853
+ if (this._lifecycle.unloadFailed) {
854
+ throw new Error(UNLOAD_FAILED);
855
+ }
856
+ const { modelId } = request;
857
+ const { key, acquireRound } = this._residency.servedRound(modelId);
858
+ let served;
859
+ const round = this._lifecycle.trackCompletion((signal) => this._residency.busyStream(async function* () {
860
+ served = await CompletionEngine.serveModelRound(request, { signal, emit: (event) => io.emit(event), retake: () => io.retake() }, { acquireRound });
861
+ }), io.signal);
862
+ try {
863
+ await round.next();
864
+ }
865
+ catch (err) {
866
+ throw await this._servedRoundFailed(err, modelId, key);
867
+ }
868
+ if (!served) {
869
+ throw new Error('A served round ended without its result');
870
+ }
871
+ this._residency.clearFaults(modelId);
872
+ return served;
873
+ }
874
+ async _servedRoundFailed(err, model, key) {
875
+ const aborted = err instanceof AbortedError || this.suspended || this._lifecycle.draining;
876
+ if (aborted || !isSdkModelWedgedError(err)) {
877
+ return err;
878
+ }
879
+ const wedged = await this._residency.evictWedged(model, key);
880
+ if (wedged.fatal) {
881
+ setTimeout(() => process.exit(1), 0);
882
+ }
883
+ return new Error(wedged.message, { cause: err });
884
+ }
844
885
  _completion(context) {
845
886
  this._lifecycle.assertNotClosing();
846
887
  if (this._lifecycle.draining) {
847
888
  throw new HarnessError('HARNESS_SUSPENDED');
848
889
  }
849
890
  if (this._lifecycle.unloadFailed) {
850
- throw new Error('Runtime unload failed; close the harness before loading models again');
891
+ throw new Error(UNLOAD_FAILED);
851
892
  }
852
893
  return this._lifecycle.trackCompletion((signal) => this._residency.busyStream(() => this._runCompletion({ ...context, signal })), context.signal);
853
894
  }
@@ -88,7 +88,8 @@ export function inspectCall(deps, context, snapshot) {
88
88
  execution,
89
89
  resource,
90
90
  call: snapshot,
91
- answeredRead
91
+ answeredRead,
92
+ unknownTool: unknownToolError(session, resolved.call.name)
92
93
  });
93
94
  return {
94
95
  call: snapshot,
@@ -110,10 +111,19 @@ export function inspectCall(deps, context, snapshot) {
110
111
  rejection
111
112
  };
112
113
  }
114
+ function unknownToolError(session, name) {
115
+ const searchable = session.sdkTools?.some((tool) => tool.name === name && tool.deferLoading);
116
+ const [owner] = searchable
117
+ ? (Agent.collectToolGrants(session.inContextSkills).grantedOwners.get(name) ?? [])
118
+ : [];
119
+ return owner
120
+ ? `${name} needs the ${owner} skill. Load it first, then call ${name}.`
121
+ : `unknown tool: ${name}`;
122
+ }
113
123
  const SKILL_WRITE_DENIED = 'Skill loaders must be read-only; this operation was not run.';
114
124
  const repeatedReadMessage = (name) => `The result of this exact ${name} call is already above. Answer from it now; ` +
115
125
  `do not call ${name} again with the same arguments.`;
116
- function inspectRejection({ context, plan, execution, resource, call, answeredRead }) {
126
+ function inspectRejection({ context, plan, execution, resource, call, answeredRead, unknownTool }) {
117
127
  const effect = plan.effect;
118
128
  const source = plan.source;
119
129
  const base = { activity: null, effect, source };
@@ -165,7 +175,7 @@ function inspectRejection({ context, plan, execution, resource, call, answeredRe
165
175
  if (!plan.toolAvailable) {
166
176
  return {
167
177
  ...base,
168
- result: { error: `unknown tool: ${call.name}` },
178
+ result: { error: unknownTool },
169
179
  activity: policyActivity({ call, effect, resource: null })
170
180
  };
171
181
  }
@@ -4,6 +4,7 @@ import { labelOf, skillEmojiFrom } from '../loop.js';
4
4
  import { readyPreflightFromFacts, reportFailure } from '../tool-execution.js';
5
5
  import { skillFileKey } from '../../tool-plan.js';
6
6
  import { toolResultTurn } from '../../tool-turns.js';
7
+ import { skillLoadTurns } from '../../sdk-tool.js';
7
8
  import { isRecord } from '../../../guards.js';
8
9
  import { loadedSkills } from '../session.js';
9
10
  import { trustedSources } from './execution-plan.js';
@@ -82,8 +83,14 @@ export async function loadSkill({ emit, input: deps, context }, plan) {
82
83
  session.loadedFilesThisTurn.add(fileKey);
83
84
  }
84
85
  session.reselectTools?.(new Set([...loadedSkills(context, session), skillName]));
86
+ const skill = session.inContextSkills.find(({ name }) => name === skillName);
87
+ const loads = skillLoadTurns(skill, {
88
+ sent: session.sdkTools,
89
+ enabled: session.enabled,
90
+ history
91
+ });
85
92
  return {
86
- history: spliceFrom(context.history, history),
93
+ history: spliceFrom(context.history, [...history, ...loads]),
87
94
  source: session.outbound.facts('skill', turn),
88
95
  activate: skillName
89
96
  };
@@ -1,8 +1,8 @@
1
1
  import { Agent } from '../../../agent/index.js';
2
2
  import { spliceFrom } from '../splice.js';
3
3
  import { AbortedError } from '../../../helpers/race-abort.js';
4
- import { annotateLastUserTime, lastUserContent } from '../../../prompt.js';
5
- import { explicitWebSearchQuery, knowledgeLastUser, lastUserImages, modelTurns, withPromptContext } from '../turns.js';
4
+ import { currentTimeAnnotation, lastUserContent } from '../../../prompt.js';
5
+ import { explicitWebSearchQuery, 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 { 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 } 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,20 +38,21 @@ 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
- return ({ input, context, reconstruct }) => prepare({ input, context, reconstruct, source });
47
+ return ({ input, context, reconstruct, emit }) => prepare({ input, context, reconstruct, source, emit });
47
48
  }
48
- async function prepare({ input, context, reconstruct, source }) {
49
+ async function prepare({ input, context, reconstruct, source, emit }) {
49
50
  const { args, session } = input;
50
51
  const { model, agent, thinkingDefault, generationParams: generationParamsOverride, responseFormat, messages: storedMessages, tools: allTools = [], skillCatalog = [], signal, fsRoots = [], fsWriteRoots = [], deferTools } = args;
51
52
  if (signal?.aborted) {
52
53
  throw new AbortedError();
53
54
  }
54
- const messages = modelTurns(storedMessages, context.policy.continuationNudge);
55
+ const messages = modelTurns(bareTurn(storedMessages), context.policy.continuationNudge);
55
56
  const userText = args.typedText === undefined ? lastUserContent(messages) : stripControlTokens(args.typedText);
56
57
  let promptContext;
57
58
  if (!session.runStarted && !reconstruct) {
@@ -98,12 +99,16 @@ async function prepare({ input, context, reconstruct, source }) {
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,44 +130,43 @@ async function prepare({ input, context, reconstruct, source }) {
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
- const turns = [
154
- ...withPromptContext(knowledgeLastUser(messages, hits), promptContext),
155
- ...checksAsk(context, takesCommand(enabled))
156
- ];
157
- const initialHistory = systemContent
158
- ? [{ role: 'system', content: systemContent }, ...turns]
159
- : turns;
160
- const history = context.round > 0 || context.directSearchDone
161
- ? [...context.history]
162
- : annotateLastUserTime(initialHistory, new Date(session.startedAt));
163
- const sources = context.round > 0 || context.directSearchDone
164
- ? [...context.sources]
165
- : hits.map((hit) => session.outbound.facts('tool-result', hit.text));
154
+ const firstTurn = context.round === 0 && !context.directSearchDone;
155
+ const added = addedContext(hits, promptContext);
156
+ const sentAt = storedMessages.findLast((turn) => turn.role === 'user')?.sentAt;
157
+ const time = currentTimeAnnotation(new Date(sentAt || session.startedAt));
158
+ const withSystem = (turns) => systemContent ? [{ role: 'system', content: systemContent }, ...turns] : turns;
159
+ const checks = checksAsk(context, takesCommand(enabled));
160
+ const initialHistory = withSystem([...withTurnContext(messages, added), ...checks]);
161
+ const history = firstTurn
162
+ ? withSystem([...withTurnContext(messages, { time, ...added }), ...checks])
163
+ : [...context.history];
164
+ if (firstTurn && !reconstruct && messages.some((turn) => turn.role === 'user')) {
165
+ emit({ type: 'context', context: { time, ...added }, round: context.round });
166
+ }
167
+ const sources = firstTurn
168
+ ? hits.map((hit) => session.outbound.facts('tool-result', hit.text))
169
+ : [...context.sources];
166
170
  const preparation = {
167
171
  history: spliceFrom(context.history, history),
168
172
  activated: [...loadedSkills],
@@ -208,6 +212,28 @@ async function prepare({ input, context, reconstruct, source }) {
208
212
  searchQuery: searchQuery(false)
209
213
  };
210
214
  }
215
+ function bareTurn(messages) {
216
+ const at = messages.findLastIndex((turn) => turn.role === 'user');
217
+ const turn = messages[at];
218
+ if (!turn || !('context' in turn)) {
219
+ return messages;
220
+ }
221
+ const bare = { ...turn };
222
+ delete bare.context;
223
+ const next = [...messages];
224
+ next[at] = bare;
225
+ return next;
226
+ }
227
+ function addedContext(hits, notes) {
228
+ const added = {};
229
+ if (hits.length > 0) {
230
+ added.excerpts = hits.map((hit) => hit.text);
231
+ }
232
+ if (notes !== undefined) {
233
+ added.notes = notes;
234
+ }
235
+ return added;
236
+ }
211
237
  function knowledgeHits(deps, context, messages) {
212
238
  if (context.round > 0 || context.directSearchDone) {
213
239
  return Promise.resolve([]);
@@ -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,23 +3,32 @@ import { isFailureResultReference } from '../../../helpers/failure-result.js';
3
3
  import { HarnessLog } from '../../../log.js';
4
4
  import { errorMessage } from '../../../guards.js';
5
5
  import { spliceFrom } from '../splice.js';
6
- import { knowledgeLastUser } from '../turns.js';
7
- export const retrieving = async function retrieving({ input, context }) {
8
- const { history } = context;
6
+ import { turnText } from '../turns.js';
7
+ export const retrieving = async function retrieving({ input, context, emit }) {
8
+ const { history, edgeInputs } = context;
9
9
  const at = history.findLastIndex((entry) => !isFailureResultReference(entry) && entry.role === 'user');
10
10
  const turn = history[at];
11
- if (!turn || isFailureResultReference(turn)) {
12
- return {};
11
+ const hits = turn && !isFailureResultReference(turn)
12
+ ? await knowledgeSearch(input, {
13
+ id: `${context.runId}:round-${context.round}:input:knowledge`,
14
+ text: turn.content
15
+ })
16
+ : [];
17
+ const excerpts = hits.map((hit) => hit.text);
18
+ for (const [index, queued] of edgeInputs.entries()) {
19
+ const added = index === edgeInputs.length - 1 && excerpts.length ? { excerpts } : {};
20
+ const turnContext = { ...queued.context, ...added };
21
+ 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 });
25
+ }
13
26
  }
14
- const hits = await knowledgeSearch(input, {
15
- id: `${context.runId}:round-${context.round}:input:knowledge`,
16
- text: turn.content
17
- });
18
- if (hits.length === 0) {
27
+ if (!turn || isFailureResultReference(turn) || hits.length === 0) {
19
28
  return {};
20
29
  }
21
30
  const next = [...history];
22
- next[at] = knowledgeLastUser([turn], hits)[0];
31
+ next[at] = { ...turn, content: turnText(turn.content, { excerpts }) };
23
32
  return {
24
33
  history: spliceFrom(history, next),
25
34
  sources: hits.map((hit) => input.session.outbound.facts('tool-result', hit.text))
@@ -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),