@qvac/harness 0.8.11 → 0.8.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +139 -1
  2. package/dist-lib/index.d.ts +1 -0
  3. package/dist-lib/index.js +16 -8
  4. package/dist-lib/lib/capabilities/completion.d.ts +9 -1
  5. package/dist-lib/lib/capabilities/completion.js +87 -25
  6. package/dist-lib/lib/capabilities/preview-model-source.d.ts +7 -1
  7. package/dist-lib/lib/capabilities/preview-model-source.js +80 -22
  8. package/dist-lib/lib/capabilities/tool-search.d.ts +4 -0
  9. package/dist-lib/lib/capabilities/tool-search.js +9 -0
  10. package/dist-lib/lib/capabilities/tool-selection.d.ts +3 -1
  11. package/dist-lib/lib/capabilities/tool-selection.js +3 -2
  12. package/dist-lib/lib/connect.js +3 -2
  13. package/dist-lib/lib/contract-types.d.ts +1 -0
  14. package/dist-lib/lib/errors.d.ts +4 -0
  15. package/dist-lib/lib/errors.js +6 -0
  16. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  17. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  18. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  19. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  20. package/dist-lib/lib/models/gguf-header.d.ts +11 -0
  21. package/dist-lib/lib/models/gguf-header.js +203 -15
  22. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  23. package/dist-lib/lib/models/kv-cache.js +8 -0
  24. package/dist-lib/lib/models/llm-presets.d.ts +2 -1
  25. package/dist-lib/lib/models/llm-presets.js +2 -2
  26. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  27. package/dist-lib/lib/models/model-pool.d.ts +6 -1
  28. package/dist-lib/lib/models/model-pool.js +22 -10
  29. package/dist-lib/lib/models/model-source.d.ts +1 -0
  30. package/dist-lib/lib/models/model-source.js +20 -3
  31. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  32. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  33. package/dist-lib/lib/prompt.d.ts +2 -1
  34. package/dist-lib/lib/prompt.js +12 -12
  35. package/dist-lib/lib/serve.js +3 -2
  36. package/dist-lib/lib/tools/edit-image.js +4 -3
  37. package/dist-lib/lib/tools/exec/adapters/python/attachments.d.ts +1 -0
  38. package/dist-lib/lib/tools/exec/adapters/python/attachments.js +11 -0
  39. package/dist-lib/lib/tools/exec/obsidian/guidance.js +2 -2
  40. package/dist-lib/lib/tools/exec/obsidian/vault-read.js +17 -16
  41. package/dist-lib/lib/tools/generate-image.js +4 -3
  42. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  43. package/dist-lib/lib/tools/http-request/request.js +2 -1
  44. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +17 -1
  45. package/dist-lib/lib/tools/http-request/truncate-response.js +51 -9
  46. package/dist-lib/lib/tools/http-request.js +13 -6
  47. package/dist-lib/lib/tools/mcp-call.js +1 -0
  48. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  49. package/dist-lib/lib/tools/office/ops.js +5 -1
  50. package/dist-lib/lib/tools/office.d.ts +1 -0
  51. package/dist-lib/lib/tools/office.js +197 -35
  52. package/dist-lib/lib/tools/operations/compile.js +4 -4
  53. package/dist-lib/lib/tools/pdf/build.d.ts +5 -1
  54. package/dist-lib/lib/tools/pdf/build.js +31 -6
  55. package/dist-lib/lib/tools/pdf.js +17 -2
  56. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  57. package/dist-lib/lib/tools/skills/credential-check.js +1 -0
  58. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  59. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  60. package/dist-lib/schema/harness.js +2 -1
  61. package/dist-lib/spec/hrpc/messages.js +8 -5
  62. package/dist-lib/spec/hyperschema/index.js +8 -5
  63. package/dist-lib/spec/hyperschema/schema.json +6 -1
  64. package/dist-lib/spec/hyperschema/types.d.ts +2 -1
  65. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -8,6 +8,142 @@ While the major version is `0`, a breaking change bumps the minor version.
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.8.13] - 2026-10-23
12
+
13
+ ### Added
14
+
15
+ - `ToolDefinition.deliversMany`, for a tool one request may call several times
16
+ for several files. A file it delivers gets the delivered-file nudge but does
17
+ not end the run one tool round later, so "draw a cat, a dog and a bird" made
18
+ one image per round still gets all three. `generate_image` and `edit_image`
19
+ set it. (#610)
20
+ - A skill whose oauth setup route has a `verify` probe and a `credentialKey`
21
+ gets that probe as its `requires.credentialChecks` entry for the key, when
22
+ the skill declares none, so a dead token reads as rejected instead of
23
+ needs-setup. A hand-written check still wins. A credential check may now
24
+ carry a `body`. A `verify` rule keyed on a response field (Spotify Premium)
25
+ still marks the token rejected in the health probe only on 401 or 403.
26
+ (#618)
27
+ - `sentAt` on a chat message, on the `@harness/message` wire type and the
28
+ contract `ChatMessage`: each user turn is stamped with its own send time,
29
+ and the stamp names the weekday. (#592)
30
+
31
+ ### Changed
32
+
33
+ - **Breaking** for a host that reads `attachmentId` off a `generate_image` or
34
+ `edit_image` result, in a chat or from `invoke` with the `image` capability:
35
+ the image is now `attachments[0]`, `{ attachmentId, fileName, byteLength }`,
36
+ the shape a delivered file has everywhere else. (#610)
37
+ - On Android, a CPU completion load runs on the performance cores only
38
+ (`threads` and `cpu-mask` from each core's max frequency), instead of one
39
+ thread per core. GPU loads, iOS and desktop are unchanged. (#601)
40
+
41
+ ### Fixed
42
+
43
+ - The wrap-up round a run ends on after blocked repeats keeps the tool block in
44
+ the prompt and forbids a call with `tool_choice: "none"`, instead of dropping
45
+ the block. Under `@qvac/sdk` 0.22 the dropped block rewrote the chat's one
46
+ cache file, so that round and the next turn each re-read the whole chat
47
+ (19.6 s to first token on Qwen3.5-2B after a 12-turn chat). (#605)
48
+ - Every user turn of a saved chat renders the same bytes on the next request,
49
+ instead of losing its time stamp, so Qwen 3.5 and 3.8 resume from the cache
50
+ rather than re-reading the whole chat each turn. (#592)
51
+ - A `skill` call resolves a display name, any case, or a tool name exactly one
52
+ skill grants (`pptx`), instead of refusing anything but the folder name.
53
+ (#528)
54
+ - `pptx` skips look-only keys, an invented theme, a body a layout cannot hold
55
+ and a picture with no upload, listing them in `skipped`, instead of
56
+ refusing the whole deck. (#527)
57
+ - After `generate_image` or `edit_image`, the next round is told the image is
58
+ attached and shown to the user, as it is after `pdf`, the office tools and
59
+ `exec`, instead of "call the next tool, or answer". On that nudge Qwen3.5-4B
60
+ sometimes called `generate_image` again to show the image it had just made,
61
+ and the chat got two. (#610)
62
+ - A custom model whose head width a quantized KV block does not divide loads
63
+ with an `f16` cache instead of failing with "Failed to initialize context"
64
+ (BeeLLM, head width 40, under the hosts' `q8_0`). (#614)
65
+ - A custom model whose chat template has no `<think>` tag no longer starts its
66
+ reply inside a think block, so the reply stops streaming as thinking and then
67
+ repeating as the answer (Qwen2.5-Coder with thinking on). Its reasoning
68
+ budget is unchanged. (#614)
69
+ - An `http_request` body, or a shaped skill operation response, is cut at a
70
+ share of the context window instead of a fixed 8 KB: half the room the last
71
+ round left, at a character per token so Chinese or Japanese text cannot
72
+ overflow it, and shared by every call in the round. With 11k tokens used of
73
+ a 51k window that is 20,000 characters where it was 8,192. A cut result
74
+ carries `truncated`, with the characters kept, the total, the share read and
75
+ a note that the reply must say so. A Google Doc export came back as its
76
+ first fragment and the model summarized that as the whole document. See
77
+ [the decision record](./docs/decisions/2026-10-23-a-tool-response-is-cut-to-the-window-and-says-so.md). (#615)
78
+ - `http_request` gives up once no byte has arrived for 10 seconds, at any
79
+ point in the request, instead of 10 seconds for the whole response. A body
80
+ that keeps arriving gets up to 30 seconds, so a large Google Doc export on a
81
+ slow link finishes, while a server that stops answering still fails as fast
82
+ as before. (#619)
83
+
84
+ ### Security
85
+
86
+ - Requires `bare-tls` 3.1.13, whose CA bundle drops emSign ECC Root CA – G3,
87
+ whose subordinate keys were recovered. Bare checks no revocation. (#593)
88
+
89
+ ## [0.8.12] - 2026-10-21
90
+
91
+ ### Added
92
+
93
+ - A custom GGUF the catalog does not know is sized by the engine fitter from
94
+ its header and tensor list, so its preview gives a fit verdict instead of
95
+ "Fit unknown". Split models stay unknown. (#562)
96
+
97
+ ### Changed
98
+
99
+ - `http_request`, `mcp_call` and every skill-gated tool (`docx`, `pptx`,
100
+ `xlsx`, `pdf`, `generate_image`, `weather_lookup`, compiled skill operations,
101
+ …) are deferred behind `tool_search`: their schemas stay out of the prompt
102
+ until searched, called or loaded with their skill. The tool set is fixed per
103
+ chat, so a skill load no longer re-primes the prompt cache. `skill-eval`
104
+ gains `--defer`. (#566)
105
+ - `@qvac/sdk` and `@qvac/inference` move to `^0.22.0`. Loads are sized on the
106
+ fitter's `floorBytes`, so more models fit under a memory cap before one is
107
+ unloaded. (#564)
108
+
109
+ ### Fixed
110
+
111
+ - A model name that is not an exact catalog or registry name never resolves
112
+ to a vision projector (`QVAC_MODEL=Qwen3.5-4B` loaded the `mmproj` file and
113
+ failed to initialize). (#551)
114
+ - The device `thinkingDefault` reaches the Qwen3.5 presets, so turning
115
+ thinking off works for 2B and 4B when the agent inherits. (#548)
116
+ - A GGUF header read that drops its connection, or gets a 408, 429 or 5xx, is
117
+ retried up to 3 times, and each failure is logged with its host and cause.
118
+ Add no longer fails after a good preview on a flaky CDN. (#561)
119
+ - A GGUF that names no architecture is no longer offered as a chat model: in
120
+ an `sd.cpp` repo it reads as image generation, otherwise it is refused as
121
+ `not-a-model`. (#529)
122
+ - Small models read an attached PDF with `pdf` instead of `web_fetch` on a
123
+ made-up link, and a text-less page the host already rendered as an image is
124
+ pointed at that image instead of "no OCR here". (#525)
125
+ - A `pptx`, `docx` or `xlsx` call that builds a new file without `output` is
126
+ saved and attached instead of refused. The file is named after
127
+ `create.title` (`Climate Change` → `climate_change.docx`), or
128
+ `presentation.pptx`, `document.docx` or `workbook.xlsx` without one, the way
129
+ the `pdf` tool names a new PDF. A 2B model often left `output` off, and the
130
+ refusal sent it guessing attachment ids until the turn ended with no file.
131
+ A call whose ops only read (`read`, `sheets`, `paragraphStyles`, …) returns
132
+ their results and saves nothing, so it never attaches a blank file.
133
+ (QVAC-26944)
134
+ - A new Word document takes two more of a small model's slips instead of
135
+ refusing the whole call: a block position past the end of what the call has
136
+ built so far lands at the end, and `appendParagraphs` with an `at` inserts
137
+ the paragraphs there. An attached document keeps the strict checks. In any
138
+ `pptx`, `docx` or `xlsx` call, an `{ "op": "output", … }` entry is dropped
139
+ instead of refused, and a file name in it names the file unless `output` is
140
+ already set. (QVAC-26944)
141
+ - In Obsidian vault folder mode, "what's in my vault" lists the notes with
142
+ `obsidian files` instead of passing the vault folder to `read` or guessing
143
+ commands, and a `read` that still names a folder is told to list it with
144
+ `obsidian files` instead of failing with a raw file system error.
145
+ (QVAC-27069)
146
+
11
147
  ## [0.8.11] - 2026-10-16
12
148
 
13
149
  ### Fixed
@@ -2078,7 +2214,9 @@ Install 0.2.12 or later to get them.
2078
2214
  - Every dependency installs from the public npm registry: GPU stats are read
2079
2215
  through `bare-gpu-info`. (#12)
2080
2216
 
2081
- [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v0.8.11...HEAD
2217
+ [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v0.8.13...HEAD
2218
+ [0.8.13]: https://github.com/tetherto/qvac-harness/compare/v0.8.12...v0.8.13
2219
+ [0.8.12]: https://github.com/tetherto/qvac-harness/compare/v0.8.11...v0.8.12
2082
2220
  [0.8.11]: https://github.com/tetherto/qvac-harness/compare/v0.8.10...v0.8.11
2083
2221
  [0.8.10]: https://github.com/tetherto/qvac-harness/compare/v0.8.9...v0.8.10
2084
2222
  [0.8.9]: https://github.com/tetherto/qvac-harness/compare/v0.8.8...v0.8.9
@@ -167,6 +167,7 @@ export declare class Harness extends ReadyResource {
167
167
  private readonly _llmDevice?;
168
168
  private readonly _llmGpuLayers?;
169
169
  private readonly _contextSize?;
170
+ private readonly _recentFits;
170
171
  private readonly _kvCacheK?;
171
172
  private readonly _kvCacheV?;
172
173
  private readonly _transcriptionDevice?;
package/dist-lib/index.js CHANGED
@@ -4,6 +4,7 @@ import { platform, totalmem } from 'os';
4
4
  import process from 'process';
5
5
  import ReadyResource from 'ready-resource';
6
6
  import { HarnessError } from './lib/errors.js';
7
+ import { androidCpuPlacement } from './lib/hardware/cpu-placement.js';
7
8
  import { probeGpuStats } from './lib/hardware/gpu-probe.js';
8
9
  import { probeCapabilityProfile } from './lib/hardware/capability-probe.js';
9
10
  import { closePythonWorker } from './lib/tools/exec/adapters/python/worker/active.js';
@@ -142,6 +143,7 @@ export class Harness extends ReadyResource {
142
143
  _llmDevice;
143
144
  _llmGpuLayers;
144
145
  _contextSize;
146
+ _recentFits = new Map();
145
147
  _kvCacheK;
146
148
  _kvCacheV;
147
149
  _transcriptionDevice;
@@ -597,14 +599,18 @@ export class Harness extends ReadyResource {
597
599
  return isModelSourceCached(sdk, { model, addon, modelsDir: this._modelsDir });
598
600
  }
599
601
  previewModelSource(context) {
600
- return previewModelSource(context, { assessFit: (query) => this._assessFit(query) });
602
+ return previewModelSource(context, {
603
+ assessFit: (query) => this._assessFit(query),
604
+ contextSize: this._contextSize,
605
+ recentFits: this._recentFits
606
+ });
601
607
  }
602
608
  async _assessFit({ src, sha256Checksum, name, contextTokens }) {
603
609
  const sdk = await this._sdk.load();
604
610
  const result = await sdk.assessModelFit({
605
611
  models: [
606
612
  {
607
- modelSrc: { src, sha256Checksum, name },
613
+ modelSrc: sha256Checksum ? { src, sha256Checksum, name } : src,
608
614
  modelType: 'llm',
609
615
  modelConfig: { ctx_size: contextTokens }
610
616
  }
@@ -716,7 +722,8 @@ export class Harness extends ReadyResource {
716
722
  kvCacheK: this._kvCacheK,
717
723
  kvCacheV: this._kvCacheV,
718
724
  mainGpu: resolveMainGpu,
719
- openclCacheDir
725
+ openclCacheDir,
726
+ cpuPlacement: androidCpuPlacement
720
727
  };
721
728
  }
722
729
  _createPool() {
@@ -726,7 +733,8 @@ export class Harness extends ReadyResource {
726
733
  loads: this._loads,
727
734
  beforeLoad: (load) => this._beforeLoad(load),
728
735
  chooseContext: (load, tier) => this._chooseContext(load, tier),
729
- hold: this._hold
736
+ hold: this._hold,
737
+ modelsDir: this._modelsDir
730
738
  });
731
739
  }
732
740
  _createEmbedPool() {
@@ -1488,12 +1496,11 @@ export class Harness extends ReadyResource {
1488
1496
  models: [{ modelSrc: fitSrc(modelSrc), modelType, modelConfig: config }]
1489
1497
  });
1490
1498
  const [fit] = models;
1491
- const bytes = fit?.estimate?.upperBoundBytes ?? fit?.floorBytes ?? downloaded;
1499
+ const bytes = fit?.floorBytes ?? downloaded;
1492
1500
  return {
1493
1501
  bytes: bytes === undefined ? undefined : bytes + projection,
1494
1502
  tooLarge: fit?.verdict === 'likely-too-large',
1495
- confirmed: fit?.verdict === 'likely-fits' &&
1496
- (fit.evidence === 'calibration' || fit.evidence === 'native-fit')
1503
+ confirmed: fit?.verdict === 'likely-fits' && fit.evidence === 'native-fit'
1497
1504
  };
1498
1505
  }
1499
1506
  catch (err) {
@@ -1745,7 +1752,7 @@ export class Harness extends ReadyResource {
1745
1752
  };
1746
1753
  this._replying.push(key);
1747
1754
  try {
1748
- const { modelId, ctxSize } = await raceAbort(handle.load(), signal);
1755
+ const { modelId, ctxSize, canThink } = await raceAbort(handle.load(), signal);
1749
1756
  log.info('model ready', { model });
1750
1757
  const sdk = await this._sdk.load();
1751
1758
  const turns = projectionModel ? messages : messages.map(({ attachments, ...turn }) => turn);
@@ -1768,6 +1775,7 @@ export class Harness extends ReadyResource {
1768
1775
  cacheKey,
1769
1776
  session,
1770
1777
  thinkingDefault,
1778
+ canThink,
1771
1779
  generationParams,
1772
1780
  responseFormat,
1773
1781
  captureInferenceCalls,
@@ -3,6 +3,7 @@ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
3
3
  import { type TextEvent } from '../helpers/thinking.ts';
4
4
  import type { ToolCallDisplay } from '../tool-call-display.ts';
5
5
  import { type LlmGenerationParams } from '../models/llm-presets.ts';
6
+ import { type CapabilityProfile } from '../models/model-catalog-constants.ts';
6
7
  import type { DriveRoot } from '../tools/fs/scope.ts';
7
8
  import { type UsageBreakdown } from './usage-breakdown.ts';
8
9
  import { type TrustedSource } from '../tools/outbound-guard.ts';
@@ -17,6 +18,7 @@ export interface Message {
17
18
  role: string;
18
19
  content: string;
19
20
  attachments?: MessageAttachment[];
21
+ sentAt?: number | undefined;
20
22
  [key: string]: unknown;
21
23
  }
22
24
  export interface Agent {
@@ -119,6 +121,7 @@ export type AskUserFn = (question: {
119
121
  export interface RunBudget {
120
122
  readonly deadlineMs: number;
121
123
  outputBytesUsed: number;
124
+ responseRoomChars?: number | undefined;
122
125
  }
123
126
  export interface ToolExecuteContext {
124
127
  agentId?: string | null | undefined;
@@ -178,14 +181,17 @@ export interface ToolDefinition {
178
181
  prompt?: ToolPromptDefinition;
179
182
  autoApprove?: boolean;
180
183
  skillGated?: boolean;
184
+ ungatedFor?: ReadonlyArray<CapabilityProfile>;
181
185
  rootsRequired?: boolean;
182
186
  writeRootsRequired?: boolean;
183
187
  externalWrite?: boolean;
184
188
  owningSkill?: string;
185
189
  toolset: Toolset | null;
190
+ deferLoading?: true;
186
191
  validate?: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => string | null;
187
192
  effect: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => ToolEffect;
188
193
  stableRead?: true;
194
+ deliversMany?: true;
189
195
  resource?: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => ResourceDescriptor | null;
190
196
  compiled?: true;
191
197
  execute: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => Promise<unknown>;
@@ -312,6 +318,7 @@ interface CompletionArgs {
312
318
  cacheKey?: string;
313
319
  session?: string;
314
320
  thinkingDefault?: string;
321
+ canThink?: boolean | undefined;
315
322
  generationParams?: LlmGenerationParams;
316
323
  responseFormat?: ResponseFormat;
317
324
  messages: Message[];
@@ -332,8 +339,9 @@ interface CompletionArgs {
332
339
  }
333
340
  export { CONTEXT_OVERFLOW_MESSAGE } from '../errors.ts';
334
341
  export declare function trustedSourcesFrom(history: readonly Message[]): TrustedSource[];
342
+ export declare function isDeferredTool(tool: ToolDefinition): boolean;
335
343
  export declare function toSdkTool(tool: ToolDefinition): SdkTool;
336
344
  export type CompletionSkillEntry = SkillCatalogEntry & {
337
345
  readonly status?: SkillState;
338
346
  };
339
- export declare function completion(sdk: CompletionSdk, { modelId, acquireRound, model, agent, ctxSize, cacheKey, session, thinkingDefault, generationParams: generationParamsOverride, responseFormat, messages: storedMessages, typedText, tools: allTools, skillCatalog, approve, attach, fetchAttachment, ragSearch, progress, askUser, signal, toolConfigs, fsRoots, fsWriteRoots, captureInferenceCalls }: CompletionArgs): AsyncGenerator<CompletionEvent>;
347
+ export declare function completion(sdk: CompletionSdk, { modelId, acquireRound, model, agent, ctxSize, cacheKey, session, thinkingDefault, canThink, generationParams: generationParamsOverride, responseFormat, messages: storedMessages, typedText, tools: allTools, skillCatalog, approve, attach, fetchAttachment, ragSearch, progress, askUser, signal, toolConfigs, fsRoots, fsWriteRoots, captureInferenceCalls }: CompletionArgs): AsyncGenerator<CompletionEvent>;
@@ -16,20 +16,24 @@ import { fallbackToolLabel } from '../helpers/tool-label.js';
16
16
  import { log } from '../log.js';
17
17
  import { resolveLlmGenerationParams } from '../models/llm-presets.js';
18
18
  import { toolDialectFor } from '../models/model-catalog.js';
19
+ import { modelNameToCapabilityProfile } from '../models/model-catalog-constants.js';
19
20
  import { isContextOverflowError, isGrammarOverrunError, isSdkModelWedgedError } from '../models/sdk-faults.js';
20
- import { annotateLastUserTime, skillsPromptSection, systemPromptParts } from '../prompt.js';
21
+ import { annotateUserTimes, skillsPromptSection, systemPromptParts } from '../prompt.js';
21
22
  import { isMetadataMethod } from '../tools/mcp/protocol.js';
22
23
  import { unquoteArg } from '../tools/model-args.js';
23
24
  import { SKILL_TOOL_NAME, WEB_SEARCH_TOOL_NAME } from './tool-names.js';
24
25
  import { mainFileRequested, skillFileArg, skillFileStem } from '../tools/skill.js';
26
+ import { executeToolSearch, loadedToolNames, renderedTools, TOOL_SEARCH_NAME } from './tool-search.js';
25
27
  import { promptUsageParts, usageBreakdown } from './usage-breakdown.js';
26
28
  import { collectToolGrants, enabledTools, isSelected, skillIsActive, skillsAreSelected } from './tool-selection.js';
27
29
  import { guardToolCall } from '../tools/outbound-guard.js';
28
30
  import { isAvailableState } from '../tools/skills/skill-state-constants.js';
29
31
  import { resolveImplicitSkill, resolveSkillMention } from '../tools/skills/mention.js';
32
+ import { parseToolGrant } from '../tools/skills/tool-grants.js';
30
33
  import { NETWORK_TOOLSETS, permittedTools } from '../tools/toolsets.js';
31
34
  import { promptPrefixHash } from './prompt-prefix.js';
32
35
  import { logToolPrompt } from './tool-prompt-log.js';
36
+ import { responseRoomChars } from '../tools/http-request/truncate-response.js';
33
37
  import { DIRECT_CALL_ID, deliversFile, FILE_DELIVERED_NUDGE, loadedSkillFilesFrom, loadedSkillsFrom, TOOL_CONTINUATION_NUDGE, toolResultTurn } from './tool-turns.js';
34
38
  export function imageSettingsFrom(agent) {
35
39
  if (!agent)
@@ -97,11 +101,17 @@ function intentParameters(tool, params) {
97
101
  required: [INTENT_PARAM, ...(params.required ?? [])]
98
102
  };
99
103
  }
104
+ export function isDeferredTool(tool) {
105
+ return tool.deferLoading === true || tool.skillGated === true;
106
+ }
100
107
  export function toSdkTool(tool) {
108
+ const deferred = isDeferredTool(tool);
101
109
  return {
102
110
  type: 'function',
103
111
  name: tool.name,
104
112
  description: tool.prompt?.description ?? tool.description,
113
+ deferLoading: deferred ? true : undefined,
114
+ group: deferred ? (tool.owningSkill ?? tool.toolset ?? undefined) : undefined,
105
115
  parameters: intentParameters(tool, tool.prompt?.parameters ?? tool.parameters)
106
116
  };
107
117
  }
@@ -417,6 +427,22 @@ function blockedSkillMessage(name, catalog, listShown) {
417
427
  `skill is available this turn — do not guess another name, and answer from what you ` +
418
428
  `already have.`;
419
429
  }
430
+ function withSkillName(call, catalog) {
431
+ if (call.name !== SKILL_TOOL_NAME)
432
+ return call;
433
+ const args = call.arguments;
434
+ const asked = unquoteArg(args.name ?? args.skill_name ?? args.skill).toLowerCase();
435
+ const entry = catalog.find((skill) => skill.name.toLowerCase() === asked) ??
436
+ catalog.find((skill) => skill.displayName?.toLowerCase() === asked) ??
437
+ soleOwner(catalog, asked);
438
+ return entry && entry.name !== args.name
439
+ ? { ...call, arguments: { ...args, name: entry.name } }
440
+ : call;
441
+ }
442
+ function soleOwner(catalog, toolName) {
443
+ const owners = catalog.filter((skill) => skill.tools.some((grant) => parseToolGrant(grant).name === toolName));
444
+ return owners.length === 1 ? owners[0] : undefined;
445
+ }
420
446
  async function resolveToolCalls(toolCalls, { enabled, agentId, pipeline, skillNames, sandboxMode, signal }) {
421
447
  const resolved = [];
422
448
  for (const call of toolCalls) {
@@ -618,7 +644,7 @@ async function* runRecoveredRoundWith(sdk, args, modelId) {
618
644
  try {
619
645
  const result = sdk.completion(params);
620
646
  result.final.catch(noop);
621
- const startInThink = args.generationParams?.reasoning_budget === -1;
647
+ const startInThink = args.generationParams?.reasoning_budget === -1 && args.canThink !== false;
622
648
  for await (const event of runRoundTokens(result, state, {
623
649
  sdk,
624
650
  signal: args.signal,
@@ -709,7 +735,7 @@ function* reportUnnamedWrites(said, landed) {
709
735
  yield { type: 'content', text: unreported };
710
736
  }
711
737
  }
712
- export async function* completion(sdk, { modelId, acquireRound, model, agent, ctxSize, cacheKey, session, thinkingDefault, generationParams: generationParamsOverride, responseFormat, messages: storedMessages, typedText, tools: allTools = [], skillCatalog = [], approve, attach, fetchAttachment, ragSearch, progress, askUser, signal, toolConfigs, fsRoots = [], fsWriteRoots = [], captureInferenceCalls = false }) {
738
+ export async function* completion(sdk, { modelId, acquireRound, model, agent, ctxSize, cacheKey, session, thinkingDefault, canThink, generationParams: generationParamsOverride, responseFormat, messages: storedMessages, typedText, tools: allTools = [], skillCatalog = [], approve, attach, fetchAttachment, ragSearch, progress, askUser, signal, toolConfigs, fsRoots = [], fsWriteRoots = [], captureInferenceCalls = false }) {
713
739
  const pipeline = new HookPipeline();
714
740
  const agentId = agent?.id ?? null;
715
741
  const disabledToolsets = agent?.sandboxMode
@@ -759,7 +785,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
759
785
  const activeSkills = inContextSkills.filter((skill) => skillIsActive(skill.name, activation));
760
786
  const mention = resolveSkillMention(userText, activeSkills);
761
787
  const { grantedNames, grantedOwners, grantedOps } = collectToolGrants(activeSkills);
762
- function selectEnabled() {
788
+ function selectEnabled(offered = false) {
763
789
  if (responseFormat)
764
790
  return [];
765
791
  const loaded = activeSkills.filter((skill) => loadedSkills.has(skill.name));
@@ -768,10 +794,11 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
768
794
  allowlist: agent?.enabledTools ?? [],
769
795
  grantedNames,
770
796
  grantedOwners,
771
- loadedGrantedNames: collectToolGrants(loaded).grantedNames,
797
+ loadedGrantedNames: offered ? grantedNames : collectToolGrants(loaded).grantedNames,
772
798
  hasRoots: fsRoots.length > 0,
773
799
  hasWriteRoots: writableRoots.length > 0,
774
- hasActiveSkills: activeSkills.length > 0
800
+ hasActiveSkills: activeSkills.length > 0,
801
+ capabilityProfile: model ? modelNameToCapabilityProfile(model) : undefined
775
802
  });
776
803
  }
777
804
  const reasoningEnabled = reasoningFlag(agent?.reasoning);
@@ -805,6 +832,17 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
805
832
  }
806
833
  skillIcon = skillEmoji(skillName) ?? skillIcon;
807
834
  }
835
+ function skillToolLoads(skillName, current) {
836
+ const skill = activeSkills.find((each) => each.name === skillName);
837
+ const granted = new Set(skill?.tools.map((entry) => parseToolGrant(entry).name));
838
+ const loaded = loadedToolNames(current);
839
+ return selectEnabled()
840
+ .filter((tool) => isDeferredTool(tool) && granted.has(tool.name) && !loaded.has(tool.name))
841
+ .map((tool) => ({
842
+ role: 'tool',
843
+ content: executeToolSearch([toSdkTool(tool)], { query: tool.name, limit: 1 }, current)
844
+ }));
845
+ }
808
846
  const toolDialect = model ? toolDialectFor(model) : undefined;
809
847
  let preloadedSkill = null;
810
848
  let preloadedResult = null;
@@ -857,15 +895,16 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
857
895
  skillIcon = skillEmoji(preload.name) ?? skillIcon;
858
896
  }
859
897
  let enabled = selectEnabled();
860
- let sdkTools = enabled.length ? enabled.map((tool) => toSdkTool(tool)) : undefined;
898
+ const offered = selectEnabled(true);
899
+ const sdkTools = offered.length ? offered.map((tool) => toSdkTool(tool)) : undefined;
861
900
  const system = systemPromptParts({
862
901
  bio: agent?.bio,
863
902
  toolNames: enabled.map((tool) => tool.name),
864
903
  skillsSection: skillsPromptSection(activeSkills)
865
904
  });
866
905
  const systemContent = system.text;
867
- let promptPrefix = promptPrefixHash({ system: systemContent, tools: sdkTools });
868
- let promptParts = promptUsageParts({ system, toolSchemas: sdkTools });
906
+ const promptPrefix = promptPrefixHash({ system: systemContent, tools: sdkTools });
907
+ const promptParts = promptUsageParts({ system, toolSchemas: renderedTools(sdkTools) });
869
908
  function logSelection() {
870
909
  logToolPrompt({
871
910
  promptPrefix,
@@ -885,9 +924,10 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
885
924
  });
886
925
  }
887
926
  logSelection();
888
- let history = annotateLastUserTime(systemContent ? [{ role: 'system', content: systemContent }, ...messages] : messages);
927
+ let history = annotateUserTimes(systemContent ? [{ role: 'system', content: systemContent }, ...messages] : messages);
889
928
  if (preload && preloadedSkill !== null) {
890
929
  history = directToolHistory(history, { name: SKILL_TOOL_NAME, arguments: { name: preload.name } }, preloadedResult);
930
+ history.push(...skillToolLoads(preload.name, history));
891
931
  }
892
932
  let roundCacheKey = cacheKey;
893
933
  const runUsage = () => usageBreakdown(promptParts, stats.cacheTokens, model);
@@ -980,24 +1020,19 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
980
1020
  let mute = 0;
981
1021
  let narrated = false;
982
1022
  let cappedRounds = 0;
1023
+ let lastToolRound = false;
983
1024
  let roundsSent = 0;
984
1025
  let round = 0;
985
1026
  for (; round < MAX_TOOL_ROUNDS; round++) {
986
1027
  if (signal?.aborted)
987
1028
  throw new AbortedError();
988
1029
  let deliveredThisRound = false;
1030
+ let deliveryEndsRun = false;
989
1031
  if (Date.now() >= runBudget.deadlineMs) {
990
1032
  outcome = 'time-capped';
991
1033
  break;
992
1034
  }
993
- const reselected = selectEnabled();
994
- if (reselected.map((tool) => tool.name).join() !== enabled.map((tool) => tool.name).join()) {
995
- enabled = reselected;
996
- sdkTools = enabled.length ? enabled.map((tool) => toSdkTool(tool)) : undefined;
997
- promptPrefix = promptPrefixHash({ system: systemContent, tools: sdkTools });
998
- promptParts = promptUsageParts({ system, toolSchemas: sdkTools });
999
- logSelection();
1000
- }
1035
+ enabled = selectEnabled();
1001
1036
  log.debug('round start', {
1002
1037
  round,
1003
1038
  turns: history.length,
@@ -1011,6 +1046,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1011
1046
  history,
1012
1047
  tools: sdkTools,
1013
1048
  generationParams,
1049
+ canThink,
1014
1050
  responseFormat,
1015
1051
  toolDialect,
1016
1052
  cacheKey: roundCacheKey,
@@ -1026,11 +1062,14 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1026
1062
  }
1027
1063
  history = recovered.history;
1028
1064
  collectStats(stats, final.stats, final.stopReason);
1065
+ runBudget.responseRoomChars = responseRoomChars(ctxSize, final.stats?.cacheTokens);
1029
1066
  log.debug('round stats', { round, wallMs: Date.now() - roundStarted, ...final.stats });
1030
1067
  const markup = stripToolResponseBlocks(truncateAtControlToken(final.raw.fullText) || recovered.unproven || '');
1068
+ const deferred = sdkTools?.filter((tool) => tool.deferLoading) ?? [];
1069
+ const searchable = deferred.length ? [...enabled, { name: TOOL_SEARCH_NAME }] : enabled;
1031
1070
  let toolCalls = final.toolCalls?.length
1032
1071
  ? final.toolCalls
1033
- : recoverMarkupToolCalls(markup, enabled);
1072
+ : recoverMarkupToolCalls(markup, searchable);
1034
1073
  if (!toolCalls.length && enabled.some((tool) => tool.name === SKILL_TOOL_NAME)) {
1035
1074
  const rescued = recoverPrintedSkillLoad(markup, SKILL_TOOL_NAME);
1036
1075
  const rescuedArgs = rescued[0]?.arguments;
@@ -1097,7 +1136,8 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1097
1136
  });
1098
1137
  toolCalls = toolCalls.slice(0, MAX_CALLS_PER_ROUND);
1099
1138
  }
1100
- const resolved = await resolveToolCalls(toolCalls, {
1139
+ const named = toolCalls.map((call) => withSkillName(call, skillCatalog));
1140
+ const resolved = await resolveToolCalls(named, {
1101
1141
  enabled,
1102
1142
  agentId: agent?.id ?? null,
1103
1143
  pipeline,
@@ -1122,6 +1162,15 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1122
1162
  for (const { call, tool, args, rawCall, rejection, intent } of resolved) {
1123
1163
  if (signal?.aborted)
1124
1164
  throw new AbortedError();
1165
+ if (call.name === TOOL_SEARCH_NAME && deferred.length) {
1166
+ history.push({ role: 'tool', content: executeToolSearch(deferred, args, history) });
1167
+ continue;
1168
+ }
1169
+ if (deferred.some((deferredTool) => deferredTool.name === call.name) &&
1170
+ !loadedToolNames(history).has(call.name)) {
1171
+ const search = { query: call.name, limit: 1 };
1172
+ history.push({ role: 'tool', content: executeToolSearch(deferred, search, history) });
1173
+ }
1125
1174
  const key = callKey(call.name, args);
1126
1175
  const priorFailure = failed.get(key);
1127
1176
  const searchCapped = tool?.name === WEB_SEARCH_TOOL_NAME && webSearches >= MAX_WEB_SEARCHES_PER_TURN;
@@ -1217,7 +1266,13 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1217
1266
  });
1218
1267
  }
1219
1268
  else {
1220
- execution = blockedResult({ error: `unknown tool: ${call.name}` }, `unknown tool: ${call.name}`);
1269
+ const [owner] = offered.some((each) => each.name === call.name)
1270
+ ? (grantedOwners.get(call.name) ?? [])
1271
+ : [];
1272
+ const reason = owner
1273
+ ? `${call.name} needs the ${owner} skill. Load it first, then call ${call.name}.`
1274
+ : `unknown tool: ${call.name}`;
1275
+ execution = blockedResult({ error: reason }, reason);
1221
1276
  }
1222
1277
  const settled = await settleToolCall(pipeline, execution, {
1223
1278
  agentId,
@@ -1291,6 +1346,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1291
1346
  }
1292
1347
  if (executionOutcome.kind === 'success' && deliversFile(output)) {
1293
1348
  deliveredThisRound = true;
1349
+ deliveryEndsRun ||= tool?.deliversMany !== true;
1294
1350
  }
1295
1351
  const turn = toolResultTurn(call.name, call.id, output);
1296
1352
  sources.push({
@@ -1298,6 +1354,9 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1298
1354
  text: turn
1299
1355
  });
1300
1356
  history.push({ role: 'tool', content: turn });
1357
+ if (call.name === SKILL_TOOL_NAME) {
1358
+ history.push(...skillToolLoads(skillName, history));
1359
+ }
1301
1360
  }
1302
1361
  runOutcomes.finishRound();
1303
1362
  if (progressed) {
@@ -1315,13 +1374,14 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1315
1374
  role: 'user',
1316
1375
  content: deliveredThisRound ? FILE_DELIVERED_NUDGE : TOOL_CONTINUATION_NUDGE
1317
1376
  });
1318
- if (runOutcomes.facts().delivered) {
1377
+ if (lastToolRound) {
1319
1378
  outcome = 'delivered';
1320
1379
  break;
1321
1380
  }
1322
1381
  if (deliveredThisRound) {
1323
1382
  runOutcomes.confirmDelivery();
1324
1383
  }
1384
+ lastToolRound ||= deliveryEndsRun;
1325
1385
  if (blockedRepeats >= MAX_BLOCKED_REPEATS) {
1326
1386
  break;
1327
1387
  }
@@ -1351,12 +1411,14 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1351
1411
  modelId,
1352
1412
  acquireRound,
1353
1413
  history,
1354
- tools: undefined,
1355
- generationParams,
1414
+ tools: sdkTools,
1415
+ generationParams: { ...generationParams, tool_choice: 'none' },
1416
+ canThink,
1417
+ toolDialect,
1356
1418
  cacheKey: roundCacheKey,
1357
1419
  signal,
1358
1420
  round: roundsSent,
1359
- promptPrefix: promptPrefixHash({ system: systemContent, tools: undefined }),
1421
+ promptPrefix,
1360
1422
  capture: captureInferenceCalls
1361
1423
  });
1362
1424
  collectStats(stats, recovered.final.stats, recovered.final.stopReason);
@@ -42,7 +42,7 @@ export type PreviewFetch = (url: string, init?: {
42
42
  }) => Promise<PreviewResponse>;
43
43
  export interface FitQuery {
44
44
  src: string;
45
- sha256Checksum: string;
45
+ sha256Checksum?: string;
46
46
  name: string;
47
47
  contextTokens: number;
48
48
  }
@@ -50,6 +50,12 @@ export interface PreviewDeps {
50
50
  fetch?: PreviewFetch;
51
51
  stat?(path: string): Promise<FileStat | null>;
52
52
  assessFit?(query: FitQuery): Promise<FitAssessment>;
53
+ contextSize?: number | undefined;
54
+ recentFits?: Map<string, RecentFit> | undefined;
55
+ }
56
+ export interface RecentFit {
57
+ readonly fit: Promise<FitAssessment>;
58
+ readonly at: number;
53
59
  }
54
60
  export interface FileStat {
55
61
  size: number;