@qvac/harness 0.8.12 → 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 (47) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/dist-lib/index.js +7 -3
  3. package/dist-lib/lib/capabilities/completion.d.ts +5 -1
  4. package/dist-lib/lib/capabilities/completion.js +35 -9
  5. package/dist-lib/lib/connect.js +3 -2
  6. package/dist-lib/lib/contract-types.d.ts +1 -0
  7. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  8. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  9. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  10. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  11. package/dist-lib/lib/models/gguf-header.d.ts +6 -0
  12. package/dist-lib/lib/models/gguf-header.js +38 -1
  13. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  14. package/dist-lib/lib/models/kv-cache.js +8 -0
  15. package/dist-lib/lib/models/llm-presets.d.ts +2 -1
  16. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  17. package/dist-lib/lib/models/model-pool.d.ts +6 -1
  18. package/dist-lib/lib/models/model-pool.js +20 -8
  19. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  20. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  21. package/dist-lib/lib/prompt.d.ts +2 -1
  22. package/dist-lib/lib/prompt.js +12 -12
  23. package/dist-lib/lib/serve.js +3 -2
  24. package/dist-lib/lib/tools/edit-image.js +4 -3
  25. package/dist-lib/lib/tools/exec/adapters/python/attachments.d.ts +1 -0
  26. package/dist-lib/lib/tools/exec/adapters/python/attachments.js +11 -0
  27. package/dist-lib/lib/tools/generate-image.js +4 -3
  28. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  29. package/dist-lib/lib/tools/http-request/request.js +2 -1
  30. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +17 -1
  31. package/dist-lib/lib/tools/http-request/truncate-response.js +51 -9
  32. package/dist-lib/lib/tools/http-request.js +12 -6
  33. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  34. package/dist-lib/lib/tools/office/ops.js +5 -1
  35. package/dist-lib/lib/tools/office.d.ts +1 -0
  36. package/dist-lib/lib/tools/office.js +151 -21
  37. package/dist-lib/lib/tools/operations/compile.js +4 -4
  38. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  39. package/dist-lib/lib/tools/skills/credential-check.js +1 -0
  40. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  41. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  42. package/dist-lib/schema/harness.js +2 -1
  43. package/dist-lib/spec/hrpc/messages.js +8 -5
  44. package/dist-lib/spec/hyperschema/index.js +8 -5
  45. package/dist-lib/spec/hyperschema/schema.json +6 -1
  46. package/dist-lib/spec/hyperschema/types.d.ts +2 -1
  47. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -8,6 +8,84 @@ 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
+
11
89
  ## [0.8.12] - 2026-10-21
12
90
 
13
91
  ### Added
@@ -2136,7 +2214,8 @@ Install 0.2.12 or later to get them.
2136
2214
  - Every dependency installs from the public npm registry: GPU stats are read
2137
2215
  through `bare-gpu-info`. (#12)
2138
2216
 
2139
- [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v0.8.12...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
2140
2219
  [0.8.12]: https://github.com/tetherto/qvac-harness/compare/v0.8.11...v0.8.12
2141
2220
  [0.8.11]: https://github.com/tetherto/qvac-harness/compare/v0.8.10...v0.8.11
2142
2221
  [0.8.10]: https://github.com/tetherto/qvac-harness/compare/v0.8.9...v0.8.10
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';
@@ -721,7 +722,8 @@ export class Harness extends ReadyResource {
721
722
  kvCacheK: this._kvCacheK,
722
723
  kvCacheV: this._kvCacheV,
723
724
  mainGpu: resolveMainGpu,
724
- openclCacheDir
725
+ openclCacheDir,
726
+ cpuPlacement: androidCpuPlacement
725
727
  };
726
728
  }
727
729
  _createPool() {
@@ -731,7 +733,8 @@ export class Harness extends ReadyResource {
731
733
  loads: this._loads,
732
734
  beforeLoad: (load) => this._beforeLoad(load),
733
735
  chooseContext: (load, tier) => this._chooseContext(load, tier),
734
- hold: this._hold
736
+ hold: this._hold,
737
+ modelsDir: this._modelsDir
735
738
  });
736
739
  }
737
740
  _createEmbedPool() {
@@ -1749,7 +1752,7 @@ export class Harness extends ReadyResource {
1749
1752
  };
1750
1753
  this._replying.push(key);
1751
1754
  try {
1752
- const { modelId, ctxSize } = await raceAbort(handle.load(), signal);
1755
+ const { modelId, ctxSize, canThink } = await raceAbort(handle.load(), signal);
1753
1756
  log.info('model ready', { model });
1754
1757
  const sdk = await this._sdk.load();
1755
1758
  const turns = projectionModel ? messages : messages.map(({ attachments, ...turn }) => turn);
@@ -1772,6 +1775,7 @@ export class Harness extends ReadyResource {
1772
1775
  cacheKey,
1773
1776
  session,
1774
1777
  thinkingDefault,
1778
+ canThink,
1775
1779
  generationParams,
1776
1780
  responseFormat,
1777
1781
  captureInferenceCalls,
@@ -18,6 +18,7 @@ export interface Message {
18
18
  role: string;
19
19
  content: string;
20
20
  attachments?: MessageAttachment[];
21
+ sentAt?: number | undefined;
21
22
  [key: string]: unknown;
22
23
  }
23
24
  export interface Agent {
@@ -120,6 +121,7 @@ export type AskUserFn = (question: {
120
121
  export interface RunBudget {
121
122
  readonly deadlineMs: number;
122
123
  outputBytesUsed: number;
124
+ responseRoomChars?: number | undefined;
123
125
  }
124
126
  export interface ToolExecuteContext {
125
127
  agentId?: string | null | undefined;
@@ -189,6 +191,7 @@ export interface ToolDefinition {
189
191
  validate?: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => string | null;
190
192
  effect: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => ToolEffect;
191
193
  stableRead?: true;
194
+ deliversMany?: true;
192
195
  resource?: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => ResourceDescriptor | null;
193
196
  compiled?: true;
194
197
  execute: (args: Record<string, unknown>, ctx?: ToolExecuteContext) => Promise<unknown>;
@@ -315,6 +318,7 @@ interface CompletionArgs {
315
318
  cacheKey?: string;
316
319
  session?: string;
317
320
  thinkingDefault?: string;
321
+ canThink?: boolean | undefined;
318
322
  generationParams?: LlmGenerationParams;
319
323
  responseFormat?: ResponseFormat;
320
324
  messages: Message[];
@@ -340,4 +344,4 @@ export declare function toSdkTool(tool: ToolDefinition): SdkTool;
340
344
  export type CompletionSkillEntry = SkillCatalogEntry & {
341
345
  readonly status?: SkillState;
342
346
  };
343
- 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>;
@@ -18,7 +18,7 @@ import { resolveLlmGenerationParams } from '../models/llm-presets.js';
18
18
  import { toolDialectFor } from '../models/model-catalog.js';
19
19
  import { modelNameToCapabilityProfile } from '../models/model-catalog-constants.js';
20
20
  import { isContextOverflowError, isGrammarOverrunError, isSdkModelWedgedError } from '../models/sdk-faults.js';
21
- import { annotateLastUserTime, skillsPromptSection, systemPromptParts } from '../prompt.js';
21
+ import { annotateUserTimes, skillsPromptSection, systemPromptParts } from '../prompt.js';
22
22
  import { isMetadataMethod } from '../tools/mcp/protocol.js';
23
23
  import { unquoteArg } from '../tools/model-args.js';
24
24
  import { SKILL_TOOL_NAME, WEB_SEARCH_TOOL_NAME } from './tool-names.js';
@@ -33,6 +33,7 @@ import { parseToolGrant } from '../tools/skills/tool-grants.js';
33
33
  import { NETWORK_TOOLSETS, permittedTools } from '../tools/toolsets.js';
34
34
  import { promptPrefixHash } from './prompt-prefix.js';
35
35
  import { logToolPrompt } from './tool-prompt-log.js';
36
+ import { responseRoomChars } from '../tools/http-request/truncate-response.js';
36
37
  import { DIRECT_CALL_ID, deliversFile, FILE_DELIVERED_NUDGE, loadedSkillFilesFrom, loadedSkillsFrom, TOOL_CONTINUATION_NUDGE, toolResultTurn } from './tool-turns.js';
37
38
  export function imageSettingsFrom(agent) {
38
39
  if (!agent)
@@ -426,6 +427,22 @@ function blockedSkillMessage(name, catalog, listShown) {
426
427
  `skill is available this turn — do not guess another name, and answer from what you ` +
427
428
  `already have.`;
428
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
+ }
429
446
  async function resolveToolCalls(toolCalls, { enabled, agentId, pipeline, skillNames, sandboxMode, signal }) {
430
447
  const resolved = [];
431
448
  for (const call of toolCalls) {
@@ -627,7 +644,7 @@ async function* runRecoveredRoundWith(sdk, args, modelId) {
627
644
  try {
628
645
  const result = sdk.completion(params);
629
646
  result.final.catch(noop);
630
- const startInThink = args.generationParams?.reasoning_budget === -1;
647
+ const startInThink = args.generationParams?.reasoning_budget === -1 && args.canThink !== false;
631
648
  for await (const event of runRoundTokens(result, state, {
632
649
  sdk,
633
650
  signal: args.signal,
@@ -718,7 +735,7 @@ function* reportUnnamedWrites(said, landed) {
718
735
  yield { type: 'content', text: unreported };
719
736
  }
720
737
  }
721
- 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 }) {
722
739
  const pipeline = new HookPipeline();
723
740
  const agentId = agent?.id ?? null;
724
741
  const disabledToolsets = agent?.sandboxMode
@@ -907,7 +924,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
907
924
  });
908
925
  }
909
926
  logSelection();
910
- let history = annotateLastUserTime(systemContent ? [{ role: 'system', content: systemContent }, ...messages] : messages);
927
+ let history = annotateUserTimes(systemContent ? [{ role: 'system', content: systemContent }, ...messages] : messages);
911
928
  if (preload && preloadedSkill !== null) {
912
929
  history = directToolHistory(history, { name: SKILL_TOOL_NAME, arguments: { name: preload.name } }, preloadedResult);
913
930
  history.push(...skillToolLoads(preload.name, history));
@@ -1003,12 +1020,14 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1003
1020
  let mute = 0;
1004
1021
  let narrated = false;
1005
1022
  let cappedRounds = 0;
1023
+ let lastToolRound = false;
1006
1024
  let roundsSent = 0;
1007
1025
  let round = 0;
1008
1026
  for (; round < MAX_TOOL_ROUNDS; round++) {
1009
1027
  if (signal?.aborted)
1010
1028
  throw new AbortedError();
1011
1029
  let deliveredThisRound = false;
1030
+ let deliveryEndsRun = false;
1012
1031
  if (Date.now() >= runBudget.deadlineMs) {
1013
1032
  outcome = 'time-capped';
1014
1033
  break;
@@ -1027,6 +1046,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1027
1046
  history,
1028
1047
  tools: sdkTools,
1029
1048
  generationParams,
1049
+ canThink,
1030
1050
  responseFormat,
1031
1051
  toolDialect,
1032
1052
  cacheKey: roundCacheKey,
@@ -1042,6 +1062,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1042
1062
  }
1043
1063
  history = recovered.history;
1044
1064
  collectStats(stats, final.stats, final.stopReason);
1065
+ runBudget.responseRoomChars = responseRoomChars(ctxSize, final.stats?.cacheTokens);
1045
1066
  log.debug('round stats', { round, wallMs: Date.now() - roundStarted, ...final.stats });
1046
1067
  const markup = stripToolResponseBlocks(truncateAtControlToken(final.raw.fullText) || recovered.unproven || '');
1047
1068
  const deferred = sdkTools?.filter((tool) => tool.deferLoading) ?? [];
@@ -1115,7 +1136,8 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1115
1136
  });
1116
1137
  toolCalls = toolCalls.slice(0, MAX_CALLS_PER_ROUND);
1117
1138
  }
1118
- const resolved = await resolveToolCalls(toolCalls, {
1139
+ const named = toolCalls.map((call) => withSkillName(call, skillCatalog));
1140
+ const resolved = await resolveToolCalls(named, {
1119
1141
  enabled,
1120
1142
  agentId: agent?.id ?? null,
1121
1143
  pipeline,
@@ -1324,6 +1346,7 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1324
1346
  }
1325
1347
  if (executionOutcome.kind === 'success' && deliversFile(output)) {
1326
1348
  deliveredThisRound = true;
1349
+ deliveryEndsRun ||= tool?.deliversMany !== true;
1327
1350
  }
1328
1351
  const turn = toolResultTurn(call.name, call.id, output);
1329
1352
  sources.push({
@@ -1351,13 +1374,14 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1351
1374
  role: 'user',
1352
1375
  content: deliveredThisRound ? FILE_DELIVERED_NUDGE : TOOL_CONTINUATION_NUDGE
1353
1376
  });
1354
- if (runOutcomes.facts().delivered) {
1377
+ if (lastToolRound) {
1355
1378
  outcome = 'delivered';
1356
1379
  break;
1357
1380
  }
1358
1381
  if (deliveredThisRound) {
1359
1382
  runOutcomes.confirmDelivery();
1360
1383
  }
1384
+ lastToolRound ||= deliveryEndsRun;
1361
1385
  if (blockedRepeats >= MAX_BLOCKED_REPEATS) {
1362
1386
  break;
1363
1387
  }
@@ -1387,12 +1411,14 @@ export async function* completion(sdk, { modelId, acquireRound, model, agent, ct
1387
1411
  modelId,
1388
1412
  acquireRound,
1389
1413
  history,
1390
- tools: undefined,
1391
- generationParams,
1414
+ tools: sdkTools,
1415
+ generationParams: { ...generationParams, tool_choice: 'none' },
1416
+ canThink,
1417
+ toolDialect,
1392
1418
  cacheKey: roundCacheKey,
1393
1419
  signal,
1394
1420
  round: roundsSent,
1395
- promptPrefix: promptPrefixHash({ system: systemContent, tools: undefined }),
1421
+ promptPrefix,
1396
1422
  capture: captureInferenceCalls
1397
1423
  });
1398
1424
  collectStats(stats, recovered.final.stats, recovered.final.stopReason);
@@ -108,10 +108,11 @@ export class RemoteHarness extends EventEmitter {
108
108
  generationParams: context.generationParams,
109
109
  responseFormat: context.responseFormat,
110
110
  captureInferenceCalls: context.captureInferenceCalls,
111
- messages: context.messages.map(({ role, content, attachments }) => ({
111
+ messages: context.messages.map(({ role, content, attachments, sentAt }) => ({
112
112
  role,
113
113
  content,
114
- attachments: attachments?.map(({ path: file }) => ({ path: file }))
114
+ attachments: attachments?.map(({ path: file }) => ({ path: file })),
115
+ sentAt
115
116
  })),
116
117
  payload: { typedText: context.typedText },
117
118
  toolConfigs: context.toolConfigs,
@@ -21,6 +21,7 @@ export interface ChatMessage {
21
21
  attachments?: {
22
22
  path: string;
23
23
  }[] | null;
24
+ sentAt?: number | undefined;
24
25
  }
25
26
  export interface AgentKnobs {
26
27
  id?: string;
@@ -0,0 +1,8 @@
1
+ export interface CpuPlacement {
2
+ threads: number;
3
+ mask: string;
4
+ }
5
+ export type ReadSysFile = (path: string) => string | null;
6
+ export declare function parseCpuList(list: string): number[];
7
+ export declare function performanceCorePlacement(read?: ReadSysFile, hostPlatform?: string): CpuPlacement | undefined;
8
+ export declare function androidCpuPlacement(): CpuPlacement | undefined;
@@ -0,0 +1,48 @@
1
+ import fs from 'fs';
2
+ import { platform } from 'os';
3
+ const CPU_ROOT = '/sys/devices/system/cpu';
4
+ function readSysFile(path) {
5
+ try {
6
+ return String(fs.readFileSync(path, 'utf8'));
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
12
+ function cpuRange(part) {
13
+ const [from, to = from] = part.split('-').map(Number);
14
+ if (!Number.isInteger(from) || !Number.isInteger(to) || to < from) {
15
+ return null;
16
+ }
17
+ return Array.from({ length: to - from + 1 }, (_, i) => from + i);
18
+ }
19
+ export function parseCpuList(list) {
20
+ const ranges = list.trim().split(',').map(cpuRange);
21
+ return ranges.some((range) => range === null) ? [] : ranges.flat().filter((cpu) => cpu !== null);
22
+ }
23
+ function readCores(read, possible) {
24
+ return parseCpuList(possible).flatMap((cpu) => {
25
+ const maxFreq = Number(read(`${CPU_ROOT}/cpu${cpu}/cpufreq/cpuinfo_max_freq`)?.trim());
26
+ return Number.isFinite(maxFreq) && maxFreq > 0 ? [{ cpu, maxFreq }] : [];
27
+ });
28
+ }
29
+ function placementOf(cores) {
30
+ const slowest = Math.min(...cores.map((core) => core.maxFreq));
31
+ const fast = cores.filter((core) => core.maxFreq > slowest);
32
+ if (fast.length === 0) {
33
+ return undefined;
34
+ }
35
+ const mask = fast.reduce((bits, core) => bits | (1n << BigInt(core.cpu)), 0n);
36
+ return { threads: fast.length, mask: mask.toString(16) };
37
+ }
38
+ export function performanceCorePlacement(read = readSysFile, hostPlatform = platform()) {
39
+ if (hostPlatform !== 'android')
40
+ return undefined;
41
+ const possible = read(`${CPU_ROOT}/possible`);
42
+ return possible === null ? undefined : placementOf(readCores(read, possible));
43
+ }
44
+ let cached = null;
45
+ export function androidCpuPlacement() {
46
+ cached ??= { placement: performanceCorePlacement() };
47
+ return cached.placement;
48
+ }
@@ -9,5 +9,6 @@ export interface CustomShardCache {
9
9
  readonly files: ReadonlyArray<string>;
10
10
  }
11
11
  export declare function customShardCache(src: string, modelsDir: string | undefined): CustomShardCache | null;
12
+ export declare function localWeightFile(src: string, modelsDir: string | undefined): string | null;
12
13
  export declare function customDownloads(entry: CustomModelEntry, modelsDir: string | undefined): Promise<CustomDownloads>;
13
14
  export declare function isCustomModelCached(entry: CustomModelEntry, modelsDir: string | undefined): Promise<boolean>;
@@ -22,6 +22,9 @@ export function customShardCache(src, modelsDir) {
22
22
  const dir = path.join(modelsDir, 'sharded', shortHash(`${set.baseUrl}/${set.base}`));
23
23
  return { dir, files: set.shards.map((shard) => path.join(dir, shard.filename)) };
24
24
  }
25
+ export function localWeightFile(src, modelsDir) {
26
+ return customShardCache(src, modelsDir)?.files[0] ?? customFileCachePath(src, modelsDir);
27
+ }
25
28
  export async function customDownloads(entry, modelsDir) {
26
29
  const remote = sourcesOf(entry).filter(isRemoteSource);
27
30
  const shardDirs = remote.flatMap((src) => customShardCache(src, modelsDir)?.dir ?? []);
@@ -7,6 +7,12 @@ export interface GgufHeader {
7
7
  readonly contextLength?: number;
8
8
  readonly sizeLabel?: string;
9
9
  readonly tags?: ReadonlyArray<string>;
10
+ readonly headDims?: HeadDims;
11
+ readonly chatTemplate?: string;
12
+ }
13
+ export interface HeadDims {
14
+ readonly k?: number;
15
+ readonly v?: number;
10
16
  }
11
17
  export type GgufRangeFetch = (url: string, init: {
12
18
  headers: Record<string, string>;
@@ -262,6 +262,7 @@ export function parseGgufHeader(bytes) {
262
262
  const count = readU64(c);
263
263
  const header = {};
264
264
  const contextLengths = new Map();
265
+ const dims = new Map();
265
266
  for (let i = 0; i < count; i += 1) {
266
267
  const key = readString(c);
267
268
  if (key === null || !has(c, 4)) {
@@ -289,15 +290,40 @@ export function parseGgufHeader(bytes) {
289
290
  else if (key === 'general.tags') {
290
291
  header.tags = value.strs;
291
292
  }
293
+ else if (key === 'tokenizer.chat_template') {
294
+ header.chatTemplate = value.str;
295
+ }
292
296
  else if (key.endsWith('.context_length')) {
293
297
  contextLengths.set(key, value.num);
294
298
  }
299
+ else if (HEAD_KEYS.some((suffix) => key.endsWith(suffix))) {
300
+ dims.set(key, value.num);
301
+ }
295
302
  }
296
303
  header.contextLength =
297
304
  contextLengths.get(`${header.architecture}.context_length`) ??
298
305
  contextLengths.values().next().value;
306
+ const headDims = headDimsOf(dims, header.architecture);
307
+ if (headDims) {
308
+ header.headDims = headDims;
309
+ }
299
310
  return header;
300
311
  }
312
+ const HEAD_KEYS = [
313
+ '.attention.key_length',
314
+ '.attention.value_length',
315
+ '.attention.head_count',
316
+ '.embedding_length'
317
+ ];
318
+ function headDimsOf(dims, architecture) {
319
+ const of = (suffix) => dims.get(`${architecture}${suffix}`);
320
+ const embedding = of('.embedding_length');
321
+ const heads = of('.attention.head_count');
322
+ const split = embedding && heads ? embedding / heads : undefined;
323
+ const k = of('.attention.key_length') ?? split;
324
+ const v = of('.attention.value_length') ?? split;
325
+ return k || v ? { k, v } : undefined;
326
+ }
301
327
  function readValue(c, type, collect = false) {
302
328
  switch (type) {
303
329
  case UINT8:
@@ -332,7 +358,7 @@ function readValue(c, type, collect = false) {
332
358
  const length = readU64(c);
333
359
  const strs = new Array();
334
360
  for (let i = 0; i < length; i += 1) {
335
- const element = readValue(c, elementType);
361
+ const element = elementType === STRING && !collect ? skipString(c) : readValue(c, elementType);
336
362
  if (!element.ok) {
337
363
  return { ok: false };
338
364
  }
@@ -379,3 +405,14 @@ function readString(c) {
379
405
  c.offset += length;
380
406
  return str;
381
407
  }
408
+ function skipString(c) {
409
+ if (!has(c, 8)) {
410
+ return { ok: false };
411
+ }
412
+ const length = readU64(c);
413
+ if (!has(c, length)) {
414
+ return { ok: false };
415
+ }
416
+ c.offset += length;
417
+ return { ok: true };
418
+ }
@@ -1,5 +1,7 @@
1
+ import type { HeadDims } from './gguf-header.ts';
1
2
  export interface KvCacheTypes {
2
3
  k: string | undefined;
3
4
  v: string | undefined;
4
5
  }
6
+ export declare function headSafeKvCache({ k, v }: KvCacheTypes, heads: HeadDims | undefined): KvCacheTypes;
5
7
  export declare function adrenoSafeKvCache(device: 'cpu' | 'gpu' | undefined, { k, v }: KvCacheTypes, hostPlatform?: string): KvCacheTypes;
@@ -1,4 +1,12 @@
1
1
  import { platform } from 'os';
2
+ const QUANT_BLOCK = 32;
3
+ const UNBLOCKED = new Set(['f32', 'f16', 'bf16']);
4
+ export function headSafeKvCache({ k, v }, heads) {
5
+ return { k: blockFits(k, heads?.k) ? k : 'f16', v: blockFits(v, heads?.v) ? v : 'f16' };
6
+ }
7
+ function blockFits(type, width) {
8
+ return !type || !width || UNBLOCKED.has(type) || width % QUANT_BLOCK === 0;
9
+ }
2
10
  export function adrenoSafeKvCache(device, { k, v }, hostPlatform = platform()) {
3
11
  if (device === 'cpu' || hostPlatform !== 'android') {
4
12
  return { k, v };
@@ -5,6 +5,7 @@ export interface LlmGenerationParams {
5
5
  presence_penalty?: number;
6
6
  repeat_penalty?: number;
7
7
  frequency_penalty?: number;
8
- reasoning_budget: -1 | 0;
8
+ reasoning_budget?: -1 | 0;
9
+ tool_choice?: 'none';
9
10
  }
10
11
  export declare function resolveLlmGenerationParams(modelName: string | undefined, reasoningEnabled: boolean | undefined, deviceDefault?: boolean): LlmGenerationParams | undefined;
@@ -4,6 +4,7 @@ export interface ModelResource {
4
4
  modelId: string;
5
5
  ctxSize?: number;
6
6
  bytes?: number;
7
+ canThink?: boolean | undefined;
7
8
  }
8
9
  export interface ModelHandleOptions {
9
10
  load(signal: AbortSignal): Promise<ModelResource>;
@@ -1,6 +1,7 @@
1
1
  import ResourcePuddle from 'resource-puddle';
2
2
  import { ModelHandle } from './model-handle.ts';
3
3
  import { type ModelSrc } from './context.ts';
4
+ import type { CpuPlacement } from '../hardware/cpu-placement.ts';
4
5
  import { type ModelAddon } from './model-source.ts';
5
6
  import type { GpuFaultState } from './sdk-faults.ts';
6
7
  import type { HoldFn } from './download-gate.ts';
@@ -34,6 +35,7 @@ export interface LlmDeviceConfig {
34
35
  kvCacheV?: string;
35
36
  mainGpu?: () => Promise<string | undefined>;
36
37
  openclCacheDir?: () => string | undefined;
38
+ cpuPlacement?: () => CpuPlacement | undefined;
37
39
  }
38
40
  export type TrackedLoad = Promise<string> & {
39
41
  requestId?: string;
@@ -66,6 +68,8 @@ export type ModelLifecycleSdk = Pick<SdkModule, 'unloadModel' | 'modelRegistrySe
66
68
  gpu_layers?: number;
67
69
  'main-gpu'?: string;
68
70
  openclCacheDir?: string;
71
+ threads?: number;
72
+ 'cpu-mask'?: string;
69
73
  };
70
74
  onProgress?: (progress: Record<string, unknown>) => void;
71
75
  }): TrackedLoad;
@@ -160,8 +164,9 @@ export interface ModelPoolOptions {
160
164
  beforeLoad?: BeforeLoad;
161
165
  chooseContext?: ChooseContext;
162
166
  hold?: HoldFn;
167
+ modelsDir?: string | undefined;
163
168
  }
164
- export declare function createModelPool(loadSdk: LoadSdk, notify: NotifyFn, { deviceConfig, loads, beforeLoad, chooseContext, hold }?: ModelPoolOptions): ModelPuddle;
169
+ export declare function createModelPool(loadSdk: LoadSdk, notify: NotifyFn, { deviceConfig, loads, beforeLoad, chooseContext, hold, modelsDir }?: ModelPoolOptions): ModelPuddle;
165
170
  export interface EmbedPoolOptions {
166
171
  faults: GpuFaultState;
167
172
  batchSize?: number;