@qvac/harness 1.0.1 → 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.
Files changed (98) hide show
  1. package/CHANGELOG.md +171 -6
  2. package/README.md +39 -0
  3. package/dist-lib/index.d.ts +32 -304
  4. package/dist-lib/index.js +16 -1147
  5. package/dist-lib/lib/agent/child-run.d.ts +33 -0
  6. package/dist-lib/lib/agent/child-run.js +58 -0
  7. package/dist-lib/lib/agent/delegate.d.ts +3 -19
  8. package/dist-lib/lib/agent/delegate.js +8 -31
  9. package/dist-lib/lib/agent/index.d.ts +7 -0
  10. package/dist-lib/lib/agent/index.js +5 -0
  11. package/dist-lib/lib/agent/read-parts.d.ts +47 -0
  12. package/dist-lib/lib/agent/read-parts.js +85 -0
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +6 -2
  14. package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -0
  15. package/dist-lib/lib/capabilities/completion-engine/engine.js +27 -18
  16. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +4 -1
  17. package/dist-lib/lib/capabilities/completion-engine/round.js +5 -4
  18. package/dist-lib/lib/client/index.js +1 -3
  19. package/dist-lib/lib/connect/decode.d.ts +3 -2
  20. package/dist-lib/lib/connect/decode.js +14 -0
  21. package/dist-lib/lib/connect.d.ts +1 -0
  22. package/dist-lib/lib/connect.js +11 -5
  23. package/dist-lib/lib/context-window.d.ts +2 -0
  24. package/dist-lib/lib/context-window.js +17 -14
  25. package/dist-lib/lib/contract/models.d.ts +13 -1
  26. package/dist-lib/lib/contract-types.d.ts +9 -0
  27. package/dist-lib/lib/harness.d.ts +269 -0
  28. package/dist-lib/lib/harness.js +1154 -0
  29. package/dist-lib/lib/models/custom-model-cache.d.ts +2 -0
  30. package/dist-lib/lib/models/custom-model-cache.js +21 -0
  31. package/dist-lib/lib/models/memory-cap.d.ts +6 -0
  32. package/dist-lib/lib/models/memory-cap.js +20 -0
  33. package/dist-lib/lib/models/model-catalog.d.ts +2 -0
  34. package/dist-lib/lib/models/model-catalog.js +8 -2
  35. package/dist-lib/lib/models/model-fit.d.ts +59 -10
  36. package/dist-lib/lib/models/model-fit.js +172 -35
  37. package/dist-lib/lib/models/model-handle.d.ts +2 -1
  38. package/dist-lib/lib/models/model-pool.d.ts +3 -2
  39. package/dist-lib/lib/models/model-pool.js +30 -13
  40. package/dist-lib/lib/models/tts-model-default.d.ts +1 -1
  41. package/dist-lib/lib/models/tts-model-default.js +7 -6
  42. package/dist-lib/lib/residency/completion-runtime.d.ts +1 -1
  43. package/dist-lib/lib/residency/completion-runtime.js +1 -1
  44. package/dist-lib/lib/residency/index.d.ts +31 -9
  45. package/dist-lib/lib/residency/index.js +286 -88
  46. package/dist-lib/lib/run-log/boundary.d.ts +4 -1
  47. package/dist-lib/lib/run-log/boundary.js +2 -1
  48. package/dist-lib/lib/run-log/index.d.ts +2 -1
  49. package/dist-lib/lib/run-log/index.js +2 -1
  50. package/dist-lib/lib/run-log/persisted-actor.d.ts +10 -0
  51. package/dist-lib/lib/run-log/persisted-actor.js +15 -0
  52. package/dist-lib/lib/run-log/run-journal.d.ts +3 -0
  53. package/dist-lib/lib/run-log/run-journal.js +19 -8
  54. package/dist-lib/lib/serve/requests.d.ts +3 -0
  55. package/dist-lib/lib/serve.js +3 -0
  56. package/dist-lib/lib/spawn.d.ts +4 -1
  57. package/dist-lib/lib/tools/exec.d.ts +2 -0
  58. package/dist-lib/lib/tools/exec.js +29 -1
  59. package/dist-lib/lib/tools/files/list-dir.js +79 -32
  60. package/dist-lib/lib/tools/fs/walk.d.ts +11 -1
  61. package/dist-lib/lib/tools/fs/walk.js +64 -30
  62. package/dist-lib/lib/tools/office.js +8 -5
  63. package/dist-lib/lib/tools/pdf/pages.d.ts +1 -1
  64. package/dist-lib/lib/tools/pdf/pages.js +3 -14
  65. package/dist-lib/lib/tools/pdf/recognize.d.ts +3 -0
  66. package/dist-lib/lib/tools/pdf/recognize.js +45 -7
  67. package/dist-lib/plugins/image/generate-image.d.ts +2 -2
  68. package/dist-lib/plugins/image/generate-image.js +9 -1
  69. package/dist-lib/plugins/image/index.js +6 -2
  70. package/dist-lib/plugins/knowledge/chunk-index.d.ts +4 -0
  71. package/dist-lib/plugins/knowledge/chunk-index.js +191 -0
  72. package/dist-lib/plugins/knowledge/index.d.ts +1 -0
  73. package/dist-lib/plugins/knowledge/index.js +1 -0
  74. package/dist-lib/plugins/knowledge/manifest.d.ts +2 -1
  75. package/dist-lib/plugins/knowledge/manifest.js +2 -9
  76. package/dist-lib/plugins/knowledge/store.d.ts +5 -1
  77. package/dist-lib/plugins/knowledge/store.js +44 -16
  78. package/dist-lib/plugins/lsp/rpc.d.ts +9 -1
  79. package/dist-lib/plugins/lsp/rpc.js +81 -17
  80. package/dist-lib/plugins/music/generate-music.d.ts +2 -2
  81. package/dist-lib/plugins/music/generate-music.js +14 -1
  82. package/dist-lib/plugins/music/index.js +4 -1
  83. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  84. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  85. package/dist-lib/plugins/speech/speech-engine.d.ts +5 -2
  86. package/dist-lib/plugins/speech/speech-engine.js +28 -7
  87. package/dist-lib/schema/harness.js +28 -2
  88. package/dist-lib/spec/bind.js +3 -0
  89. package/dist-lib/spec/calls.js +1 -0
  90. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  91. package/dist-lib/spec/hrpc/index.js +15 -3
  92. package/dist-lib/spec/hrpc/messages.js +87 -6
  93. package/dist-lib/spec/hyperschema/index.js +87 -6
  94. package/dist-lib/spec/hyperschema/schema.json +70 -2
  95. package/dist-lib/spec/hyperschema/types.d.ts +21 -1
  96. package/package.json +29 -28
  97. package/scripts/addon-externals.cjs +1 -0
  98. package/worker/harness-sidecar.mjs +12 -1
@@ -0,0 +1,33 @@
1
+ import type { FollowEvent, FollowHost } from './follow.ts';
2
+ export interface ChildRequest {
3
+ runId?: string;
4
+ parentRunId?: string;
5
+ cacheKey?: string;
6
+ messages?: ReadonlyArray<{
7
+ role: string;
8
+ content: string;
9
+ }>;
10
+ tools?: ReadonlyArray<{
11
+ name: string;
12
+ }>;
13
+ resume?: unknown;
14
+ recovery?: unknown;
15
+ input?: unknown;
16
+ goal?: unknown;
17
+ latency?: unknown;
18
+ }
19
+ export interface ChildRun {
20
+ parent: string | undefined;
21
+ id: string;
22
+ prompt: string;
23
+ }
24
+ export interface ChildResult {
25
+ status: 'answered' | 'paused' | 'aborted' | 'error';
26
+ text: string;
27
+ }
28
+ export declare function childRun<Request extends ChildRequest>(base: Request, { parent, id, prompt }: ChildRun): Request;
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;
@@ -0,0 +1,58 @@
1
+ export function childRun(base, { parent, id, prompt }) {
2
+ const run = {
3
+ ...base,
4
+ runId: parent === undefined ? undefined : `${parent}/${id}`,
5
+ parentRunId: parent,
6
+ messages: [{ role: 'user', content: prompt }]
7
+ };
8
+ delete run.resume;
9
+ delete run.recovery;
10
+ delete run.input;
11
+ delete run.goal;
12
+ delete run.latency;
13
+ return run;
14
+ }
15
+ export async function collect(host, request) {
16
+ let text = '';
17
+ let status = 'answered';
18
+ for await (const event of host.completion(request)) {
19
+ const { type } = event;
20
+ if (type === 'content') {
21
+ text += String(Object(event).text ?? '');
22
+ }
23
+ else if (type === 'error') {
24
+ status = type;
25
+ text = String(Object(event).message ?? '');
26
+ }
27
+ else if (type === 'paused' || type === 'aborted') {
28
+ status = type;
29
+ }
30
+ }
31
+ return { status, text };
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,28 +1,14 @@
1
1
  import type { AccessPolicy, ToolDefinition, ToolExecuteContext } from '../contract/index.ts';
2
+ import type { ChildRequest, ChildResult } from './child-run.ts';
2
3
  import type { FollowEvent, FollowHost } from './follow.ts';
3
4
  export declare const DELEGATE_TOOL_NAME = "delegate";
4
- export interface DelegateRequest {
5
- runId?: string;
6
- parentRunId?: string;
7
- cacheKey?: string;
5
+ export interface DelegateRequest extends ChildRequest {
8
6
  signal?: ToolExecuteContext['signal'];
9
- messages?: ReadonlyArray<{
10
- role: string;
11
- content: string;
12
- }>;
13
- tools?: ReadonlyArray<{
14
- name: string;
15
- }>;
16
7
  agent?: {
17
8
  handoffs?: unknown;
18
9
  policy?: AccessPolicy | null;
19
10
  };
20
11
  policy?: AccessPolicy;
21
- resume?: unknown;
22
- recovery?: unknown;
23
- input?: unknown;
24
- goal?: unknown;
25
- latency?: unknown;
26
12
  }
27
13
  export type TargetAccess = 'read' | 'write';
28
14
  export interface TargetTask {
@@ -62,10 +48,8 @@ export interface DelegateOptions {
62
48
  read?: readonly string[];
63
49
  maxExternal?: number;
64
50
  }
65
- export interface LocalResult {
51
+ export interface LocalResult extends ChildResult {
66
52
  task: string;
67
- status: 'answered' | 'paused' | 'aborted' | 'error';
68
- text: string;
69
53
  }
70
54
  export interface ExternalResult {
71
55
  task: string;
@@ -1,4 +1,5 @@
1
1
  import { Policy } from '../policy/index.js';
2
+ import { childRun, collect } from './child-run.js';
2
3
  export const DELEGATE_TOOL_NAME = 'delegate';
3
4
  const LOCAL = 'local';
4
5
  const MAX_EXTERNAL = 2;
@@ -149,7 +150,7 @@ async function fanOut(host, base, { slots, maxExternal, args, ctx, ...roster })
149
150
  await Promise.all([
150
151
  pool(local, slots, async (index, worker) => {
151
152
  const request = child(base, ctx, { ...tasks[index], summary, index, worker });
152
- fanned.results[index] = await subagent(host, tasks[index].task, request);
153
+ fanned.results[index] = { task: tasks[index].task, ...(await collect(host, request)) };
153
154
  }),
154
155
  pool(outside, maxExternal, async ({ index, target }, worker) => {
155
156
  const { task } = tasks[index];
@@ -226,39 +227,15 @@ function deadlineTimer(deadlineMs, controller) {
226
227
  return deadline;
227
228
  }
228
229
  function child(base, ctx, { task, summary, index, worker }) {
229
- const parent = ctx?.runId ?? base.runId;
230
- const run = {
231
- ...base,
232
- runId: parent === undefined ? undefined : `${parent}/d-${ctx?.callId ?? 0}-${index}`,
233
- parentRunId: parent,
230
+ return {
231
+ ...childRun(base, {
232
+ parent: ctx?.runId ?? base.runId,
233
+ id: `d-${ctx?.callId ?? 0}-${index}`,
234
+ prompt: summary ? `${summary}\n\n${task}` : task
235
+ }),
234
236
  signal: ctx?.signal ?? base.signal,
235
237
  cacheKey: base.cacheKey === undefined ? undefined : `${base.cacheKey}/d-${worker}`,
236
- messages: [{ role: 'user', content: summary ? `${summary}\n\n${task}` : task }],
237
238
  tools: base.tools?.filter((tool) => tool.name !== DELEGATE_TOOL_NAME),
238
239
  agent: base.agent && { ...base.agent, handoffs: null }
239
240
  };
240
- delete run.resume;
241
- delete run.recovery;
242
- delete run.input;
243
- delete run.goal;
244
- delete run.latency;
245
- return run;
246
- }
247
- async function subagent(host, task, request) {
248
- let text = '';
249
- let status = 'answered';
250
- for await (const event of host.completion(request)) {
251
- const { type } = event;
252
- if (type === 'content') {
253
- text += String(Object(event).text ?? '');
254
- }
255
- else if (type === 'error') {
256
- status = type;
257
- text = String(Object(event).message ?? '');
258
- }
259
- else if (type === 'paused' || type === 'aborted') {
260
- status = type;
261
- }
262
- }
263
- return { task, status, text };
264
241
  }
@@ -1,6 +1,8 @@
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';
5
+ import { notesContext, readParts } from './read-parts.ts';
4
6
  import { agentPolicy, resolveAgent } from './resolve.ts';
5
7
  import { planFromMessages, planSteps } from './plan.ts';
6
8
  import { parseToolGrant } from './tool-grants.ts';
@@ -23,6 +25,9 @@ export declare class Agent<Skill extends AgentSkill = AgentSkill> {
23
25
  static skillIsActive: typeof skillIsActive;
24
26
  static follow: typeof follow;
25
27
  static delegateTool: typeof createDelegateTool;
28
+ static readParts: typeof readParts;
29
+ static limiter: typeof limiter;
30
+ static notesContext: typeof notesContext;
26
31
  static untransferred: typeof untransferred;
27
32
  static planSteps: typeof planSteps;
28
33
  static planFromMessages: typeof planFromMessages;
@@ -33,5 +38,7 @@ export declare class Agent<Skill extends AgentSkill = AgentSkill> {
33
38
  policy(): AgentPolicy;
34
39
  }
35
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';
36
42
  export type { FollowAgent, FollowEvent, FollowHost, FollowRequest } from './follow.ts';
43
+ export type { DocumentNotes, DocumentPart, PartNote, PartProgress, ReadPartsOptions, ReadPartsRequest } from './read-parts.ts';
37
44
  export type { TransferResult } from './transfer.ts';
@@ -1,5 +1,7 @@
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';
4
+ import { notesContext, readParts } from './read-parts.js';
3
5
  import { agentPolicy, resolveAgent } from './resolve.js';
4
6
  import { MAX_PLAN_STEPS, PLAN_TOOL_NAME, planFromMessages, planSteps } from './plan.js';
5
7
  import { parseToolGrant } from './tool-grants.js';
@@ -24,6 +26,9 @@ export class Agent {
24
26
  static skillIsActive = skillIsActive;
25
27
  static follow = follow;
26
28
  static delegateTool = createDelegateTool;
29
+ static readParts = readParts;
30
+ static limiter = limiter;
31
+ static notesContext = notesContext;
27
32
  static untransferred = untransferred;
28
33
  static planSteps = planSteps;
29
34
  static planFromMessages = planFromMessages;
@@ -0,0 +1,47 @@
1
+ import type { ChildRequest, ChildResult, Limiter } from './child-run.ts';
2
+ import type { FollowEvent, FollowHost } from './follow.ts';
3
+ export interface ReadPartsRequest extends ChildRequest {
4
+ signal?: {
5
+ readonly aborted: boolean;
6
+ };
7
+ agent?: {
8
+ handoffs?: unknown;
9
+ toolsScope?: 'all' | 'selected' | null;
10
+ enabledTools?: string[] | null;
11
+ skillsScope?: 'all' | 'selected' | null;
12
+ enabledSkills?: string[] | null;
13
+ };
14
+ generationParams?: {
15
+ reasoning_budget?: number;
16
+ predict?: number;
17
+ };
18
+ }
19
+ export interface DocumentPart {
20
+ text: string;
21
+ span?: string;
22
+ }
23
+ export interface ReadPartsOptions {
24
+ read: string;
25
+ title: string;
26
+ parts: ReadonlyArray<DocumentPart>;
27
+ noteTokens: number;
28
+ onPart?: (progress: PartProgress) => void;
29
+ onNote?: (progress: PartProgress) => void;
30
+ limiter?: Limiter;
31
+ }
32
+ export interface PartProgress {
33
+ part: number;
34
+ parts: number;
35
+ }
36
+ export interface PartNote extends ChildResult {
37
+ span?: string;
38
+ }
39
+ export interface DocumentNotes {
40
+ title: string;
41
+ notes: ReadonlyArray<{
42
+ text: string;
43
+ span?: string;
44
+ }>;
45
+ }
46
+ export declare function readParts<Request extends ReadPartsRequest, Event extends FollowEvent>(host: FollowHost<Request, Event>, base: Request, { parts, limiter: lane, ...options }: ReadPartsOptions): Promise<PartNote[]>;
47
+ export declare function notesContext(documents: ReadonlyArray<DocumentNotes>): string;
@@ -0,0 +1,85 @@
1
+ import { childRun, collect, limiter } from './child-run.js';
2
+ const WORDS_PER_TOKEN = 0.55;
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) {
36
+ break;
37
+ }
38
+ run.push(note);
39
+ if (note.status !== 'answered') {
40
+ break;
41
+ }
42
+ }
43
+ return run;
44
+ }
45
+ export function notesContext(documents) {
46
+ const names = documents.map((document) => `"${document.title}"`).join(', ');
47
+ const lines = [
48
+ `Notes taken while reading the whole of ${names} part by part follow, in reading order. Answer the user from them directly.`
49
+ ];
50
+ for (const { title, notes } of documents) {
51
+ for (const [index, note] of notes.entries()) {
52
+ const span = note.span ? ` (${note.span})` : '';
53
+ lines.push('', `--- ${title}, part ${index + 1} of ${notes.length}${span} ---`, note.text);
54
+ }
55
+ }
56
+ return lines.join('\n');
57
+ }
58
+ function notesPrompt({ title, part, index, count, noteTokens }) {
59
+ const span = part.span ? ` (${part.span})` : '';
60
+ const words = Math.floor((noteTokens * WORDS_PER_TOKEN) / 10) * 10;
61
+ return [
62
+ `Part ${index + 1} of ${count} of the document "${title}"${span} follows.`,
63
+ '',
64
+ `--- ${title}${span} ---`,
65
+ part.text,
66
+ '',
67
+ `You are reading this document part by part so it can be summarized afterwards. Write notes on this part only: its main argument, then every specific claim, recommendation, number, definition and caveat a faithful summary would need. State each claim itself, do not just name its topic. Use at most ${words} words. Add nothing that is not in the text.`
68
+ ].join('\n');
69
+ }
70
+ function child(base, { prompt, id, index, noteTokens }) {
71
+ return {
72
+ ...childRun(base, { parent: base.runId, id: `r-${id}-${index}`, prompt }),
73
+ cacheKey: undefined,
74
+ tools: [],
75
+ agent: base.agent && {
76
+ ...base.agent,
77
+ handoffs: null,
78
+ toolsScope: 'selected',
79
+ enabledTools: [],
80
+ skillsScope: 'selected',
81
+ enabledSkills: []
82
+ },
83
+ generationParams: { ...base.generationParams, reasoning_budget: 0, predict: noteTokens }
84
+ };
85
+ }
@@ -521,7 +521,7 @@ export async function* driveCompletion(args, runtime, options) {
521
521
  : args.input,
522
522
  lockOwner: args.lockOwner ?? options.lockOwner ?? completionLockOwner,
523
523
  now,
524
- async start({ operations, invokes, boot: openedBoot }) {
524
+ async start({ operations, invokes, boot: openedBoot, initial }) {
525
525
  if (resume &&
526
526
  RunLog.unsettledRedactedIds(openedBoot.redactedPendingIds, openedBoot.receipts).length > 0) {
527
527
  const forkAt = safeForkLength(openedBoot);
@@ -570,10 +570,14 @@ export async function* driveCompletion(args, runtime, options) {
570
570
  outbound: options.outbound,
571
571
  agentPorts: worded(options.agentPorts, full.wording?.guidelines)
572
572
  });
573
- session.startedAt = openedBoot.metadata?.startedAt ?? openedBoot.firstSavedAt ?? now();
573
+ session.startedAt =
574
+ openedBoot.metadata?.startedAt ?? openedBoot.firstSavedAt ?? initial?.startedAt ?? now();
574
575
  if (openedBoot.metadata?.budget) {
575
576
  session.runBudget = { ...openedBoot.metadata.budget };
576
577
  }
578
+ else if (initial?.budget) {
579
+ session.runBudget = { ...initial.budget };
580
+ }
577
581
  session.toolContext = runToolContext(full, session.runBudget);
578
582
  const context = CompletionMachine.emptyContext({
579
583
  policy,
@@ -27,6 +27,10 @@ export interface EngineRun {
27
27
  operations: EngineOperationPort;
28
28
  invokes: InvokeTracker;
29
29
  boot: EngineBoot;
30
+ initial?: {
31
+ budget: RunBudget;
32
+ startedAt?: number;
33
+ };
30
34
  }): Promise<{
31
35
  ports: EnginePorts;
32
36
  context: CompletionContext;
@@ -43,7 +43,8 @@ function started({ runId, resume, parentRunId }) {
43
43
  }
44
44
  export async function* runEngine(run, options = {}) {
45
45
  const { runId } = run;
46
- const journal = RunLog.openBoundary(options);
46
+ const transient = !run.resume && !options.boot && typeof options.onStep !== 'function';
47
+ const journal = RunLog.openBoundary(options, { transient });
47
48
  const core = journal.core;
48
49
  const release = RunLog.acquireRun(run.lockOwner ?? options.lockOwner ?? core, runId);
49
50
  try {
@@ -53,6 +54,7 @@ export async function* runEngine(run, options = {}) {
53
54
  else if (journal.knownLength !== core.length) {
54
55
  throw new Error(`Run ${runId} changed while opening`);
55
56
  }
57
+ let startedAt;
56
58
  if (run.resume) {
57
59
  if (!journal.metadata) {
58
60
  throw new Error(`Run ${runId} does not exist`);
@@ -76,20 +78,23 @@ export async function* runEngine(run, options = {}) {
76
78
  if (run.recovery?.length) {
77
79
  throw new Error('Recovery resolutions require resume mode');
78
80
  }
79
- const metadata = {
80
- version: RunLog.VERSION,
81
- type: 'metadata',
82
- machine: CompletionMachine.VERSION,
83
- definition: CompletionMachine.definition(),
84
- xstate: RunLog.XSTATE_VERSION,
85
- runId,
86
- request: run.request,
87
- requestDigest: run.requestDigest,
88
- digestRunId: run.requestDigest ? runId : undefined,
89
- budget: run.budget,
90
- startedAt: run.now ? run.now() : undefined
91
- };
92
- await journal.append(metadata);
81
+ startedAt = run.now ? run.now() : undefined;
82
+ if (!transient) {
83
+ const metadata = {
84
+ version: RunLog.VERSION,
85
+ type: 'metadata',
86
+ machine: CompletionMachine.VERSION,
87
+ definition: CompletionMachine.definition(),
88
+ xstate: RunLog.XSTATE_VERSION,
89
+ runId,
90
+ request: run.request,
91
+ requestDigest: run.requestDigest,
92
+ digestRunId: run.requestDigest ? runId : undefined,
93
+ budget: run.budget,
94
+ startedAt
95
+ };
96
+ await journal.append(metadata);
97
+ }
93
98
  }
94
99
  const restored = readRestoredSnapshot(journal.snapshot);
95
100
  if (restored && restored.context?.runId !== runId) {
@@ -118,7 +123,8 @@ export async function* runEngine(run, options = {}) {
118
123
  const { ports, context } = await run.start({
119
124
  operations: createOperationPort(journal),
120
125
  invokes,
121
- boot
126
+ boot,
127
+ initial: transient ? { budget: run.budget, startedAt } : undefined
122
128
  });
123
129
  return yield* drive({
124
130
  journal,
@@ -135,6 +141,7 @@ export async function* runEngine(run, options = {}) {
135
141
  invokes,
136
142
  now: ports.now,
137
143
  durable: typeof options.onStep === 'function',
144
+ transient,
138
145
  onDetached: options.onDetached,
139
146
  mailbox
140
147
  });
@@ -146,7 +153,7 @@ export async function* runEngine(run, options = {}) {
146
153
  release();
147
154
  }
148
155
  }
149
- async function* drive({ journal, run, machine, invokes, now, durable, onDetached, mailbox }) {
156
+ async function* drive({ journal, run, machine, invokes, now, durable, transient, onDetached, mailbox }) {
150
157
  const { runId, signal } = run;
151
158
  const pausedMs = run.resume && journal.snapshotSavedAt !== undefined
152
159
  ? Math.max(0, now() - journal.snapshotSavedAt)
@@ -167,7 +174,9 @@ async function* drive({ journal, run, machine, invokes, now, durable, onDetached
167
174
  wake();
168
175
  };
169
176
  mailbox.notify = notify;
170
- const { actor, persistence } = await RunLog.createPersistedActor(journal, machine, notify, now);
177
+ const { actor, persistence } = transient
178
+ ? RunLog.createTransientActor(machine, journal, notify)
179
+ : await RunLog.createPersistedActor(journal, machine, notify, now);
171
180
  actor.on('*', (event) => {
172
181
  queue.push(event);
173
182
  notify();
@@ -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;
@@ -372,8 +372,12 @@ async function* runRecoveredRoundWith(send) {
372
372
  }
373
373
  async function* runLadder({ send, history, origins, fold }) {
374
374
  let lastOverflow = null;
375
- const candidates = ContextWindow.contextCandidates(history, ...harnessTurns(send.args, history));
375
+ let tried = 0;
376
+ const candidates = ContextWindow.contextCandidateIterator(history, ...harnessTurns(send.args, history));
376
377
  for (const candidate of candidates) {
378
+ if (tried++ === 1) {
379
+ await dropShrunkKey(send);
380
+ }
377
381
  const outcome = yield* runCandidateAttempts({ ...send, candidate, history, origins });
378
382
  if ('round' in outcome) {
379
383
  const cacheable = !send.attempts.uncached;
@@ -386,9 +390,6 @@ async function* runLadder({ send, history, origins, fold }) {
386
390
  if (folded) {
387
391
  return { folded };
388
392
  }
389
- if (candidates.length > 1) {
390
- await dropShrunkKey(send);
391
- }
392
393
  }
393
394
  }
394
395
  if (!lastOverflow) {
@@ -149,9 +149,7 @@ export class HarnessClient {
149
149
  actualSize: actualSize || undefined,
150
150
  label: label || undefined,
151
151
  taskType: addonTaskType(row.type),
152
- fit: (fit || undefined),
153
- fitBasis: (fitBasis || undefined),
154
- fitEvidence: (fitEvidence || undefined)
152
+ fit: (fit || undefined)
155
153
  }));
156
154
  }
157
155
  close() {
@@ -1,5 +1,5 @@
1
- import type { HarnessLoadedModel } from '../../spec/hyperschema/types.d.ts';
2
- import type { AgentKnobs, CompletionContext, HarnessEvent, HostContext, LoadedModel } from '../contract-types.ts';
1
+ import type { HarnessLoadedModel, HarnessMemoryUsage } from '../../spec/hyperschema/types.d.ts';
2
+ import type { AgentKnobs, CompletionContext, HarnessEvent, HostContext, LoadedModel, MemoryUsage } from '../contract-types.ts';
3
3
  import type { ToolCallDisplay } from '../contract/index.ts';
4
4
  import { type SkillState } from '../tools/skills/skill-state.ts';
5
5
  import type { WireDownloadEvent } from '../wire.ts';
@@ -11,6 +11,7 @@ export interface WireModelEvent extends HarnessEvent {
11
11
  loaded?: HarnessLoadedModel[];
12
12
  }
13
13
  export declare function loadedModel({ model, refs, fit }: HarnessLoadedModel | LoadedModel): LoadedModel;
14
+ export declare function memoryUsage({ usedBytes, pools }: HarnessMemoryUsage): MemoryUsage;
14
15
  export declare function parseSkillState(value: string): SkillState;
15
16
  export declare function errorDetails(err: unknown): ErrorDetails;
16
17
  export declare function isToolCallDisplay(value: unknown): value is ToolCallDisplay;
@@ -19,6 +19,20 @@ export function loadedModel({ model, refs, fit }) {
19
19
  }
20
20
  };
21
21
  }
22
+ export function memoryUsage({ usedBytes, pools }) {
23
+ if (!pools) {
24
+ return { usedBytes };
25
+ }
26
+ return {
27
+ usedBytes,
28
+ pools: pools.map(({ id, usedBytes: used, capBytes, totalBytes }) => ({
29
+ id,
30
+ usedBytes: used,
31
+ capBytes: capBytes || undefined,
32
+ totalBytes: totalBytes || undefined
33
+ }))
34
+ };
35
+ }
22
36
  export function parseSkillState(value) {
23
37
  return value ? value : SKILL_STATE.failed;
24
38
  }
@@ -41,6 +41,7 @@ export declare class RemoteHarness extends EventEmitter implements HarnessContra
41
41
  private _run;
42
42
  download(context: HostContext<DownloadContext>): AsyncIterable<HarnessEvent>;
43
43
  embed(context: HostContext<EmbedContext>): Promise<number[][]>;
44
+ embeddingWeights(model: string): Promise<string | undefined>;
44
45
  transcribe(context: HostContext<TranscribeContext>): Promise<string>;
45
46
  ocrRead(context: HostContext<OcrReadContext>): Promise<OcrPage>;
46
47
  detectLanguage(context: DetectLanguageContext): Promise<DetectedLanguage[]>;
@@ -22,7 +22,7 @@ import { sweepSpill } from './spill.js';
22
22
  import { readInstall, readSetup } from './tools/skills/manifest-parse.js';
23
23
  import { asToolset } from './tools/toolsets.js';
24
24
  import { Wire } from './wire.js';
25
- import { loadedModel, parseSkillState, errorDetails, knobs, explicitEmptyIdentityFields, frames, downloadFrames } from './connect/decode.js';
25
+ import { loadedModel, memoryUsage, parseSkillState, errorDetails, knobs, explicitEmptyIdentityFields, frames, downloadFrames } from './connect/decode.js';
26
26
  import { died, noop, abortable, awaitWithAbort } from './connect/abort.js';
27
27
  import { abortedRound, servedRound, servedMedia } from './connect/served.js';
28
28
  import { bridgeAttach, bridgeShow, bridgeFetch, bridgeDrive, sendInput, answerQuestion, approvalCall } from './connect/bridges.js';
@@ -686,6 +686,11 @@ export class RemoteHarness extends EventEmitter {
686
686
  }
687
687
  return rows;
688
688
  }
689
+ async embeddingWeights(model) {
690
+ const { client } = await this._ensure();
691
+ const response = await client.embeddingWeights({ model });
692
+ return response.weights || undefined;
693
+ }
689
694
  async transcribe(context) {
690
695
  const { client } = await this._ensure();
691
696
  const response = await abortable(client.transcribe({ model: context.model, audio: context.audio }), context.signal);
@@ -770,7 +775,7 @@ export class RemoteHarness extends EventEmitter {
770
775
  }
771
776
  async memoryUsage() {
772
777
  const { client } = await this._ensure();
773
- return await client.memoryUsage({});
778
+ return memoryUsage(await client.memoryUsage({}));
774
779
  }
775
780
  async setDownloadsAllowed({ allowed }) {
776
781
  const { client } = await this._ensure();
@@ -952,9 +957,7 @@ export class RemoteHarness extends EventEmitter {
952
957
  memoryBytes: memoryBytes || undefined,
953
958
  label: label || undefined,
954
959
  taskType: addonTaskType(row.type),
955
- fit: (fit || undefined),
956
- fitBasis: (fitBasis || undefined),
957
- fitEvidence: (fitEvidence || undefined)
960
+ fit: (fit || undefined)
958
961
  }));
959
962
  }
960
963
  async deleteModel(name) {
@@ -1019,6 +1022,9 @@ export class RemoteHarness extends EventEmitter {
1019
1022
  if (response.hostRunLog === true) {
1020
1023
  capability.hostRunLog = true;
1021
1024
  }
1025
+ if (response.mobileMemoryCap === true) {
1026
+ capability.mobileMemoryCap = true;
1027
+ }
1022
1028
  if (response.hostRunLogVersion && response.hostRunLogVersion > 0) {
1023
1029
  capability.hostRunLogVersion = response.hostRunLogVersion;
1024
1030
  }