@qvac/harness 0.8.11 → 0.8.12

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.
package/CHANGELOG.md CHANGED
@@ -8,6 +8,64 @@ While the major version is `0`, a breaking change bumps the minor version.
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.8.12] - 2026-10-21
12
+
13
+ ### Added
14
+
15
+ - A custom GGUF the catalog does not know is sized by the engine fitter from
16
+ its header and tensor list, so its preview gives a fit verdict instead of
17
+ "Fit unknown". Split models stay unknown. (#562)
18
+
19
+ ### Changed
20
+
21
+ - `http_request`, `mcp_call` and every skill-gated tool (`docx`, `pptx`,
22
+ `xlsx`, `pdf`, `generate_image`, `weather_lookup`, compiled skill operations,
23
+ …) are deferred behind `tool_search`: their schemas stay out of the prompt
24
+ until searched, called or loaded with their skill. The tool set is fixed per
25
+ chat, so a skill load no longer re-primes the prompt cache. `skill-eval`
26
+ gains `--defer`. (#566)
27
+ - `@qvac/sdk` and `@qvac/inference` move to `^0.22.0`. Loads are sized on the
28
+ fitter's `floorBytes`, so more models fit under a memory cap before one is
29
+ unloaded. (#564)
30
+
31
+ ### Fixed
32
+
33
+ - A model name that is not an exact catalog or registry name never resolves
34
+ to a vision projector (`QVAC_MODEL=Qwen3.5-4B` loaded the `mmproj` file and
35
+ failed to initialize). (#551)
36
+ - The device `thinkingDefault` reaches the Qwen3.5 presets, so turning
37
+ thinking off works for 2B and 4B when the agent inherits. (#548)
38
+ - A GGUF header read that drops its connection, or gets a 408, 429 or 5xx, is
39
+ retried up to 3 times, and each failure is logged with its host and cause.
40
+ Add no longer fails after a good preview on a flaky CDN. (#561)
41
+ - A GGUF that names no architecture is no longer offered as a chat model: in
42
+ an `sd.cpp` repo it reads as image generation, otherwise it is refused as
43
+ `not-a-model`. (#529)
44
+ - Small models read an attached PDF with `pdf` instead of `web_fetch` on a
45
+ made-up link, and a text-less page the host already rendered as an image is
46
+ pointed at that image instead of "no OCR here". (#525)
47
+ - A `pptx`, `docx` or `xlsx` call that builds a new file without `output` is
48
+ saved and attached instead of refused. The file is named after
49
+ `create.title` (`Climate Change` → `climate_change.docx`), or
50
+ `presentation.pptx`, `document.docx` or `workbook.xlsx` without one, the way
51
+ the `pdf` tool names a new PDF. A 2B model often left `output` off, and the
52
+ refusal sent it guessing attachment ids until the turn ended with no file.
53
+ A call whose ops only read (`read`, `sheets`, `paragraphStyles`, …) returns
54
+ their results and saves nothing, so it never attaches a blank file.
55
+ (QVAC-26944)
56
+ - A new Word document takes two more of a small model's slips instead of
57
+ refusing the whole call: a block position past the end of what the call has
58
+ built so far lands at the end, and `appendParagraphs` with an `at` inserts
59
+ the paragraphs there. An attached document keeps the strict checks. In any
60
+ `pptx`, `docx` or `xlsx` call, an `{ "op": "output", … }` entry is dropped
61
+ instead of refused, and a file name in it names the file unless `output` is
62
+ already set. (QVAC-26944)
63
+ - In Obsidian vault folder mode, "what's in my vault" lists the notes with
64
+ `obsidian files` instead of passing the vault folder to `read` or guessing
65
+ commands, and a `read` that still names a folder is told to list it with
66
+ `obsidian files` instead of failing with a raw file system error.
67
+ (QVAC-27069)
68
+
11
69
  ## [0.8.11] - 2026-10-16
12
70
 
13
71
  ### Fixed
@@ -2078,7 +2136,8 @@ Install 0.2.12 or later to get them.
2078
2136
  - Every dependency installs from the public npm registry: GPU stats are read
2079
2137
  through `bare-gpu-info`. (#12)
2080
2138
 
2081
- [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v0.8.11...HEAD
2139
+ [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v0.8.12...HEAD
2140
+ [0.8.12]: https://github.com/tetherto/qvac-harness/compare/v0.8.11...v0.8.12
2082
2141
  [0.8.11]: https://github.com/tetherto/qvac-harness/compare/v0.8.10...v0.8.11
2083
2142
  [0.8.10]: https://github.com/tetherto/qvac-harness/compare/v0.8.9...v0.8.10
2084
2143
  [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
@@ -142,6 +142,7 @@ export class Harness extends ReadyResource {
142
142
  _llmDevice;
143
143
  _llmGpuLayers;
144
144
  _contextSize;
145
+ _recentFits = new Map();
145
146
  _kvCacheK;
146
147
  _kvCacheV;
147
148
  _transcriptionDevice;
@@ -597,14 +598,18 @@ export class Harness extends ReadyResource {
597
598
  return isModelSourceCached(sdk, { model, addon, modelsDir: this._modelsDir });
598
599
  }
599
600
  previewModelSource(context) {
600
- return previewModelSource(context, { assessFit: (query) => this._assessFit(query) });
601
+ return previewModelSource(context, {
602
+ assessFit: (query) => this._assessFit(query),
603
+ contextSize: this._contextSize,
604
+ recentFits: this._recentFits
605
+ });
601
606
  }
602
607
  async _assessFit({ src, sha256Checksum, name, contextTokens }) {
603
608
  const sdk = await this._sdk.load();
604
609
  const result = await sdk.assessModelFit({
605
610
  models: [
606
611
  {
607
- modelSrc: { src, sha256Checksum, name },
612
+ modelSrc: sha256Checksum ? { src, sha256Checksum, name } : src,
608
613
  modelType: 'llm',
609
614
  modelConfig: { ctx_size: contextTokens }
610
615
  }
@@ -1488,12 +1493,11 @@ export class Harness extends ReadyResource {
1488
1493
  models: [{ modelSrc: fitSrc(modelSrc), modelType, modelConfig: config }]
1489
1494
  });
1490
1495
  const [fit] = models;
1491
- const bytes = fit?.estimate?.upperBoundBytes ?? fit?.floorBytes ?? downloaded;
1496
+ const bytes = fit?.floorBytes ?? downloaded;
1492
1497
  return {
1493
1498
  bytes: bytes === undefined ? undefined : bytes + projection,
1494
1499
  tooLarge: fit?.verdict === 'likely-too-large',
1495
- confirmed: fit?.verdict === 'likely-fits' &&
1496
- (fit.evidence === 'calibration' || fit.evidence === 'native-fit')
1500
+ confirmed: fit?.verdict === 'likely-fits' && fit.evidence === 'native-fit'
1497
1501
  };
1498
1502
  }
1499
1503
  catch (err) {
@@ -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';
@@ -178,11 +179,13 @@ export interface ToolDefinition {
178
179
  prompt?: ToolPromptDefinition;
179
180
  autoApprove?: boolean;
180
181
  skillGated?: boolean;
182
+ ungatedFor?: ReadonlyArray<CapabilityProfile>;
181
183
  rootsRequired?: boolean;
182
184
  writeRootsRequired?: boolean;
183
185
  externalWrite?: boolean;
184
186
  owningSkill?: string;
185
187
  toolset: Toolset | null;
188
+ deferLoading?: true;
186
189
  validate?: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => string | null;
187
190
  effect: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => ToolEffect;
188
191
  stableRead?: true;
@@ -332,6 +335,7 @@ interface CompletionArgs {
332
335
  }
333
336
  export { CONTEXT_OVERFLOW_MESSAGE } from '../errors.ts';
334
337
  export declare function trustedSourcesFrom(history: readonly Message[]): TrustedSource[];
338
+ export declare function isDeferredTool(tool: ToolDefinition): boolean;
335
339
  export declare function toSdkTool(tool: ToolDefinition): SdkTool;
336
340
  export type CompletionSkillEntry = SkillCatalogEntry & {
337
341
  readonly status?: SkillState;
@@ -16,17 +16,20 @@ 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
21
  import { annotateLastUserTime, 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';
@@ -97,11 +100,17 @@ function intentParameters(tool, params) {
97
100
  required: [INTENT_PARAM, ...(params.required ?? [])]
98
101
  };
99
102
  }
103
+ export function isDeferredTool(tool) {
104
+ return tool.deferLoading === true || tool.skillGated === true;
105
+ }
100
106
  export function toSdkTool(tool) {
107
+ const deferred = isDeferredTool(tool);
101
108
  return {
102
109
  type: 'function',
103
110
  name: tool.name,
104
111
  description: tool.prompt?.description ?? tool.description,
112
+ deferLoading: deferred ? true : undefined,
113
+ group: deferred ? (tool.owningSkill ?? tool.toolset ?? undefined) : undefined,
105
114
  parameters: intentParameters(tool, tool.prompt?.parameters ?? tool.parameters)
106
115
  };
107
116
  }
@@ -759,7 +768,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
759
768
  const activeSkills = inContextSkills.filter((skill) => skillIsActive(skill.name, activation));
760
769
  const mention = resolveSkillMention(userText, activeSkills);
761
770
  const { grantedNames, grantedOwners, grantedOps } = collectToolGrants(activeSkills);
762
- function selectEnabled() {
771
+ function selectEnabled(offered = false) {
763
772
  if (responseFormat)
764
773
  return [];
765
774
  const loaded = activeSkills.filter((skill) => loadedSkills.has(skill.name));
@@ -768,10 +777,11 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
768
777
  allowlist: agent?.enabledTools ?? [],
769
778
  grantedNames,
770
779
  grantedOwners,
771
- loadedGrantedNames: collectToolGrants(loaded).grantedNames,
780
+ loadedGrantedNames: offered ? grantedNames : collectToolGrants(loaded).grantedNames,
772
781
  hasRoots: fsRoots.length > 0,
773
782
  hasWriteRoots: writableRoots.length > 0,
774
- hasActiveSkills: activeSkills.length > 0
783
+ hasActiveSkills: activeSkills.length > 0,
784
+ capabilityProfile: model ? modelNameToCapabilityProfile(model) : undefined
775
785
  });
776
786
  }
777
787
  const reasoningEnabled = reasoningFlag(agent?.reasoning);
@@ -805,6 +815,17 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
805
815
  }
806
816
  skillIcon = skillEmoji(skillName) ?? skillIcon;
807
817
  }
818
+ function skillToolLoads(skillName, current) {
819
+ const skill = activeSkills.find((each) => each.name === skillName);
820
+ const granted = new Set(skill?.tools.map((entry) => parseToolGrant(entry).name));
821
+ const loaded = loadedToolNames(current);
822
+ return selectEnabled()
823
+ .filter((tool) => isDeferredTool(tool) && granted.has(tool.name) && !loaded.has(tool.name))
824
+ .map((tool) => ({
825
+ role: 'tool',
826
+ content: executeToolSearch([toSdkTool(tool)], { query: tool.name, limit: 1 }, current)
827
+ }));
828
+ }
808
829
  const toolDialect = model ? toolDialectFor(model) : undefined;
809
830
  let preloadedSkill = null;
810
831
  let preloadedResult = null;
@@ -857,15 +878,16 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
857
878
  skillIcon = skillEmoji(preload.name) ?? skillIcon;
858
879
  }
859
880
  let enabled = selectEnabled();
860
- let sdkTools = enabled.length ? enabled.map((tool) => toSdkTool(tool)) : undefined;
881
+ const offered = selectEnabled(true);
882
+ const sdkTools = offered.length ? offered.map((tool) => toSdkTool(tool)) : undefined;
861
883
  const system = systemPromptParts({
862
884
  bio: agent?.bio,
863
885
  toolNames: enabled.map((tool) => tool.name),
864
886
  skillsSection: skillsPromptSection(activeSkills)
865
887
  });
866
888
  const systemContent = system.text;
867
- let promptPrefix = promptPrefixHash({ system: systemContent, tools: sdkTools });
868
- let promptParts = promptUsageParts({ system, toolSchemas: sdkTools });
889
+ const promptPrefix = promptPrefixHash({ system: systemContent, tools: sdkTools });
890
+ const promptParts = promptUsageParts({ system, toolSchemas: renderedTools(sdkTools) });
869
891
  function logSelection() {
870
892
  logToolPrompt({
871
893
  promptPrefix,
@@ -888,6 +910,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
888
910
  let history = annotateLastUserTime(systemContent ? [{ role: 'system', content: systemContent }, ...messages] : messages);
889
911
  if (preload && preloadedSkill !== null) {
890
912
  history = directToolHistory(history, { name: SKILL_TOOL_NAME, arguments: { name: preload.name } }, preloadedResult);
913
+ history.push(...skillToolLoads(preload.name, history));
891
914
  }
892
915
  let roundCacheKey = cacheKey;
893
916
  const runUsage = () => usageBreakdown(promptParts, stats.cacheTokens, model);
@@ -990,14 +1013,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
990
1013
  outcome = 'time-capped';
991
1014
  break;
992
1015
  }
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
- }
1016
+ enabled = selectEnabled();
1001
1017
  log.debug('round start', {
1002
1018
  round,
1003
1019
  turns: history.length,
@@ -1028,9 +1044,11 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1028
1044
  collectStats(stats, final.stats, final.stopReason);
1029
1045
  log.debug('round stats', { round, wallMs: Date.now() - roundStarted, ...final.stats });
1030
1046
  const markup = stripToolResponseBlocks(truncateAtControlToken(final.raw.fullText) || recovered.unproven || '');
1047
+ const deferred = sdkTools?.filter((tool) => tool.deferLoading) ?? [];
1048
+ const searchable = deferred.length ? [...enabled, { name: TOOL_SEARCH_NAME }] : enabled;
1031
1049
  let toolCalls = final.toolCalls?.length
1032
1050
  ? final.toolCalls
1033
- : recoverMarkupToolCalls(markup, enabled);
1051
+ : recoverMarkupToolCalls(markup, searchable);
1034
1052
  if (!toolCalls.length && enabled.some((tool) => tool.name === SKILL_TOOL_NAME)) {
1035
1053
  const rescued = recoverPrintedSkillLoad(markup, SKILL_TOOL_NAME);
1036
1054
  const rescuedArgs = rescued[0]?.arguments;
@@ -1122,6 +1140,15 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1122
1140
  for (const { call, tool, args, rawCall, rejection, intent } of resolved) {
1123
1141
  if (signal?.aborted)
1124
1142
  throw new AbortedError();
1143
+ if (call.name === TOOL_SEARCH_NAME && deferred.length) {
1144
+ history.push({ role: 'tool', content: executeToolSearch(deferred, args, history) });
1145
+ continue;
1146
+ }
1147
+ if (deferred.some((deferredTool) => deferredTool.name === call.name) &&
1148
+ !loadedToolNames(history).has(call.name)) {
1149
+ const search = { query: call.name, limit: 1 };
1150
+ history.push({ role: 'tool', content: executeToolSearch(deferred, search, history) });
1151
+ }
1125
1152
  const key = callKey(call.name, args);
1126
1153
  const priorFailure = failed.get(key);
1127
1154
  const searchCapped = tool?.name === WEB_SEARCH_TOOL_NAME && webSearches >= MAX_WEB_SEARCHES_PER_TURN;
@@ -1217,7 +1244,13 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1217
1244
  });
1218
1245
  }
1219
1246
  else {
1220
- execution = blockedResult({ error: `unknown tool: ${call.name}` }, `unknown tool: ${call.name}`);
1247
+ const [owner] = offered.some((each) => each.name === call.name)
1248
+ ? (grantedOwners.get(call.name) ?? [])
1249
+ : [];
1250
+ const reason = owner
1251
+ ? `${call.name} needs the ${owner} skill. Load it first, then call ${call.name}.`
1252
+ : `unknown tool: ${call.name}`;
1253
+ execution = blockedResult({ error: reason }, reason);
1221
1254
  }
1222
1255
  const settled = await settleToolCall(pipeline, execution, {
1223
1256
  agentId,
@@ -1298,6 +1331,9 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1298
1331
  text: turn
1299
1332
  });
1300
1333
  history.push({ role: 'tool', content: turn });
1334
+ if (call.name === SKILL_TOOL_NAME) {
1335
+ history.push(...skillToolLoads(skillName, history));
1336
+ }
1301
1337
  }
1302
1338
  runOutcomes.finishRound();
1303
1339
  if (progressed) {
@@ -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;
@@ -1,8 +1,11 @@
1
+ import crypto from 'crypto';
1
2
  import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
2
5
  import defaultFetch from '#fetch';
3
6
  import { errorMessage } from '../guards.js';
4
7
  import { defaultContextSize } from '../models/context.js';
5
- import { isRemoteSource, localSourcePath, parseGgufHeader, readGgufHeaderBytes } from '../models/gguf-header.js';
8
+ import { fetchGgufStub, isRemoteSource, localSourcePath, parseGgufHeader, readGgufHeaderBytes } from '../models/gguf-header.js';
6
9
  import { shardSet } from '../models/shards.js';
7
10
  const HUGGING_FACE = 'https://huggingface.co';
8
11
  const HUGGING_FACE_HOSTS = new Set(['huggingface.co', 'www.huggingface.co', 'hf.co']);
@@ -17,6 +20,7 @@ const PIPELINE_TASKS = {
17
20
  'text-generation': 'llm',
18
21
  'image-text-to-text': 'llm'
19
22
  };
23
+ const SD_CPP_TAGS = new Set(['sd.cpp', 'stable-diffusion.cpp']);
20
24
  const ARCHITECTURE_TASKS = [
21
25
  [/^whisper/i, 'speech-to-text'],
22
26
  [/^parakeet/i, 'speech-to-text'],
@@ -25,8 +29,10 @@ const ARCHITECTURE_TASKS = [
25
29
  [/bert/i, 'embeddings']
26
30
  ];
27
31
  const NOT_LLM_REASON = 'Fit is estimated only for text-generation models.';
28
- const NO_CHECKSUM_REASON = 'Fit is estimated only for files the SDK catalog knows by checksum, and this source publishes none.';
32
+ const NO_ARCHITECTURE_REASON = 'This GGUF names no model architecture, so it cannot run as a text model.';
29
33
  const NO_ESTIMATOR_REASON = 'This harness has no fit estimator.';
34
+ const SHARDED_REASON = 'Fit is estimated only for a model in one file, and this one is split.';
35
+ const NO_TENSOR_LIST_REASON = 'Could not read the tensor list the fit estimate needs.';
30
36
  export async function previewModelSource(context, deps = {}) {
31
37
  const fetch = deps.fetch ?? defaultFetch;
32
38
  const src = context.src.trim();
@@ -37,15 +43,15 @@ export async function previewModelSource(context, deps = {}) {
37
43
  if ('answer' in weight) {
38
44
  return weight.answer;
39
45
  }
40
- const problem = modelProblem(weight.header);
41
- if (problem) {
42
- return refuse(problem[0], problem[1]);
43
- }
44
46
  const taskType = taskTypeFor({
45
47
  pipelineTag: weight.file.pipelineTag,
46
48
  tags: [...(weight.file.tags ?? []), ...(weight.header.tags ?? [])],
47
- architecture: weight.header.architecture
49
+ header: weight.header
48
50
  });
51
+ const problem = modelProblem(weight.header, taskType);
52
+ if (problem) {
53
+ return refuse(problem[0], problem[1]);
54
+ }
49
55
  let projectionBytes = 0;
50
56
  let projectionSrc;
51
57
  const mmprojSrc = context.mmprojSrc?.trim();
@@ -62,7 +68,7 @@ export async function previewModelSource(context, deps = {}) {
62
68
  projectionBytes = projection.file.sizeBytes;
63
69
  projectionSrc = projection.file.src;
64
70
  }
65
- const { fit, fitReasons } = await assess(weight, taskType, deps);
71
+ const { fit, fitReasons } = await assess(weight, taskType, { deps, fetch });
66
72
  return defined({
67
73
  ok: true,
68
74
  src: weight.file.src,
@@ -331,7 +337,7 @@ function fileOf(ref, sibling) {
331
337
  sha256: sibling.lfs?.sha256
332
338
  });
333
339
  }
334
- function modelProblem(header) {
340
+ function modelProblem(header, taskType) {
335
341
  if (isProjection(header)) {
336
342
  return [
337
343
  'not-a-model',
@@ -341,35 +347,49 @@ function modelProblem(header) {
341
347
  if (header.type === 'adapter') {
342
348
  return ['not-a-model', 'This is a LoRA adapter, not a model.'];
343
349
  }
350
+ if (taskType === 'llm' && !header.architecture) {
351
+ return ['not-a-model', NO_ARCHITECTURE_REASON];
352
+ }
344
353
  return null;
345
354
  }
346
355
  function isProjection(header) {
347
356
  return header.architecture === 'clip' || header.type === 'mmproj';
348
357
  }
349
- function taskTypeFor({ pipelineTag, tags = [], architecture }) {
358
+ function taskTypeFor({ pipelineTag, tags = [], header }) {
350
359
  const tagged = [pipelineTag, ...tags].find((tag) => tag !== undefined && Object.hasOwn(PIPELINE_TASKS, tag));
351
360
  if (tagged) {
352
361
  return PIPELINE_TASKS[tagged];
353
362
  }
354
- return ARCHITECTURE_TASKS.find(([pattern]) => pattern.test(architecture ?? ''))?.[1] ?? 'llm';
363
+ if (header && !header.architecture && tags.some((tag) => SD_CPP_TAGS.has(tag))) {
364
+ return 'image-generation';
365
+ }
366
+ const architecture = header?.architecture ?? '';
367
+ return ARCHITECTURE_TASKS.find(([pattern]) => pattern.test(architecture))?.[1] ?? 'llm';
355
368
  }
356
- async function assess({ file, header }, taskType, deps) {
369
+ async function assess({ file, header }, taskType, { deps, fetch }) {
370
+ const { assessFit } = deps;
357
371
  if (taskType !== 'llm') {
358
372
  return { fit: 'unknown', fitReasons: [NOT_LLM_REASON] };
359
373
  }
360
- if (!file.sha256) {
361
- return { fit: 'unknown', fitReasons: [NO_CHECKSUM_REASON] };
362
- }
363
- if (!deps.assessFit) {
374
+ if (!assessFit) {
364
375
  return { fit: 'unknown', fitReasons: [NO_ESTIMATOR_REASON] };
365
376
  }
377
+ const query = {
378
+ src: file.src,
379
+ name: header.name ?? file.label,
380
+ contextTokens: deps.contextSize || defaultContextSize(file.src, header.contextLength)
381
+ };
366
382
  try {
367
- return await deps.assessFit({
368
- src: file.src,
369
- sha256Checksum: file.sha256,
370
- name: header.name ?? file.label,
371
- contextTokens: defaultContextSize(file.src, header.contextLength)
372
- });
383
+ const catalog = file.sha256
384
+ ? await assessFit({ ...query, sha256Checksum: file.sha256 }).catch(() => null)
385
+ : null;
386
+ return catalog && catalog.fit !== 'unknown'
387
+ ? catalog
388
+ : await assessTensorList(query, {
389
+ assessFit,
390
+ fetch,
391
+ recentFits: deps.recentFits ?? new Map()
392
+ });
373
393
  }
374
394
  catch (err) {
375
395
  return {
@@ -378,6 +398,44 @@ async function assess({ file, header }, taskType, deps) {
378
398
  };
379
399
  }
380
400
  }
401
+ const RECENT_FIT_MS = 60_000;
402
+ async function assessTensorList(query, tools) {
403
+ const { assessFit, recentFits } = tools;
404
+ if ((shardSet(query.src)?.shards.length ?? 1) > 1) {
405
+ return { fit: 'unknown', fitReasons: [SHARDED_REASON] };
406
+ }
407
+ const local = localSourcePath(query.src);
408
+ if (local !== null) {
409
+ return assessFit({ ...query, src: local });
410
+ }
411
+ const file = path.join(os.tmpdir(), `qvac-fit-stub-${stubName(query.src)}.gguf`);
412
+ const recent = recentFits.get(file);
413
+ if (recent && Date.now() - recent.at < RECENT_FIT_MS) {
414
+ return recent.fit;
415
+ }
416
+ const fit = fitStub(file, query, tools);
417
+ recentFits.set(file, { fit, at: Infinity });
418
+ fit.then((result) => result.fit === 'unknown'
419
+ ? recentFits.delete(file)
420
+ : recentFits.set(file, { fit, at: Date.now() }), () => recentFits.delete(file));
421
+ return fit;
422
+ }
423
+ async function fitStub(file, query, { assessFit, fetch }) {
424
+ const stub = await fetchGgufStub(query.src, { fetch });
425
+ if (!stub) {
426
+ return { fit: 'unknown', fitReasons: [NO_TENSOR_LIST_REASON] };
427
+ }
428
+ try {
429
+ await fs.promises.writeFile(file, stub);
430
+ return await assessFit({ ...query, src: file });
431
+ }
432
+ finally {
433
+ await fs.promises.rm(file, { force: true });
434
+ }
435
+ }
436
+ function stubName(src) {
437
+ return crypto.createHash('sha256').update(src, 'utf8').digest('hex').slice(0, 16);
438
+ }
381
439
  function modelInfoUrl(ref) {
382
440
  const revision = ref.revision === 'main' ? '' : `/revision/${encodeURIComponent(ref.revision)}`;
383
441
  return `${HUGGING_FACE}/api/models/${encodePath(ref.repo)}${revision}?blobs=true`;
@@ -0,0 +1,4 @@
1
+ import type { Tool as SdkTool } from '@qvac/sdk';
2
+ import { executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME } from '#sdk';
3
+ export { executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME };
4
+ export declare function renderedTools(tools: SdkTool[] | undefined): SdkTool[] | undefined;
@@ -0,0 +1,9 @@
1
+ import { buildToolSearchTool, executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME } from '#sdk';
2
+ export { executeToolSearch, loadedToolNames, TOOL_SEARCH_NAME };
3
+ export function renderedTools(tools) {
4
+ const deferred = tools?.filter((tool) => tool.deferLoading);
5
+ if (!tools || !deferred?.length) {
6
+ return tools;
7
+ }
8
+ return [...tools.filter((tool) => !tool.deferLoading), buildToolSearchTool(deferred)];
9
+ }
@@ -24,6 +24,7 @@ export declare function skillIsActive(name: string, { skillsSelected, enabledSki
24
24
  export interface SelectableTool {
25
25
  name: string;
26
26
  skillGated?: boolean | undefined;
27
+ ungatedFor?: ReadonlyArray<string> | undefined;
27
28
  rootsRequired?: boolean | undefined;
28
29
  writeRootsRequired?: boolean | undefined;
29
30
  owningSkill?: string | undefined;
@@ -37,6 +38,7 @@ export interface ToolGateInputs {
37
38
  hasRoots: boolean;
38
39
  hasWriteRoots: boolean;
39
40
  hasActiveSkills: boolean;
41
+ capabilityProfile?: string | undefined;
40
42
  }
41
43
  export declare function isSelected(scope: 'all' | 'selected' | null | undefined, list?: ReadonlyArray<string> | null): boolean;
42
- export declare function enabledTools<T extends SelectableTool>(tools: ReadonlyArray<T>, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills }: ToolGateInputs): T[];
44
+ export declare function enabledTools<T extends SelectableTool>(tools: ReadonlyArray<T>, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills, capabilityProfile }: ToolGateInputs): T[];
@@ -31,7 +31,7 @@ export function skillIsActive(name, { skillsSelected, enabledSkills }) {
31
31
  export function isSelected(scope, list) {
32
32
  return (scope ?? (list?.length ? 'selected' : 'all')) === 'selected';
33
33
  }
34
- export function enabledTools(tools, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills }) {
34
+ export function enabledTools(tools, { toolsSelected, allowlist, grantedNames, grantedOwners, loadedGrantedNames, hasRoots, hasWriteRoots, hasActiveSkills, capabilityProfile }) {
35
35
  return tools.filter((tool) => {
36
36
  if (tool.name === SKILL_TOOL_NAME)
37
37
  return hasActiveSkills;
@@ -49,7 +49,8 @@ export function enabledTools(tools, { toolsSelected, allowlist, grantedNames, gr
49
49
  return hasWriteRoots;
50
50
  }
51
51
  if (tool.skillGated) {
52
- return loadedGrantedNames.has(tool.name);
52
+ const early = capabilityProfile !== undefined && tool.ungatedFor?.includes(capabilityProfile);
53
+ return loadedGrantedNames.has(tool.name) || (early === true && grantedNames.has(tool.name));
53
54
  }
54
55
  if (!toolsSelected) {
55
56
  return true;
@@ -204,6 +204,10 @@ declare const HARNESS_ERRORS: {
204
204
  readonly code: 102610;
205
205
  readonly message: (filePath: string) => string;
206
206
  };
207
+ readonly OBSIDIAN_PATH_IS_FOLDER: {
208
+ readonly code: 102611;
209
+ readonly message: (folder: string) => string;
210
+ };
207
211
  readonly SKILL_FILE_NOT_FOUND: {
208
212
  readonly code: 102701;
209
213
  readonly message: (name: string, file: string) => string;
@@ -143,6 +143,12 @@ const HARNESS_ERRORS = {
143
143
  code: 102610,
144
144
  message: (filePath) => `Destination already exists: ${filePath}`
145
145
  },
146
+ OBSIDIAN_PATH_IS_FOLDER: {
147
+ code: 102611,
148
+ message: (folder) => `"${folder || '.'}" is a folder, not a note. List it with ` +
149
+ (folder ? `\`obsidian files folder="${folder}"\`` : '`obsidian files`') +
150
+ ', then read one note by its path.'
151
+ },
146
152
  SKILL_FILE_NOT_FOUND: {
147
153
  code: 102701,
148
154
  message: (name, file) => `ENOENT: ${name}/${file}`
@@ -21,6 +21,9 @@ export type GgufRangeFetch = (url: string, init: {
21
21
  }>;
22
22
  export declare const GGUF_HEADER_BYTES = 1048576;
23
23
  export declare const GGUF_HEADER_TIMEOUT_MS = 30000;
24
+ export declare const GGUF_HEADER_ATTEMPTS = 3;
25
+ export declare const GGUF_STUB_MAX_BYTES = 33554432;
26
+ export declare const GGUF_STUB_TIMEOUT_MS = 60000;
24
27
  export declare function isRemoteSource(src: string): boolean;
25
28
  export declare function localSourcePath(src: string): string | null;
26
29
  export interface ReadGgufHeaderOptions {
@@ -28,4 +31,6 @@ export interface ReadGgufHeaderOptions {
28
31
  maxBytes?: number;
29
32
  }
30
33
  export declare function readGgufHeaderBytes(src: string, opts?: ReadGgufHeaderOptions): Promise<Uint8Array | null>;
34
+ export declare function fetchGgufStub(src: string, opts?: ReadGgufHeaderOptions): Promise<Uint8Array | null>;
35
+ export declare function ggufDataOffset(bytes: Uint8Array): number | null;
31
36
  export declare function parseGgufHeader(bytes: Uint8Array): GgufHeader | null;