@qvac/harness 1.1.0 → 1.2.0

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
@@ -12,6 +12,39 @@ API had in that release; a breaking change shows the call before and after.
12
12
 
13
13
  ## [Unreleased]
14
14
 
15
+ ## [1.2.0] - 2026-11-20
16
+
17
+ ### Added
18
+
19
+ - `Agent.readParts` reads parts side by side when given a `limiter` (`Agent.limiter(width)`), which
20
+ several reads can share, and reports each note as it lands through `onNote`. Notes still come back
21
+ in reading order. Calls named as one group with `parallel: { group, slots, ctxSize? }` share one
22
+ load of the model with slots when that fits, else the agent's own load. See
23
+ [Read a long document part by part](README.md#read-a-long-document-part-by-part). (#945)
24
+
25
+ ```ts
26
+ await Agent.readParts(
27
+ harness,
28
+ { model, agent, parallel: { group: 'book', slots: 4 } },
29
+ { read: 'book', title: 'book.pdf', parts, noteTokens: 640, limiter: Agent.limiter(4) }
30
+ )
31
+ ```
32
+
33
+ ### Changed
34
+
35
+ - With `slots` above 1, a fit that cannot answer loads 1 slot: a machine with no GPU, a CPU
36
+ device, or a fit that timed out. It used to load every slot unchecked. (#946)
37
+
38
+ ### Fixed
39
+
40
+ - `exec` refuses a `curl` or `wget` fetch of a public `http(s)://` URL when `http_request` is offered
41
+ in the round, so the model retries with `http_request` instead of stopping at an approval card.
42
+ Private hosts and downloads to disk still run through `exec`. (#943)
43
+ - With `slots` above 1, a model that only fit by moving layers to the CPU loaded partly on the CPU
44
+ at the full slot count, so a 27B on a 20 GB card ran at about 1 token/s. The slot count now
45
+ halves until every layer stays on the GPU, an agent's own context included, and the context
46
+ steps down only at 1 slot. A context climb never moves layers to the CPU either. (#946)
47
+
15
48
  ## [1.1.0] - 2026-11-18
16
49
 
17
50
  ### Added
@@ -4067,7 +4100,8 @@ Install 0.2.12 or later to get them.
4067
4100
  - Every dependency installs from the public npm registry: GPU stats are read
4068
4101
  through `bare-gpu-info`. (#12)
4069
4102
 
4070
- [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v1.1.0...HEAD
4103
+ [Unreleased]: https://github.com/tetherto/qvac-harness/compare/v1.2.0...HEAD
4104
+ [1.2.0]: https://github.com/tetherto/qvac-harness/compare/v1.1.0...v1.2.0
4071
4105
  [1.1.0]: https://github.com/tetherto/qvac-harness/compare/v1.0.1...v1.1.0
4072
4106
  [1.0.1]: https://github.com/tetherto/qvac-harness/compare/v1.0.0...v1.0.1
4073
4107
  [1.0.0]: https://github.com/tetherto/qvac-harness/compare/v0.8.12...v1.0.0
package/README.md CHANGED
@@ -194,6 +194,17 @@ const whole = notes.length === 2 && notes.every((note) => note.status === 'answe
194
194
  const context = whole ? Agent.notesContext([{ title: 'book.pdf', notes }]) : undefined
195
195
  ```
196
196
 
197
+ Pass a `limiter` to read parts side by side, and name the calls as one group with `parallel` so the
198
+ model is loaded with slots for them when that fits:
199
+
200
+ ```ts
201
+ await Agent.readParts(
202
+ harness,
203
+ { model, agent, parallel: { group: 'book', slots: 4 } },
204
+ { read: 'book', title: 'book.pdf', parts, noteTokens: 640, limiter: Agent.limiter(4) }
205
+ )
206
+ ```
207
+
197
208
  The read stops at the first part that does not answer, so fewer notes than parts means the document
198
209
  was not read whole: frame the notes only when every part answered. `read` names the read under the
199
210
  parent run, so two reads of one run never share a child run id.
@@ -27,3 +27,7 @@ export interface ChildResult {
27
27
  }
28
28
  export declare function childRun<Request extends ChildRequest>(base: Request, { parent, id, prompt }: ChildRun): Request;
29
29
  export declare function collect<Request, Event extends FollowEvent>(host: FollowHost<Request, Event>, request: Request): Promise<ChildResult>;
30
+ export interface Limiter {
31
+ run<T>(task: () => Promise<T>): Promise<T>;
32
+ }
33
+ export declare function limiter(width: number): Limiter;
@@ -30,3 +30,29 @@ export async function collect(host, request) {
30
30
  }
31
31
  return { status, text };
32
32
  }
33
+ export function limiter(width) {
34
+ const waiting = [];
35
+ let free = Math.max(1, Math.floor(width));
36
+ return {
37
+ async run(task) {
38
+ if (free > 0) {
39
+ free--;
40
+ }
41
+ else {
42
+ await new Promise((resolve) => waiting.push(resolve));
43
+ }
44
+ try {
45
+ return await task();
46
+ }
47
+ finally {
48
+ const next = waiting.shift();
49
+ if (next) {
50
+ next();
51
+ }
52
+ else {
53
+ free++;
54
+ }
55
+ }
56
+ }
57
+ };
58
+ }
@@ -1,6 +1,7 @@
1
1
  import type { AgentConfig, AgentPolicy, AgentPorts, AgentRequest, AgentSkill, ResolvedAgent } from '../contract/index.ts';
2
2
  import { createDelegateTool } from './delegate.ts';
3
3
  import { follow, untransferred } from './follow.ts';
4
+ import { limiter } from './child-run.ts';
4
5
  import { notesContext, readParts } from './read-parts.ts';
5
6
  import { agentPolicy, resolveAgent } from './resolve.ts';
6
7
  import { planFromMessages, planSteps } from './plan.ts';
@@ -25,6 +26,7 @@ export declare class Agent<Skill extends AgentSkill = AgentSkill> {
25
26
  static follow: typeof follow;
26
27
  static delegateTool: typeof createDelegateTool;
27
28
  static readParts: typeof readParts;
29
+ static limiter: typeof limiter;
28
30
  static notesContext: typeof notesContext;
29
31
  static untransferred: typeof untransferred;
30
32
  static planSteps: typeof planSteps;
@@ -36,6 +38,7 @@ export declare class Agent<Skill extends AgentSkill = AgentSkill> {
36
38
  policy(): AgentPolicy;
37
39
  }
38
40
  export type { DelegateOptions, DelegateRequest, DelegateResult, DelegateTarget, ExternalResult, ExternalRun, LocalResult, TargetAccess, TargetEvent, TargetResult, TargetTask, TargetUsage } from './delegate.ts';
41
+ export type { Limiter } from './child-run.ts';
39
42
  export type { FollowAgent, FollowEvent, FollowHost, FollowRequest } from './follow.ts';
40
43
  export type { DocumentNotes, DocumentPart, PartNote, PartProgress, ReadPartsOptions, ReadPartsRequest } from './read-parts.ts';
41
44
  export type { TransferResult } from './transfer.ts';
@@ -1,5 +1,6 @@
1
1
  import { createDelegateTool, DELEGATE_TOOL_NAME } from './delegate.js';
2
2
  import { follow, MAX_TRANSFERS, untransferred } from './follow.js';
3
+ import { limiter } from './child-run.js';
3
4
  import { notesContext, readParts } from './read-parts.js';
4
5
  import { agentPolicy, resolveAgent } from './resolve.js';
5
6
  import { MAX_PLAN_STEPS, PLAN_TOOL_NAME, planFromMessages, planSteps } from './plan.js';
@@ -26,6 +27,7 @@ export class Agent {
26
27
  static follow = follow;
27
28
  static delegateTool = createDelegateTool;
28
29
  static readParts = readParts;
30
+ static limiter = limiter;
29
31
  static notesContext = notesContext;
30
32
  static untransferred = untransferred;
31
33
  static planSteps = planSteps;
@@ -1,4 +1,4 @@
1
- import type { ChildRequest, ChildResult } from './child-run.ts';
1
+ import type { ChildRequest, ChildResult, Limiter } from './child-run.ts';
2
2
  import type { FollowEvent, FollowHost } from './follow.ts';
3
3
  export interface ReadPartsRequest extends ChildRequest {
4
4
  signal?: {
@@ -26,6 +26,8 @@ export interface ReadPartsOptions {
26
26
  parts: ReadonlyArray<DocumentPart>;
27
27
  noteTokens: number;
28
28
  onPart?: (progress: PartProgress) => void;
29
+ onNote?: (progress: PartProgress) => void;
30
+ limiter?: Limiter;
29
31
  }
30
32
  export interface PartProgress {
31
33
  part: number;
@@ -41,5 +43,5 @@ export interface DocumentNotes {
41
43
  span?: string;
42
44
  }>;
43
45
  }
44
- export declare function readParts<Request extends ReadPartsRequest, Event extends FollowEvent>(host: FollowHost<Request, Event>, base: Request, { read: id, title, parts, noteTokens, onPart }: ReadPartsOptions): Promise<PartNote[]>;
46
+ export declare function readParts<Request extends ReadPartsRequest, Event extends FollowEvent>(host: FollowHost<Request, Event>, base: Request, { parts, limiter: lane, ...options }: ReadPartsOptions): Promise<PartNote[]>;
45
47
  export declare function notesContext(documents: ReadonlyArray<DocumentNotes>): string;
@@ -1,21 +1,46 @@
1
- import { childRun, collect } from './child-run.js';
1
+ import { childRun, collect, limiter } from './child-run.js';
2
2
  const WORDS_PER_TOKEN = 0.55;
3
- export async function readParts(host, base, { read: id, title, parts, noteTokens, onPart }) {
4
- const notes = [];
5
- for (const [index, part] of parts.entries()) {
6
- if (base.signal?.aborted) {
7
- notes.push({ status: 'aborted', text: '' });
3
+ export async function readParts(host, base, { parts, limiter: lane = limiter(1), ...options }) {
4
+ const reading = { notes: parts.map(() => undefined), stopped: false };
5
+ const count = parts.length;
6
+ await Promise.all(parts.map((part, index) => lane.run(async () => {
7
+ if (reading.stopped) {
8
+ return;
9
+ }
10
+ const note = await readPart(host, base, { ...options, part, index, count }).catch((err) => {
11
+ reading.stopped = true;
12
+ throw err;
13
+ });
14
+ reading.notes[index] = note;
15
+ reading.stopped ||= note.status !== 'answered';
16
+ })));
17
+ return answeredRun(reading.notes);
18
+ }
19
+ async function readPart(host, base, { read: id, title, noteTokens, onPart, onNote, part, index, count }) {
20
+ if (base.signal?.aborted) {
21
+ return { status: 'aborted', text: '' };
22
+ }
23
+ const place = { part: index + 1, parts: count };
24
+ onPart?.(place);
25
+ const prompt = notesPrompt({ title, part, index, count, noteTokens });
26
+ const note = await collect(host, child(base, { prompt, id, index, noteTokens }));
27
+ if (note.status === 'answered') {
28
+ onNote?.(place);
29
+ }
30
+ return { status: note.status, text: note.text.trim(), span: part.span };
31
+ }
32
+ function answeredRun(notes) {
33
+ const run = [];
34
+ for (const note of notes) {
35
+ if (!note) {
8
36
  break;
9
37
  }
10
- onPart?.({ part: index + 1, parts: parts.length });
11
- const prompt = notesPrompt({ title, part, index, count: parts.length, noteTokens });
12
- const note = await collect(host, child(base, { prompt, id, index, noteTokens }));
13
- notes.push({ status: note.status, text: note.text.trim(), span: part.span });
38
+ run.push(note);
14
39
  if (note.status !== 'answered') {
15
40
  break;
16
41
  }
17
42
  }
18
- return notes;
43
+ return run;
19
44
  }
20
45
  export function notesContext(documents) {
21
46
  const names = documents.map((document) => `"${document.title}"`).join(', ');
@@ -2,13 +2,16 @@ import type { CompletionFinal, Tool as SdkTool, ToolDialect } from '@qvac/infere
2
2
  import { type AbortSignal as BareAbortSignal } from 'bare-abort-controller';
3
3
  import type { TextEvent } from '../../helpers/thinking.ts';
4
4
  import type { AgentConfig, CompletionSdk, LlmGenerationParams, Message, ResponseFormat, RoundModelLease, RunLifecycleEvent } from '../../contract/index.ts';
5
+ import type { ParallelLoad } from '../../contract/models.ts';
5
6
  export interface ModelRoundRequest {
6
7
  runId: string;
7
8
  round: number;
8
9
  kind: 'streaming' | 'wrap-up';
9
10
  attempt: number;
10
11
  modelId: string;
11
- load?: Pick<AgentConfig, 'ctxSize' | 'kvCacheK' | 'kvCacheV'> | undefined;
12
+ load?: (Pick<AgentConfig, 'ctxSize' | 'kvCacheK' | 'kvCacheV'> & {
13
+ parallel?: ParallelLoad | undefined;
14
+ }) | undefined;
12
15
  history: Message[];
13
16
  tools?: SdkTool[] | undefined;
14
17
  toolSet?: string | undefined;
@@ -26,6 +26,11 @@ export interface RoomHold {
26
26
  srcs: ReadonlyArray<string>;
27
27
  unloadIdle(): Promise<void>;
28
28
  }
29
+ export interface ParallelLoad {
30
+ group: string;
31
+ slots: number;
32
+ ctxSize?: number | undefined;
33
+ }
29
34
  export interface BorrowedModel {
30
35
  modelId: string;
31
36
  release(): void;
@@ -11,6 +11,7 @@ import { type ModelSourcePreview, type PreviewModelSourceContext } from './capab
11
11
  import type { CapabilityInfo, CredentialEntry, DownloadsAllowedOptions, HarnessDiagnostics, HarnessInfo, InfraModel, LoadModelResult, MemoryUsage, SkillWriteResult, UnloadModelContext, UnloadModelResult } from './contract-types.ts';
12
12
  import type { AccessPolicy, AgentConfig, ApproveFn, AskUserFn, AttachFn, CompletionEvent, FetchAttachmentFn, HarnessHook, MediaRoundIo, MediaRoundPort, MediaRoundRequest, MediaRoundResult, Message, ProgressFn, ProjectSkill, ResponseFormat, RunGoal, RunInput, ShowImageFn, ToolDefinition, ToolExecuteContext, WorkspaceSkill } from './contract/index.ts';
13
13
  import type { KnowledgeArtifact, KnowledgeGrant, KnowledgeHit, KnowledgeQuery, KnowledgeRemoved, KnowledgeStatus, KnowledgeUpsertResult } from './contract/knowledge.ts';
14
+ import type { ParallelLoad } from './contract/models.ts';
14
15
  import type { OcrPage, OcrReadContext } from './contract/ocr.ts';
15
16
  import type { SpeakContext, SpeakResult, SpeakStreamContext, TranscribeContext } from './contract/speech.ts';
16
17
  import { RunLatency } from './helpers/run-latency.ts';
@@ -36,6 +37,7 @@ export type HarnessExecOptions = Pick<ExecToolOptions, 'spawn' | 'killProcess' |
36
37
  export interface CompletionContext {
37
38
  runId?: string;
38
39
  parentRunId?: string;
40
+ parallel?: ParallelLoad;
39
41
  tools?: ToolDefinition[];
40
42
  policy?: AccessPolicy;
41
43
  now?: () => number;
@@ -915,7 +915,7 @@ export class Harness extends ReadyResource {
915
915
  throw new Error(UNLOAD_FAILED);
916
916
  }
917
917
  const { modelId } = request;
918
- const { key, acquireRound: acquire } = this._residency.servedRound(modelId, request.load);
918
+ const { key, acquireRound: acquire } = await this._residency.servedRound(modelId, request.load);
919
919
  const acquireRound = this._seeding(acquire, modelId);
920
920
  let served;
921
921
  const round = this._lifecycle.trackCompletion((signal) => this._residency.busyStream(async function* () {
@@ -19,12 +19,18 @@ export interface FitQuery {
19
19
  registrySource?: string;
20
20
  modelType?: FitModelType;
21
21
  contextTokens: number;
22
+ slots?: number;
23
+ kvCacheK?: string;
24
+ kvCacheV?: string;
25
+ device?: 'cpu' | 'gpu';
26
+ gpuLayers?: number;
22
27
  onDisk?: boolean;
23
28
  }
24
29
  export interface FitAssessment {
25
30
  verdict: ModelFitVerdict;
26
31
  bytes: number | undefined;
27
32
  pools: PoolBytes;
33
+ free?: PoolBytes;
28
34
  reasons: string[];
29
35
  }
30
36
  export interface FitAsset {
@@ -39,16 +45,27 @@ export interface ContextChoice {
39
45
  slots: number;
40
46
  fits: boolean;
41
47
  }
42
- export interface FitQueryOptions {
48
+ export interface FitLoad {
49
+ readonly slots?: number;
50
+ readonly kvCacheK?: string;
51
+ readonly kvCacheV?: string;
52
+ readonly device?: 'cpu' | 'gpu';
53
+ readonly gpuLayers?: number;
54
+ }
55
+ export interface FitQueryOptions extends FitLoad {
43
56
  readonly native?: boolean;
44
57
  readonly modelType?: FitModelType;
45
58
  }
59
+ export interface LadderOptions extends FitLoad {
60
+ readonly rungs?: boolean;
61
+ }
46
62
  export type AssessModelFit = (input: AssessModelFitInput) => Promise<AssessModelFitResult>;
47
63
  export type LocateWeight = (query: FitQuery) => Promise<string | undefined>;
48
64
  export interface DownloadedWeightSdk {
49
65
  getModelInfo: typeof getModelInfo;
50
66
  }
51
67
  export declare class ModelFit {
68
+ static readonly ALL_LAYERS = 999;
52
69
  private readonly _assess;
53
70
  private readonly _locate;
54
71
  private readonly _chosen;
@@ -62,7 +79,7 @@ export declare class ModelFit {
62
79
  constructor(assess: AssessModelFit, locate?: LocateWeight);
63
80
  static need(label: string, usedBytes: number, freeBytes: number | undefined): string;
64
81
  static downloaded(sdk: DownloadedWeightSdk, name: string, sha256Checksum: string): Promise<string | undefined>;
65
- static query(asset: FitAsset, contextTokens: number, { native, modelType }?: FitQueryOptions): FitQuery;
82
+ static query(asset: FitAsset, contextTokens: number, { native, ...load }?: FitQueryOptions): FitQuery;
66
83
  static confirms(assessed: FitAssessment | null): boolean;
67
84
  static judge(model: SdkModelFit | undefined): FitAssessment;
68
85
  observe(pools: ReadonlyArray<SdkPool>): void;
@@ -75,7 +92,7 @@ export declare class ModelFit {
75
92
  chosen(key: string): number | undefined;
76
93
  chosenSlots(key: string): number | undefined;
77
94
  keep(key: string, { ctxSize, slots }: ContextChoice): void;
78
- ladder(asset: FitAsset, tier: number, slots?: number): Promise<ContextChoice>;
95
+ ladder(asset: FitAsset, tier: number, { slots, rungs, gpuLayers, ...load }?: LadderOptions): Promise<ContextChoice>;
79
96
  private _steps;
80
97
  private _ask;
81
98
  private _files;
@@ -8,6 +8,7 @@ const VERDICTS = {
8
8
  };
9
9
  const CONTEXT_RUNGS = [32_768, 16_384, 8_192];
10
10
  export class ModelFit {
11
+ static ALL_LAYERS = 999;
11
12
  _assess;
12
13
  _locate;
13
14
  _chosen = new Map();
@@ -34,11 +35,10 @@ export class ModelFit {
34
35
  }
35
36
  return files.find((file) => file.sha256Checksum === sha256Checksum)?.path;
36
37
  }
37
- static query(asset, contextTokens, { native = false, modelType } = {}) {
38
+ static query(asset, contextTokens, { native = false, ...load } = {}) {
38
39
  const { src, sha256Checksum, name, registryPath, registrySource } = asset;
39
- return native
40
- ? { src, sha256Checksum, name, registryPath, registrySource, modelType, contextTokens }
41
- : { src, sha256Checksum, name, modelType, contextTokens };
40
+ const query = { src, sha256Checksum, name, contextTokens, ...load };
41
+ return native ? { ...query, registryPath, registrySource } : query;
42
42
  }
43
43
  static confirms(assessed) {
44
44
  return assessed?.verdict === 'likely-fits';
@@ -49,14 +49,19 @@ export class ModelFit {
49
49
  }
50
50
  const { status, devices } = model;
51
51
  const pools = {};
52
- for (const { id, unified, usedBytes } of devices) {
52
+ const free = {};
53
+ for (const { id, unified, usedBytes, freeBytes } of devices) {
53
54
  const pool = unified ? HOST_POOL : id;
54
55
  pools[pool] = (pools[pool] ?? 0) + usedBytes;
56
+ if (freeBytes !== undefined) {
57
+ free[pool] = Math.min(free[pool] ?? freeBytes, freeBytes);
58
+ }
55
59
  }
56
60
  return {
57
61
  verdict: VERDICTS[status],
58
62
  bytes: devices.length ? totalBytes(pools) : undefined,
59
63
  pools,
64
+ free,
60
65
  reasons: devices.map(deviceReason)
61
66
  };
62
67
  }
@@ -110,28 +115,35 @@ export class ModelFit {
110
115
  this._chosen.set(key, { ctxSize, slots });
111
116
  }
112
117
  }
113
- async ladder(asset, tier, slots = 1) {
114
- const choice = await this._steps(asset, tier, { slots, native: true });
115
- if (choice.fits || slots === 1) {
116
- return choice;
118
+ async ladder(asset, tier, { slots = 1, rungs = true, gpuLayers, ...load } = {}) {
119
+ for (let count = slots; count > 1; count = Math.ceil(count / 2)) {
120
+ const query = ModelFit.query(asset, tier * count, {
121
+ ...load,
122
+ native: true,
123
+ slots: count,
124
+ gpuLayers: gpuLayers ?? ModelFit.ALL_LAYERS
125
+ });
126
+ if (ModelFit.confirms(await this.settle(query))) {
127
+ return { ctxSize: tier, slots: count, fits: true };
128
+ }
117
129
  }
118
- return this._steps(asset, tier, { slots: 1, native: false });
130
+ return this._steps(asset, tier, { ...load, gpuLayers, rungs, native: slots === 1 });
119
131
  }
120
- async _steps(asset, tier, { slots, native }) {
121
- const top = await this.settle(ModelFit.query(asset, tier * slots, { native }));
132
+ async _steps(asset, tier, { native, rungs, ...load }) {
133
+ const top = await this.settle(ModelFit.query(asset, tier, { ...load, native }));
122
134
  if (top?.verdict !== 'likely-too-large') {
123
- return { ctxSize: tier, slots, fits: true };
135
+ return { ctxSize: tier, slots: 1, fits: true };
124
136
  }
125
- for (const rung of CONTEXT_RUNGS.filter((size) => size < tier)) {
126
- const assessed = await this.settle(ModelFit.query(asset, rung * slots));
137
+ for (const rung of rungs ? CONTEXT_RUNGS.filter((size) => size < tier) : []) {
138
+ const assessed = await this.settle(ModelFit.query(asset, rung, load));
127
139
  if (ModelFit.confirms(assessed)) {
128
- return { ctxSize: rung, slots, fits: true };
140
+ return { ctxSize: rung, slots: 1, fits: true };
129
141
  }
130
142
  if (assessed?.verdict !== 'likely-too-large') {
131
143
  break;
132
144
  }
133
145
  }
134
- return { ctxSize: tier, slots, fits: false };
146
+ return { ctxSize: tier, slots: 1, fits: false };
135
147
  }
136
148
  async _ask(queries) {
137
149
  return this._fit(queries, await this._files(queries));
@@ -189,10 +201,17 @@ export class ModelFit {
189
201
  }
190
202
  async _fit(queries, files) {
191
203
  const result = await this._assess({
192
- models: queries.map(({ contextTokens, modelType = 'llm', sha256Checksum, onDisk, ...source }, i) => ({
204
+ models: queries.map(({ contextTokens, slots = 1, kvCacheK, kvCacheV, device, gpuLayers, modelType = 'llm', sha256Checksum, onDisk, ...source }, i) => ({
193
205
  modelSrc: files[i] ?? (sha256Checksum ? { ...source, sha256Checksum } : source.src),
194
206
  modelType,
195
- modelConfig: { ctx_size: contextTokens }
207
+ modelConfig: defined({
208
+ ctx_size: contextTokens,
209
+ parallel: slots > 1 ? slots : undefined,
210
+ 'cache-type-k': kvCacheK,
211
+ 'cache-type-v': kvCacheV,
212
+ device,
213
+ gpu_layers: gpuLayers
214
+ })
196
215
  }))
197
216
  });
198
217
  this.observe(result.pools);
@@ -211,6 +230,9 @@ function describedKey({ sha256Checksum, src, contextTokens }) {
211
230
  function deviceReason({ name, usedBytes, freeBytes }) {
212
231
  return ModelFit.need(name, usedBytes, freeBytes);
213
232
  }
233
+ function defined(config) {
234
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== undefined));
235
+ }
214
236
  function mib(bytes) {
215
237
  return `${Math.round(bytes / 1_048_576)} MiB`;
216
238
  }
@@ -36,7 +36,7 @@ interface RuntimeResidency {
36
36
  tools(): readonly ToolDefinition[];
37
37
  skills(agentId: string | null, model: string, trees?: readonly SkillTreeRef[]): Promise<CompletionSkillEntry[]>;
38
38
  platform(): string | undefined;
39
- loadOptions(model: string, agent?: CompletionContext['agent']): ModelLoadOptions;
39
+ sharedLoadOptions(model: string, agent: CompletionContext['agent'] | undefined, parallel: CompletionContext['parallel']): Promise<ModelLoadOptions>;
40
40
  deviceConfig(): LlmDeviceConfig;
41
41
  acquireLease(options: RuntimeAcquireOptions): Promise<RuntimeLease | null>;
42
42
  roomForCompletion(model: string, options: {
@@ -11,7 +11,7 @@ export async function prepareCompletionRuntime(residency, request) {
11
11
  const agent = request.agent;
12
12
  const messages = request.messages ?? [];
13
13
  const { signal, grantedDirs, grantedDrives, driveOp } = request;
14
- const loadOpts = residency.loadOptions(model, agent);
14
+ const loadOpts = await residency.sharedLoadOptions(model, agent, request.parallel);
15
15
  const projectionModel = loadOpts.projectionModel;
16
16
  if (request.resume && request.ctxSize) {
17
17
  loadOpts.ctxSize = request.ctxSize;
@@ -2,7 +2,7 @@ import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
2
  import type { CompletionSkillEntry } from '../capabilities/skill-entry.ts';
3
3
  import type { SkillTreeRef } from '../tools/skills/catalog.ts';
4
4
  import type { AgentConfig, ToolDefinition } from '../contract/index.ts';
5
- import type { BorrowedModel, ReleaseRoom, RoomHold } from '../contract/models.ts';
5
+ import type { BorrowedModel, ParallelLoad, ReleaseRoom, RoomHold } from '../contract/models.ts';
6
6
  import type { CapabilityInfo, LoadedModel, LoadModelResult, MemoryPoolUsage, UnloadModelContext, UnloadModelResult } from '../contract-types.ts';
7
7
  import type { Lifecycle } from '../lifecycle/index.ts';
8
8
  import type { HoldFn } from '../models/download-gate.ts';
@@ -53,6 +53,9 @@ export interface WedgedEviction {
53
53
  fatal: boolean;
54
54
  }
55
55
  export type LoadOptionKnobs = Pick<AgentConfig, 'ctxSize' | 'kvCacheK' | 'kvCacheV'>;
56
+ export type ServedLoad = LoadOptionKnobs & {
57
+ parallel?: ParallelLoad | undefined;
58
+ };
56
59
  export interface ResidencyOptions {
57
60
  llmDevice?: 'cpu' | 'gpu' | undefined;
58
61
  llmGpuLayers?: number | undefined;
@@ -98,6 +101,7 @@ export declare class Residency {
98
101
  private readonly _pinned;
99
102
  private readonly _borrowed;
100
103
  private readonly _replying;
104
+ private readonly _parallel;
101
105
  private readonly _modelStatus;
102
106
  private readonly _llmDevice?;
103
107
  private readonly _llmGpuLayers?;
@@ -202,10 +206,14 @@ export declare class Residency {
202
206
  loadOptions(model: string, agent?: LoadOptionKnobs): ModelLoadOptions;
203
207
  acquireLease({ pool, key, open, signal, prepare, onLoad }: ModelLeaseOptions): Promise<ModelLease | null>;
204
208
  completionRuntime(request: CompletionRuntimeRequest): Promise<import("./completion-runtime.ts").PreparedRuntime>;
205
- servedRound(model: string, load?: LoadOptionKnobs): {
209
+ servedRound(model: string, load?: ServedLoad): Promise<{
206
210
  key: string;
207
211
  acquireRound: (invocationSignal?: BareAbortSignal) => Promise<import("../contract/completion.ts").RoundModelLease>;
208
- };
212
+ }>;
213
+ sharedLoadOptions(model: string, knobs: LoadOptionKnobs | undefined, parallel: ParallelLoad | undefined): Promise<ModelLoadOptions>;
214
+ private _slottedLoad;
215
+ private _inUse;
216
+ private _fitsInPlaceOf;
209
217
  roomForCompletion(model: string, { loadOpts, signal }: Pick<RoomOptions, 'loadOpts' | 'signal'>): Promise<void>;
210
218
  makeRoomForCompletion(model: string, { loadOpts, signal, deadlineMs }: RoomOptions): Promise<boolean>;
211
219
  evictWedged(model: string, key: string): Promise<WedgedEviction>;
@@ -8,6 +8,7 @@ import { ContextChoice as ContextClimb } from '../models/context-choice.js';
8
8
  import { parseGgufHeader, readGgufHeaderBytes } from '../models/gguf-header.js';
9
9
  import { resolveMainGpu } from '../models/gpu-selection.js';
10
10
  import { createIdleReaper } from '../models/idle-unload.js';
11
+ import { adrenoSafeKvCache } from '../models/kv-cache.js';
11
12
  import { createLoadRequests } from '../models/load-requests.js';
12
13
  import { BUDGET_POOL, HOST_POOL, memoryCapBytes, nextVictim, poolsOver, sumPools, totalBytes, VictimRank } from '../models/memory-cap.js';
13
14
  import { assetBytes, curatedListables, curatedModelAsset, customContextLength, customModelSrc, generatorRowName, modelAddonOf, speculativeDraft } from '../models/model-catalog.js';
@@ -23,6 +24,9 @@ const WARM_ROOM_WAIT_MS = 2_000;
23
24
  const LOAD_BUSY_MESSAGE = 'the chat model is busy; load this model once the current reply finishes';
24
25
  const UNLOAD_LEASE_WAIT_MS = 10_000;
25
26
  const DEFAULT_COMPLETION_MODEL_CAP = 1;
27
+ const MAX_PARALLEL_SLOTS = 4;
28
+ const PARALLEL_CHOICE_MS = 10 * 60_000;
29
+ const SWAP_HEADROOM = 0.9;
26
30
  const WEDGED_EVICT_LEASED_MS = 120_000;
27
31
  function fitSrc(modelSrc) {
28
32
  if (typeof modelSrc === 'string')
@@ -60,6 +64,7 @@ export class Residency {
60
64
  _pinned = new Set();
61
65
  _borrowed = new Set();
62
66
  _replying = [];
67
+ _parallel = new Map();
63
68
  _modelStatus = createModelStatusCache();
64
69
  _llmDevice;
65
70
  _llmGpuLayers;
@@ -532,7 +537,7 @@ export class Residency {
532
537
  if (choice?.fits === false) {
533
538
  return this._alone(model, target);
534
539
  }
535
- if (choice && !target.loadOpts.ctxSize && !signal?.aborted) {
540
+ if (choice && !signal?.aborted) {
536
541
  this.fit.keep(target.key, choice);
537
542
  }
538
543
  return true;
@@ -673,7 +678,11 @@ export class Residency {
673
678
  fits: async (rung) => {
674
679
  const sized = await this._sizeLoad({
675
680
  ...load,
676
- modelConfig: { ...load.modelConfig, ctx_size: rung * slots }
681
+ modelConfig: {
682
+ gpu_layers: ModelFit.ALL_LAYERS,
683
+ ...load.modelConfig,
684
+ ctx_size: rung * slots
685
+ }
677
686
  });
678
687
  if (!sized.confirmed || this._capPercent === null) {
679
688
  return sized.confirmed;
@@ -834,13 +843,26 @@ export class Residency {
834
843
  if (!asset) {
835
844
  return null;
836
845
  }
837
- const load = { opts: loadOpts, deviceConfig: this.deviceConfig() };
846
+ const deviceConfig = this.deviceConfig();
847
+ const load = { opts: loadOpts, deviceConfig };
838
848
  const tier = contextSize(model, asset, load);
839
849
  const slots = slotCount(model, load);
840
- if (loadOpts.ctxSize || this.fit.chosen(modelKey(model, loadOpts))) {
850
+ if (this.fit.chosen(modelKey(model, loadOpts))) {
841
851
  return { ctxSize: tier, slots, fits: await this._fits(model, loadOpts, { native: true }) };
842
852
  }
843
- return this.fit.ladder(asset, tier, slots);
853
+ const { device, gpuLayers } = deviceConfig;
854
+ const { k: kvCacheK, v: kvCacheV } = adrenoSafeKvCache(device, {
855
+ k: loadOpts.kvCacheK,
856
+ v: loadOpts.kvCacheV
857
+ });
858
+ return this.fit.ladder(asset, tier, {
859
+ slots,
860
+ kvCacheK,
861
+ kvCacheV,
862
+ device,
863
+ gpuLayers,
864
+ rungs: !loadOpts.ctxSize
865
+ });
844
866
  }
845
867
  async _yieldPins(model, loadOpts) {
846
868
  for (const key of this._pinned) {
@@ -946,11 +968,73 @@ export class Residency {
946
968
  releaseWork();
947
969
  }
948
970
  }
949
- servedRound(model, load) {
950
- const loadOpts = this.loadOptions(model, load);
971
+ async servedRound(model, load) {
972
+ const loadOpts = await this.sharedLoadOptions(model, load, load?.parallel);
951
973
  const key = modelKey(model, loadOpts);
952
974
  return { key, acquireRound: roundAcquirer(this, { model, key, loadOpts }) };
953
975
  }
976
+ async sharedLoadOptions(model, knobs, parallel) {
977
+ const own = this.loadOptions(model, knobs);
978
+ if (!parallel || parallel.slots < 2) {
979
+ return own;
980
+ }
981
+ const now = Date.now();
982
+ for (const [group, { at }] of this._parallel) {
983
+ if (now - at > PARALLEL_CHOICE_MS) {
984
+ this._parallel.delete(group);
985
+ }
986
+ }
987
+ const group = `${model}\0${parallel.group}`;
988
+ const load = this._parallel.get(group)?.load ?? this._slottedLoad(model, own, parallel).catch(() => null);
989
+ this._parallel.set(group, { at: now, load });
990
+ return (await load) ?? own;
991
+ }
992
+ async _slottedLoad(model, own, { slots, ctxSize }) {
993
+ const asset = curatedModelAsset(model, 'llm');
994
+ const load = { opts: own, deviceConfig: this.deviceConfig() };
995
+ if (!asset || slotCount(model, load) > 1 || this._inUse(model)) {
996
+ return null;
997
+ }
998
+ const perSlot = ctxSize ?? contextSize(model, asset, load);
999
+ for (let width = Math.min(slots, MAX_PARALLEL_SLOTS); width > 1; width = Math.floor(width / 2)) {
1000
+ const opts = { ...own, ctxSize: perSlot, slots: width };
1001
+ if (await this._fitsInPlaceOf(model, own, opts)) {
1002
+ this.fit.keep(modelKey(model, opts), { ctxSize: perSlot, slots: width, fits: true });
1003
+ HarnessLog.info('slotted load', { model, slots: width, ctxSize: perSlot });
1004
+ return opts;
1005
+ }
1006
+ }
1007
+ return null;
1008
+ }
1009
+ _inUse(model) {
1010
+ return (loadingModels(this._models).includes(model) ||
1011
+ settledEntries(this._models).some(({ key, refs }) => modelOf(key) === model && (refs > 0 || this._replying.includes(key))));
1012
+ }
1013
+ async _fitsInPlaceOf(model, own, opts) {
1014
+ const asset = curatedModelAsset(model, 'llm');
1015
+ if (!asset) {
1016
+ return false;
1017
+ }
1018
+ const config = this.deviceConfig();
1019
+ const tokens = (loadOpts) => {
1020
+ const load = { opts: loadOpts, deviceConfig: config };
1021
+ return contextSize(model, asset, load) * slotCount(model, load);
1022
+ };
1023
+ const asked = await this.fit.settle(ModelFit.query(asset, tokens(opts), { native: true }));
1024
+ if (!asked || asked.verdict === 'unknown') {
1025
+ return false;
1026
+ }
1027
+ const idle = settledEntries(this._models).filter(({ key, refs }) => refs === 0 && modelOf(key) === model);
1028
+ if (this._over(asked.pools, sumPools(idle.flatMap(sizedPools))).length > 0) {
1029
+ return false;
1030
+ }
1031
+ if (asked.verdict !== 'likely-too-large') {
1032
+ return true;
1033
+ }
1034
+ const replaced = idle.length === 1 && idle[0].key === modelKey(model, own);
1035
+ const held = replaced ? await this.fit.settle(ModelFit.query(asset, tokens(own))) : null;
1036
+ return held?.bytes !== undefined && swapFits(asked, held);
1037
+ }
954
1038
  async roomForCompletion(model, { loadOpts, signal }) {
955
1039
  const key = modelKey(model, loadOpts);
956
1040
  if (isResident(this._models, key)) {
@@ -986,7 +1070,8 @@ export class Residency {
986
1070
  }
987
1071
  await this._yieldPins(model, loadOpts);
988
1072
  const key = modelKey(model, loadOpts);
989
- if (roomed && !signal?.aborted && !loadOpts.ctxSize && this.fit.chosen(key) === undefined) {
1073
+ const decides = !loadOpts.ctxSize || (loadOpts.slots ?? 1) > 1;
1074
+ if (roomed && !signal?.aborted && decides && this.fit.chosen(key) === undefined) {
990
1075
  const choice = await this._loadDecision(model, loadOpts);
991
1076
  if (choice) {
992
1077
  this.fit.keep(key, choice);
@@ -1042,6 +1127,12 @@ export class Residency {
1042
1127
  }
1043
1128
  }
1044
1129
  }
1130
+ function swapFits(asked, held) {
1131
+ return Object.entries(asked.pools).every(([pool, bytes]) => {
1132
+ const free = asked.free?.[pool];
1133
+ return free !== undefined && bytes - (held.pools[pool] ?? 0) <= free * SWAP_HEADROOM;
1134
+ });
1135
+ }
1045
1136
  function sizedPools({ pools }) {
1046
1137
  return pools ? [pools] : [];
1047
1138
  }
@@ -20,4 +20,6 @@ export interface ExecToolOptions {
20
20
  }
21
21
  export type SkillEnvFn = (skill: string) => Readonly<Record<string, string>> | undefined;
22
22
  export declare function declaredEnv(declared: Readonly<Record<string, string>> | undefined, session: string | undefined): Record<string, string>;
23
+ export declare const WEB_REQUEST_ERROR = "exec does not make web requests. Call http_request with method \"GET\" instead; it attaches stored skill credentials itself.";
24
+ export declare function webRequestError(command: string, toolNames: readonly string[]): string | null;
23
25
  export declare function createExecTool({ policyVersion, spawn, killProcess, shell: composedShell, languages, routes, skillSettings, skillEnv, realpath, deniedRoots, skillsDir }?: ExecToolOptions): ToolDefinition;
@@ -5,7 +5,8 @@ import { createShellAdapter } from './exec/adapters/shell/shell-adapter.js';
5
5
  import { isPythonLanguage } from './exec/python-source.js';
6
6
  import { MAX_OUTPUT_CHARS, MAX_OUTPUT_CHARS_LIMIT } from './exec/runner.js';
7
7
  import { bareBin, sanitizeCommand } from './exec/scope.js';
8
- import { LANGUAGE_UNAVAILABLE_ERROR, PYTHON_UNAVAILABLE_ERROR, SHELL_DOWNLOAD_NOTE, shellOnlyError, tlsBypassError, videoToolError } from './exec/shell-guidance.js';
8
+ import { commandBin, LANGUAGE_UNAVAILABLE_ERROR, PYTHON_UNAVAILABLE_ERROR, savesDownload, SHELL_DOWNLOAD_NOTE, shellOnlyError, tlsBypassError, videoToolError } from './exec/shell-guidance.js';
9
+ import { isPrivateOrBlocked, stripIPv6Brackets } from './private-ip.js';
9
10
  import { ShellLine } from './exec/shell-line.js';
10
11
  import { bareRuntime } from './exec/bare-runtime.js';
11
12
  import { canonicalDenyRoots, defaultRealpath, hostPath, resolveKey } from './fs/scope.js';
@@ -239,6 +240,29 @@ function execSchema(languages) {
239
240
  }
240
241
  };
241
242
  }
243
+ export const WEB_REQUEST_ERROR = 'exec does not make web requests. Call http_request with method "GET" instead; it attaches stored skill credentials itself.';
244
+ export function webRequestError(command, toolNames) {
245
+ const bin = commandBin(command);
246
+ if ((bin !== 'curl' && bin !== 'wget') || !toolNames.includes('http_request')) {
247
+ return null;
248
+ }
249
+ if (savesDownload(command)) {
250
+ return null;
251
+ }
252
+ const argv = ShellLine.parse(command).commands[0]?.argv ?? [];
253
+ const target = argv.find((word) => /^https?:\/\//i.test(word));
254
+ if (!target) {
255
+ return null;
256
+ }
257
+ try {
258
+ return isPrivateOrBlocked(stripIPv6Brackets(new URL(target).hostname))
259
+ ? null
260
+ : WEB_REQUEST_ERROR;
261
+ }
262
+ catch {
263
+ return null;
264
+ }
265
+ }
242
266
  export function createExecTool({ policyVersion, spawn, killProcess, shell: composedShell, languages = [], routes = [], skillSettings, skillEnv, realpath = defaultRealpath, deniedRoots, skillsDir } = {}) {
243
267
  const shell = composedShell ??
244
268
  createShellAdapter({
@@ -312,6 +336,10 @@ export function createExecTool({ policyVersion, spawn, killProcess, shell: compo
312
336
  if (scopeError) {
313
337
  return scopeError;
314
338
  }
339
+ const webRequest = language ? null : webRequestError(command, ctx?.toolNames ?? []);
340
+ if (webRequest) {
341
+ return webRequest;
342
+ }
315
343
  const workdirGiven = rawArgs.workdir !== undefined && rawArgs.workdir !== null;
316
344
  if (workdirGiven && !language && (ctx?.fsRoots ?? []).length === 0) {
317
345
  return WORKDIR_NO_ROOTS_ERROR;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qvac/harness",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "bare": ">=1.33.4",