@qvac/harness 1.0.0-rc.14 → 1.0.0-rc.16

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 (91) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +36 -6
  3. package/dist-lib/index.d.ts +2 -0
  4. package/dist-lib/index.js +2 -1
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +20 -1
  6. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +2 -0
  7. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +5 -2
  8. package/dist-lib/lib/capabilities/completion-engine/driver.js +15 -0
  9. package/dist-lib/lib/capabilities/completion-engine/engine.js +23 -39
  10. package/dist-lib/lib/capabilities/completion-engine/loop.js +2 -1
  11. package/dist-lib/lib/capabilities/completion-engine/operations.js +1 -0
  12. package/dist-lib/lib/capabilities/completion-engine/round.js +14 -6
  13. package/dist-lib/lib/contract/completion.d.ts +6 -0
  14. package/dist-lib/lib/contract/models.d.ts +1 -1
  15. package/dist-lib/lib/contract/ocr.d.ts +9 -0
  16. package/dist-lib/lib/contract/ocr.js +1 -0
  17. package/dist-lib/lib/contract/run.d.ts +2 -0
  18. package/dist-lib/lib/helpers/goal-check.d.ts +26 -0
  19. package/dist-lib/lib/helpers/goal-check.js +248 -22
  20. package/dist-lib/lib/helpers/spawn-path.d.ts +1 -0
  21. package/dist-lib/lib/helpers/spawn-path.js +2 -1
  22. package/dist-lib/lib/machine/completion/actions/completion.d.ts +3 -2
  23. package/dist-lib/lib/machine/completion/actions/completion.js +65 -15
  24. package/dist-lib/lib/machine/completion/actions/tools.js +47 -6
  25. package/dist-lib/lib/machine/completion/context.js +5 -1
  26. package/dist-lib/lib/machine/completion/implementations.d.ts +1 -0
  27. package/dist-lib/lib/machine/completion/implementations.js +7 -0
  28. package/dist-lib/lib/machine/completion/machine.d.ts +4 -1
  29. package/dist-lib/lib/machine/completion/machine.js +10 -1
  30. package/dist-lib/lib/machine/completion/rules.d.ts +3 -1
  31. package/dist-lib/lib/machine/completion/rules.js +25 -4
  32. package/dist-lib/lib/machine/completion/types.d.ts +16 -0
  33. package/dist-lib/lib/machine/index.d.ts +6 -1
  34. package/dist-lib/lib/machine/index.js +2 -0
  35. package/dist-lib/lib/models/gpu-selection.d.ts +6 -1
  36. package/dist-lib/lib/models/gpu-selection.js +29 -5
  37. package/dist-lib/lib/models/model-pool.js +1 -2
  38. package/dist-lib/lib/office/engine/pptx/presentation.js +10 -5
  39. package/dist-lib/lib/plugins/registry.d.ts +2 -0
  40. package/dist-lib/lib/serve.js +5 -34
  41. package/dist-lib/lib/sidecar/index.js +1 -1
  42. package/dist-lib/lib/skills-host/index.d.ts +1 -1
  43. package/dist-lib/lib/skills-host/index.js +3 -2
  44. package/dist-lib/lib/spawn.d.ts +1 -0
  45. package/dist-lib/lib/tools/exec/runner.d.ts +4 -0
  46. package/dist-lib/lib/tools/exec/runner.js +20 -3
  47. package/dist-lib/lib/tools/files/read-file.js +3 -3
  48. package/dist-lib/lib/tools/fs/document-text.d.ts +7 -1
  49. package/dist-lib/lib/tools/fs/document-text.js +9 -2
  50. package/dist-lib/lib/tools/office.js +1 -0
  51. package/dist-lib/lib/tools/operations/builders.d.ts +4 -3
  52. package/dist-lib/lib/tools/operations/builders.js +41 -3
  53. package/dist-lib/lib/tools/operations/calendar-range.d.ts +16 -0
  54. package/dist-lib/lib/tools/operations/calendar-range.js +40 -0
  55. package/dist-lib/lib/tools/operations/compile.js +4 -2
  56. package/dist-lib/lib/tools/operations/manifest.d.ts +4 -0
  57. package/dist-lib/lib/tools/pdf/build.d.ts +11 -1
  58. package/dist-lib/lib/tools/pdf/build.js +52 -16
  59. package/dist-lib/lib/tools/pdf/recognize.d.ts +13 -0
  60. package/dist-lib/lib/tools/pdf/recognize.js +58 -0
  61. package/dist-lib/lib/tools/pdf.js +18 -4
  62. package/dist-lib/lib/tools/skills/overlay-watch.d.ts +2 -2
  63. package/dist-lib/lib/tools/skills/overlay-watch.js +4 -3
  64. package/dist-lib/lib/wire.js +9 -3
  65. package/dist-lib/plugins/image/index.js +5 -5
  66. package/dist-lib/plugins/music/index.js +4 -4
  67. package/dist-lib/plugins/ocr/bmp.d.ts +2 -0
  68. package/dist-lib/plugins/ocr/bmp.js +27 -0
  69. package/dist-lib/plugins/ocr/index.d.ts +12 -0
  70. package/dist-lib/plugins/ocr/index.js +18 -0
  71. package/dist-lib/plugins/ocr/ocr-runtime.d.ts +23 -0
  72. package/dist-lib/plugins/ocr/ocr-runtime.js +82 -0
  73. package/dist-lib/plugins/ocr/reading-order.d.ts +5 -0
  74. package/dist-lib/plugins/ocr/reading-order.js +71 -0
  75. package/dist-lib/plugins/sandbox-linux/index.js +2 -2
  76. package/dist-lib/plugins/sandbox-macos/index.js +2 -2
  77. package/dist-lib/plugins/sandbox-vm/index.d.ts +2 -1
  78. package/dist-lib/plugins/sandbox-vm/index.js +2 -2
  79. package/dist-lib/plugins/sandbox-vm/vm-shell.d.ts +3 -1
  80. package/dist-lib/plugins/sandbox-vm/vm-shell.js +45 -16
  81. package/dist-lib/plugins/sandbox-windows/index.js +2 -2
  82. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  83. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  84. package/package.json +14 -5
  85. package/scripts/addon-externals.cjs +3 -0
  86. package/worker/harness-sidecar.mjs +5 -0
  87. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +0 -20
  88. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +0 -110
  89. package/dist-lib/lib/helpers/input-budget.d.ts +0 -8
  90. package/dist-lib/lib/helpers/input-budget.js +0 -9
  91. package/patches/localwatch@1.4.3.patch +0 -13
@@ -1,7 +1,7 @@
1
1
  import { activate, applyHistorySplice, applySplice, cutOffMessage, recordTool, retainFailureResults, settledSince } from '../rules.js';
2
2
  import { failureResultRef, storeFailureResult, toolDeniedResult } from '../../../helpers/failure-result.js';
3
3
  import { applyPreparation } from './completion.js';
4
- import { asksChecks, existenceOnly, mergeChecks } from '../../../helpers/goal-check.js';
4
+ import { deliverableChecked, existenceOnly, MAX_GOAL_CHECKS, MAX_PROVING, mergeChecks, runsCode, runsCodeCheck, runsDeliverable, runsScript, samePath, sourceFile } from '../../../helpers/goal-check.js';
5
5
  export function resolveTools({ context, params }) {
6
6
  return {
7
7
  toolQueue: [...params.calls],
@@ -215,7 +215,7 @@ function applyToolResult(context, payload, call) {
215
215
  metrics: recordTool(context, call, payload.durationMs),
216
216
  activated: activate(context.activated, payload.activate ? [payload.activate] : []),
217
217
  plan: payload.plan ?? context.plan,
218
- goal: applyChecks(adoptProof(context.goal, payload.proved), payload.checked),
218
+ goal: applyChecks(adoptProof(adoptRun(addProving(context.goal, payload.wrote), payload.ran), payload.proved), payload.checked),
219
219
  planMode: context.planMode && payload.leftPlanMode !== true,
220
220
  pendingCall: null,
221
221
  approval: { status: 'idle', key: null },
@@ -289,6 +289,37 @@ export function rejectPlanModeWrite({ params }) {
289
289
  }
290
290
  };
291
291
  }
292
+ function addProving(goal, wrote) {
293
+ if (!goal || !wrote) {
294
+ return goal;
295
+ }
296
+ const written = wrote.map(({ path }) => path);
297
+ const checks = goal.checks.map((check) => runsScript(check.name, written) ? { ...check, passed: false, output: null } : check);
298
+ const edited = editCode(goal, written);
299
+ const changed = wrote.filter((write) => write.proving !== undefined);
300
+ if (!changed.length) {
301
+ return { ...goal, ...edited, checks };
302
+ }
303
+ const kept = (goal.proving ?? []).filter((path) => !changed.some((write) => samePath(write.path, path)));
304
+ const added = changed.filter((write) => write.proving).map(({ path }) => path);
305
+ return { ...goal, ...edited, checks, proving: [...kept, ...added].slice(-MAX_PROVING) };
306
+ }
307
+ function editCode(goal, written) {
308
+ const code = written.filter(sourceFile);
309
+ if (!code.length) {
310
+ return {};
311
+ }
312
+ const edited = code.reduce((list, path) => [...list.filter((known) => !samePath(known, path)), path], goal.edited ?? []);
313
+ return { edited: edited.slice(-MAX_PROVING), proof: undefined };
314
+ }
315
+ function adoptRun(goal, ran) {
316
+ if (!goal?.edited?.length || !ran) {
317
+ return goal;
318
+ }
319
+ const proof = runsCode(ran, goal.edited) ??
320
+ runsCodeCheck(ran, goal.checks.map((check) => check.name));
321
+ return proof ? { ...goal, proof } : goal;
322
+ }
292
323
  function applyChecks(goal, checked) {
293
324
  if (!goal || !checked) {
294
325
  return goal;
@@ -299,10 +330,15 @@ function applyChecks(goal, checked) {
299
330
  };
300
331
  }
301
332
  function adoptProof(goal, proved) {
302
- if (!goal ||
303
- !proved ||
304
- !asksChecks(goal) ||
305
- !existenceOnly(goal.checks.map((check) => check.name))) {
333
+ if (!goal || !proved) {
334
+ return goal;
335
+ }
336
+ if (goal.named) {
337
+ return goal.checks.length < MAX_GOAL_CHECKS && runsOutput(goal, proved.name)
338
+ ? { ...goal, checks: [...goal.checks, proved] }
339
+ : goal;
340
+ }
341
+ if (!goal.checkable || !existenceOnly(goal.checks.map((check) => check.name))) {
306
342
  return goal;
307
343
  }
308
344
  const names = mergeChecks(goal.checks.map((check) => check.name), [proved.name]);
@@ -315,3 +351,8 @@ function adoptProof(goal, proved) {
315
351
  named: true
316
352
  };
317
353
  }
354
+ function runsOutput(goal, name) {
355
+ return (!!goal.deliverable &&
356
+ !deliverableChecked(goal) &&
357
+ runsDeliverable(name, goal.deliverable, goal.proving ?? []));
358
+ }
@@ -1,4 +1,6 @@
1
+ import { existenceOnly, pathsOf } from '../../helpers/goal-check.js';
1
2
  export function emptyCompletionContext(opts) {
3
+ const existence = !opts.goal?.checksProve && existenceOnly(opts.goal?.checks ?? []);
2
4
  return {
3
5
  runId: opts.runId ?? '',
4
6
  policy: opts.policy,
@@ -67,7 +69,9 @@ export function emptyCompletionContext(opts) {
67
69
  turns: 0,
68
70
  status: 'open',
69
71
  checks: (opts.goal.checks ?? []).map((name) => ({ name, passed: false, output: null })),
70
- named: (opts.goal.checksProve && Boolean(opts.goal.checks?.length)) || undefined
72
+ named: (opts.goal.checksProve && Boolean(opts.goal.checks?.length)) || undefined,
73
+ review: 'due',
74
+ deliverable: existence ? pathsOf(opts.goal.checks ?? []) : undefined
71
75
  }
72
76
  : null
73
77
  };
@@ -100,6 +100,7 @@ export declare const completionActions: {
100
100
  cause?: import("../../helpers/engine-error.ts").ErrorCause;
101
101
  }, never, never, never, never, never>;
102
102
  markTimeUp: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, never>;
103
+ markHalfTime: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, never>;
103
104
  recordPause: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, never>;
104
105
  recordRecovery: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, never>;
105
106
  resumeRun: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, never>;
@@ -133,6 +133,7 @@ export const completionActions = {
133
133
  requestApproval: assignAction(requestApproval),
134
134
  failCompletion: assignAction(failCompletion),
135
135
  markTimeUp: assignAction(() => ({ timeUp: true })),
136
+ markHalfTime: assignAction(() => ({ halfTime: true })),
136
137
  recordPause: assignAction(({ context }) => ({
137
138
  pauseCount: context.pauseCount + 1
138
139
  })),
@@ -222,6 +223,12 @@ function goalAction(action) {
222
223
  if (goal.checks.length) {
223
224
  event.checks = goal.checks.map(({ name }) => name);
224
225
  }
226
+ if (goal.proof) {
227
+ event.proof = goal.proof;
228
+ }
229
+ if (goal.status === 'met' && goal.cases) {
230
+ event.cases = true;
231
+ }
225
232
  enqueue.emit(event);
226
233
  });
227
234
  }
@@ -175,6 +175,9 @@ declare const createCompletionMachineImplementation: (context?: CompletionContex
175
175
  } | {
176
176
  type: "markGoalStalled";
177
177
  params: undefined;
178
+ } | {
179
+ type: "markHalfTime";
180
+ params: undefined;
178
181
  } | {
179
182
  type: "markTimeUp";
180
183
  params: undefined;
@@ -426,7 +429,7 @@ declare const createCompletionMachineImplementation: (context?: CompletionContex
426
429
  } | {
427
430
  type: "toolRejected";
428
431
  params: unknown;
429
- }, "deadline", "done" | "failed" | "paused" | "pausing" | "resuming" | {
432
+ }, "deadline" | "halfTime", "done" | "failed" | "paused" | "pausing" | "resuming" | {
430
433
  active: "answering" | "finishing" | "generating" | "idle" | "prepareChecking" | "prepareRunning" | "preparing" | "resolving" | "retrieving" | "round" | "searching" | "wrapping" | {
431
434
  tools: "approving" | "batching" | "executing" | "inspecting" | "rejecting" | "selecting";
432
435
  };
@@ -98,6 +98,12 @@ const createCompletionMachineImplementation = (context, now = noClock) => setup(
98
98
  deadline: ({ context }) => {
99
99
  const deadline = context.durable?.runBudget.deadlineMs;
100
100
  return deadline === undefined ? MAX_DELAY : clamp(deadline - now());
101
+ },
102
+ halfTime: ({ context }) => {
103
+ const budget = context.durable?.runBudget;
104
+ return budget?.totalMs === undefined
105
+ ? MAX_DELAY
106
+ : clamp(budget.deadlineMs - budget.totalMs / 2 - now());
101
107
  }
102
108
  }
103
109
  }).createMachine({
@@ -139,7 +145,10 @@ const createCompletionMachineImplementation = (context, now = noClock) => setup(
139
145
  states: {
140
146
  active: {
141
147
  initial: 'idle',
142
- after: { deadline: { actions: 'markTimeUp' } },
148
+ after: {
149
+ deadline: { actions: 'markTimeUp' },
150
+ halfTime: { actions: 'markHalfTime' }
151
+ },
143
152
  on: {
144
153
  PAUSE: { target: '#completion.pausing', actions: 'recordPause' },
145
154
  FAIL: [
@@ -10,7 +10,9 @@ export declare const MAX_UNCHANGED_RESULTS = 3;
10
10
  export declare const MAX_ROUND_REPEATS = 3;
11
11
  export declare const MAX_ROUND_CALLS = 32;
12
12
  export declare function nudgeWithPlan(nudge: string, plan: readonly PlanStep[]): string;
13
- export declare function goalMet({ plan, goal }: Readonly<CompletionContext>): boolean;
13
+ export declare function goalMet(context: Readonly<CompletionContext>): boolean;
14
+ export declare function casesDue(context: Readonly<CompletionContext>): boolean;
15
+ export declare function checksMet({ plan, goal }: Readonly<CompletionContext>): boolean;
14
16
  export declare function nudgeWithChecks(nudge: string, checks: readonly GoalCheck[], unnamed?: boolean): string;
15
17
  export declare function goalTokensLeft({ goal, metrics }: Readonly<CompletionContext>): boolean;
16
18
  export declare function goalStalled({ outcome }: Readonly<CompletionContext>): boolean;
@@ -1,5 +1,5 @@
1
1
  import { isFailureResultReference } from '../../helpers/failure-result.js';
2
- import { asksChecks, GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../helpers/goal-check.js';
2
+ import { asksChecks, codeUnrun, deliverableChecked, GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../helpers/goal-check.js';
3
3
  export function runsUnasked(facts) {
4
4
  if (facts.permission === 'ask')
5
5
  return false;
@@ -33,9 +33,29 @@ function isDone(step) {
33
33
  function planDone(plan) {
34
34
  return plan.length > 0 && plan.every(isDone);
35
35
  }
36
- export function goalMet({ plan, goal }) {
36
+ export function goalMet(context) {
37
+ return checksMet(context) && !reviewPending(context.goal) && !casesOpen(context);
38
+ }
39
+ export function casesDue(context) {
40
+ return checksMet(context) && !reviewPending(context.goal) && casesOpen(context);
41
+ }
42
+ function casesOpen(context) {
43
+ return !!context.goal?.checkable && !context.goal.cases && halfLeft(context);
44
+ }
45
+ function halfLeft({ halfTime, round, policy, goal, metrics }) {
46
+ return (!halfTime &&
47
+ (round + 1) * 2 < policy.maxToolRounds &&
48
+ (!goal || goal.tokens === null || metrics.tokens * 2 < goal.tokens));
49
+ }
50
+ export function checksMet({ plan, goal }) {
37
51
  const checks = goal?.checks ?? [];
38
- return planDone(plan) && !(goal && asksChecks(goal)) && checks.every((check) => check.passed);
52
+ return (planDone(plan) &&
53
+ !(goal && asksChecks(goal)) &&
54
+ checks.every((check) => check.passed) &&
55
+ (!goal || (deliverableChecked(goal) && !codeUnrun(goal))));
56
+ }
57
+ function reviewPending(goal) {
58
+ return !!goal?.checkable && (goal.review === 'due' || goal.review === 'asked');
39
59
  }
40
60
  export function nudgeWithChecks(nudge, checks, unnamed) {
41
61
  if (!checks.length) {
@@ -127,7 +147,8 @@ const ROUND_STATS = [
127
147
  'generatedTokens',
128
148
  'promptTokensPerSecond',
129
149
  'tokensPerSecond',
130
- 'timeToFirstToken'
150
+ 'timeToFirstToken',
151
+ 'avgConcurrentSeq'
131
152
  ];
132
153
  function roundSpeed(round, { stats, stopReason, durationMs, overflows, reasoningDeltas, keyed }) {
133
154
  const speed = { round, durationMs: durationMs ?? 0 };
@@ -8,6 +8,7 @@ export interface CompletionStats {
8
8
  tokensPerSecond?: number | undefined;
9
9
  promptTokens?: number | undefined;
10
10
  cacheTokens?: number | undefined;
11
+ avgConcurrentSeq?: number | undefined;
11
12
  contextBoundary?: boolean | undefined;
12
13
  }
13
14
  export interface EngineEvent {
@@ -22,6 +23,8 @@ export interface EngineEvent {
22
23
  status?: GoalStatus;
23
24
  turn?: number;
24
25
  checks?: string[];
26
+ proof?: string;
27
+ cases?: true;
25
28
  context?: TurnContext;
26
29
  }
27
30
  export interface EngineFacts extends Record<string, unknown> {
@@ -158,6 +161,11 @@ export interface ToolDonePayload {
158
161
  leftPlanMode?: boolean;
159
162
  checked?: GoalCheck[];
160
163
  proved?: GoalCheck;
164
+ wrote?: {
165
+ path: string;
166
+ proving?: boolean;
167
+ }[];
168
+ ran?: string;
161
169
  }
162
170
  export interface BatchDonePayload {
163
171
  history?: HistorySplice;
@@ -283,6 +291,13 @@ export interface GoalState {
283
291
  checkable?: boolean;
284
292
  named?: boolean;
285
293
  stalled?: true;
294
+ review?: 'due' | 'asked' | 'done';
295
+ deliverable?: string[];
296
+ proving?: string[];
297
+ edited?: string[];
298
+ proof?: string;
299
+ reviewAsks?: number;
300
+ cases?: true;
286
301
  }
287
302
  export interface QueuedInput {
288
303
  id?: string;
@@ -294,6 +309,7 @@ export interface CompletionContext {
294
309
  runId: string;
295
310
  policy: RunPolicy;
296
311
  timeUp: boolean;
312
+ halfTime?: true;
297
313
  pauseCount: number;
298
314
  durable: EngineFacts | null;
299
315
  recovery: Operation | undefined;
@@ -1,3 +1,4 @@
1
+ import { goalStatus } from './completion/actions/completion.ts';
1
2
  import { emptyCompletionContext } from './completion/context.ts';
2
3
  import { atContextBoundary, cutOffMessage, cutShort, runsUnasked } from './completion/rules.ts';
3
4
  import { completionMachineDefinition, transitionName } from './definition.ts';
@@ -179,6 +180,9 @@ export declare class CompletionMachine {
179
180
  } | {
180
181
  type: "markGoalStalled";
181
182
  params: undefined;
183
+ } | {
184
+ type: "markHalfTime";
185
+ params: undefined;
182
186
  } | {
183
187
  type: "markTimeUp";
184
188
  params: undefined;
@@ -430,7 +434,7 @@ export declare class CompletionMachine {
430
434
  } | {
431
435
  type: "toolRejected";
432
436
  params: unknown;
433
- }, "deadline", "done" | "failed" | "paused" | "pausing" | "resuming" | {
437
+ }, "deadline" | "halfTime", "done" | "failed" | "paused" | "pausing" | "resuming" | {
434
438
  active: "answering" | "finishing" | "generating" | "idle" | "prepareChecking" | "prepareRunning" | "preparing" | "resolving" | "retrieving" | "round" | "searching" | "wrapping" | {
435
439
  tools: "approving" | "batching" | "executing" | "inspecting" | "rejecting" | "selecting";
436
440
  };
@@ -480,6 +484,7 @@ export declare class CompletionMachine {
480
484
  }, import("xstate").MetaObject>;
481
485
  static definition: typeof completionMachineDefinition;
482
486
  static emptyContext: typeof emptyCompletionContext;
487
+ static goalStatus: typeof goalStatus;
483
488
  static transitionName: typeof transitionName;
484
489
  static runsUnasked: typeof runsUnasked;
485
490
  static cutOffMessage: typeof cutOffMessage;
@@ -1,3 +1,4 @@
1
+ import { goalStatus } from './completion/actions/completion.js';
1
2
  import { PLAN_MODE_REFUSAL } from './completion/actions/tools.js';
2
3
  import { emptyCompletionContext } from './completion/context.js';
3
4
  import { createCompletionMachine } from './completion/machine.js';
@@ -10,6 +11,7 @@ export class CompletionMachine {
10
11
  static create = createCompletionMachine;
11
12
  static definition = completionMachineDefinition;
12
13
  static emptyContext = emptyCompletionContext;
14
+ static goalStatus = goalStatus;
13
15
  static transitionName = transitionName;
14
16
  static runsUnasked = runsUnasked;
15
17
  static cutOffMessage = cutOffMessage;
@@ -1,3 +1,8 @@
1
1
  export type MainGpuProbe = () => Promise<string | undefined>;
2
- export declare function resolveMainGpu(): Promise<string | undefined>;
2
+ interface GpuHost {
3
+ readonly platform?: string;
4
+ readonly root?: string;
5
+ }
6
+ export declare function resolveMainGpu(host?: GpuHost): Promise<string | undefined>;
3
7
  export declare function resetMainGpuCache(): void;
8
+ export {};
@@ -1,12 +1,15 @@
1
1
  import { promises } from 'fs';
2
2
  import { platform } from 'os';
3
+ import path from 'path';
4
+ const NVIDIA_VENDOR = '0x10de';
3
5
  let cachedDedicated = null;
4
- export async function resolveMainGpu() {
5
- if (platform() !== 'linux')
6
+ export async function resolveMainGpu(host = {}) {
7
+ if ((host.platform ?? platform()) !== 'linux')
6
8
  return undefined;
7
9
  if (cachedDedicated !== null)
8
10
  return cachedDedicated;
9
- if (await hasNvidiaGpu()) {
11
+ const root = host.root ?? '/';
12
+ if ((await hasNvidiaGpu(root)) && (await hasOtherGpu(root))) {
10
13
  cachedDedicated = 'dedicated';
11
14
  return cachedDedicated;
12
15
  }
@@ -15,12 +18,33 @@ export async function resolveMainGpu() {
15
18
  export function resetMainGpuCache() {
16
19
  cachedDedicated = null;
17
20
  }
18
- async function hasNvidiaGpu() {
21
+ async function hasNvidiaGpu(root) {
19
22
  try {
20
- const entries = await promises.readdir('/proc/driver/nvidia/gpus');
23
+ const entries = await promises.readdir(path.join(root, 'proc/driver/nvidia/gpus'));
21
24
  return entries.length > 0;
22
25
  }
23
26
  catch {
24
27
  return false;
25
28
  }
26
29
  }
30
+ async function hasOtherGpu(root) {
31
+ const drm = path.join(root, 'sys/class/drm');
32
+ let entries;
33
+ try {
34
+ entries = await promises.readdir(drm);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ const cards = entries.filter((name) => /^card\d+$/.test(name));
40
+ const vendors = await Promise.all(cards.map((card) => vendorOf(path.join(drm, card, 'device/vendor'))));
41
+ return vendors.some((vendor) => vendor !== '' && vendor !== NVIDIA_VENDOR);
42
+ }
43
+ async function vendorOf(file) {
44
+ try {
45
+ return (await promises.readFile(file, 'utf8')).trim().toLowerCase();
46
+ }
47
+ catch {
48
+ return '';
49
+ }
50
+ }
@@ -438,8 +438,7 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
438
438
  gpu_layers: deviceConfig.gpuLayers,
439
439
  'main-gpu': mainGpu,
440
440
  openclCacheDir: openclCache || undefined,
441
- threads: resolved.llama?.threads ?? placement?.threads,
442
- 'cpu-mask': placement?.mask
441
+ threads: resolved.llama?.threads ?? placement?.threads
443
442
  });
444
443
  const pending = { key, model, modelSrc, modelType: 'llamacpp-completion' };
445
444
  const chosen = contextSize(model, modelSrc, { opts: resolved, deviceConfig });
@@ -765,11 +765,10 @@ export class Presentation {
765
765
  checkPlacement(opts);
766
766
  const ratio = info.height / info.width;
767
767
  let { width, height } = opts;
768
- if (width === undefined && height === undefined) {
769
- const natural = { width: info.width * EMU_PER_PIXEL, height: info.height * EMU_PER_PIXEL };
770
- const scale = Math.min(1, area.width / natural.width, area.height / natural.height);
771
- width = Math.round(natural.width * scale);
772
- height = Math.round(natural.height * scale);
768
+ const sized = width !== undefined || height !== undefined;
769
+ if (!sized) {
770
+ width = info.width * EMU_PER_PIXEL;
771
+ height = info.height * EMU_PER_PIXEL;
773
772
  }
774
773
  else if (height === undefined) {
775
774
  height = Math.round((width ?? 0) * ratio);
@@ -777,6 +776,12 @@ export class Presentation {
777
776
  else if (width === undefined) {
778
777
  width = Math.round(height / ratio);
779
778
  }
779
+ const placed = opts.x !== undefined || opts.y !== undefined;
780
+ if (width && height && !(sized && placed)) {
781
+ const scale = Math.min(1, area.width / width, area.height / height);
782
+ width = Math.round(width * scale);
783
+ height = Math.round(height * scale);
784
+ }
780
785
  if (!width || !height) {
781
786
  throw new DocsError('INVALID_BOX', 'the picture would have no visible size');
782
787
  }
@@ -1,5 +1,6 @@
1
1
  import type { AddonLoaders, ToolDefinition, ToolExecuteContext, ToolFetch } from '../contract/index.ts';
2
2
  import type { KnowledgeService } from '../contract/knowledge.ts';
3
+ import type { OcrService } from '../contract/ocr.ts';
3
4
  import type { SandboxService } from '../contract/sandbox.ts';
4
5
  import type { EgressProxyService } from '../contract/egress-proxy.ts';
5
6
  import type { EmbedHost, ModelHost } from '../contract/models.ts';
@@ -15,6 +16,7 @@ declare module './context.ts' {
15
16
  models: ModelHost;
16
17
  embed: EmbedHost;
17
18
  knowledge: KnowledgeService;
19
+ ocr: OcrService;
18
20
  sandbox: SandboxService;
19
21
  'egress-proxy': EgressProxyService;
20
22
  }
@@ -8,7 +8,6 @@ import { bindApi } from '../spec/bind.js';
8
8
  import HRPC from '../spec/hrpc/index.js';
9
9
  import { encode } from '../spec/hrpc/messages.js';
10
10
  import { checkGoal, checkMaxToolRounds } from './capabilities/tool-turns.js';
11
- import { acceptsInput, inputBytes } from './helpers/input-budget.js';
12
11
  import { isCapability } from './capabilities/invoke.js';
13
12
  import { CUSTOM_TASK_TYPES } from './models/model-catalog.js';
14
13
  import { unsupportedKvCacheDeletion } from './capabilities/kv-cache.js';
@@ -650,19 +649,7 @@ function completion(harness) {
650
649
  const pendingQuestion = new Map();
651
650
  const pendingDrive = new Map();
652
651
  const pendingRunLog = new Map();
653
- const inputQueue = pushQueue();
654
- let queuedInputCount = 0;
655
- let queuedInputBytes = 0;
656
- let inputLimitNotified = false;
657
- const input = {
658
- async *[Symbol.asyncIterator]() {
659
- for await (const item of inputQueue) {
660
- queuedInputCount--;
661
- queuedInputBytes -= inputBytes(item);
662
- yield item;
663
- }
664
- }
665
- };
652
+ const input = pushQueue();
666
653
  const controller = new AbortController();
667
654
  const rounds = new RoundPort((event) => events.push(event));
668
655
  let calls = 0;
@@ -700,7 +687,7 @@ function completion(harness) {
700
687
  }
701
688
  pendingRunLog.clear();
702
689
  rounds.close();
703
- inputQueue.end();
690
+ input.end();
704
691
  events.end();
705
692
  };
706
693
  duplex.on('close', gone);
@@ -813,27 +800,11 @@ function completion(harness) {
813
800
  return;
814
801
  }
815
802
  if (frame.type === 'steer' || frame.type === 'follow-up') {
816
- const item = {
803
+ void input.push({
817
804
  mode: frame.type,
818
805
  text: frame.messages?.[0]?.content ?? '',
819
806
  id: frame.callId || undefined
820
- };
821
- const bytes = inputBytes(item);
822
- if (!acceptsInput(queuedInputCount, queuedInputBytes, item)) {
823
- if (!inputLimitNotified) {
824
- inputLimitNotified = true;
825
- void events.push({
826
- type: 'input-rejected',
827
- text: 'Input queue limit exceeded; one or more inputs were rejected'
828
- });
829
- }
830
- }
831
- else {
832
- inputLimitNotified = false;
833
- queuedInputCount++;
834
- queuedInputBytes += bytes;
835
- void inputQueue.push(item);
836
- }
807
+ });
837
808
  return;
838
809
  }
839
810
  if (frame.type === 'run-log-result') {
@@ -1099,7 +1070,7 @@ function completion(harness) {
1099
1070
  await text.flush();
1100
1071
  events.push({ type: 'error', message: errorMessage(err) });
1101
1072
  }
1102
- inputQueue.end();
1073
+ input.end();
1103
1074
  events.push({ type: 'done' });
1104
1075
  HarnessLog.debug('wire end', { produced, frames });
1105
1076
  events.end();
@@ -87,7 +87,7 @@ export class HarnessSidecar {
87
87
  pluginMode: 'dynamic',
88
88
  plugins: admit(plugins, log)
89
89
  });
90
- await harness.ready().catch((err) => log.error(SCOPE, 'harness failed to open', err));
90
+ await harness.ready();
91
91
  await addUserPlugins(harness, log);
92
92
  await addHostModule(harness, log);
93
93
  sealAddons();
@@ -34,7 +34,7 @@ export declare class SkillsHost {
34
34
  constructor(opts: SkillsHostOptions);
35
35
  get names(): string[];
36
36
  open(): Promise<void>;
37
- close(): void;
37
+ close(): Promise<void>;
38
38
  publish(skills: readonly SkillReadiness[]): void;
39
39
  setCredentials(entries: ReadonlyArray<CredentialEntry>): void;
40
40
  setSkillSettings(entries: ReadonlyArray<SkillSettingEntry>): void;
@@ -44,9 +44,10 @@ export class SkillsHost {
44
44
  await this._reload();
45
45
  await this._watch();
46
46
  }
47
- close() {
48
- this._watcher?.stop();
47
+ async close() {
48
+ const watcher = this._watcher;
49
49
  this._watcher = null;
50
+ await watcher?.stop();
50
51
  }
51
52
  publish(skills) {
52
53
  this._readiness = new Map(skills.map((readiness) => [readiness.skill, readiness]));
@@ -49,6 +49,7 @@ export interface HarnessPluginOptions {
49
49
  mcp?: {
50
50
  servers?: HarnessMcpServer[];
51
51
  };
52
+ ocr?: boolean;
52
53
  [name: string]: unknown;
53
54
  }
54
55
  export interface HarnessChildOptions {
@@ -14,6 +14,8 @@ export interface RunCommandOptions {
14
14
  readonly platform?: string;
15
15
  }
16
16
  export declare const DEFAULT_TIMEOUT_MS = 120000;
17
+ export declare const STOP_GRACE_MS = 2000;
18
+ export declare const TIMED_OUT_EXIT_CODE = 124;
17
19
  export declare const MAX_OUTPUT_CHARS = 8192;
18
20
  export declare const MAX_OUTPUT_CHARS_LIMIT = 65536;
19
21
  interface CapturedOutput {
@@ -27,6 +29,8 @@ export declare function capOutput(text: string, limit: number): string;
27
29
  export declare function appendOutput(output: CapturedOutput, chunk: Buffer | string): void;
28
30
  export declare function formatOutput(output: CapturedOutput, locator?: string | null): string;
29
31
  export declare function createCapturedOutput(limit: number, sink?: SpillSink): CapturedOutput;
32
+ export declare function timeoutNote(timeoutMs: number, printed: boolean): string;
33
+ export declare function withNote(stderr: string, note: string): string;
30
34
  export interface StartCommandOptions {
31
35
  readonly cwd?: string;
32
36
  readonly spawn: SpawnFn;
@@ -1,10 +1,10 @@
1
1
  import b4a from 'b4a';
2
2
  import process from 'process';
3
- import { HarnessError } from '../../errors.js';
4
3
  import { headTail, joinHeadTail } from '../../helpers/head-tail.js';
5
4
  import { AbortedError } from '../../helpers/race-abort.js';
6
5
  export const DEFAULT_TIMEOUT_MS = 120_000;
7
- const STOP_GRACE_MS = 2_000;
6
+ export const STOP_GRACE_MS = 2_000;
7
+ export const TIMED_OUT_EXIT_CODE = 124;
8
8
  export const MAX_OUTPUT_CHARS = 8_192;
9
9
  export const MAX_OUTPUT_CHARS_LIMIT = 65_536;
10
10
  export function capOutput(text, limit) {
@@ -27,6 +27,23 @@ export function formatOutput(output, locator) {
27
27
  export function createCapturedOutput(limit, sink) {
28
28
  return { limit, sink, head: '', tail: '', total: 0 };
29
29
  }
30
+ export function timeoutNote(timeoutMs, printed) {
31
+ const stopped = `command timed out after ${timeoutMs}ms and was stopped`;
32
+ return printed
33
+ ? `${stopped}; the output shown is what it printed before then`
34
+ : `${stopped}; no output reached exec in that time. A filter it pipes into (head, grep, sort) loses what it held when the command is stopped: send the output to a file, then head or tail the file. Otherwise it may loop over too much work or wait for input: try it on a small input that prints its progress`;
35
+ }
36
+ export function withNote(stderr, note) {
37
+ return stderr === '' || stderr.endsWith('\n') ? `${stderr}${note}` : `${stderr}\n${note}`;
38
+ }
39
+ function timedOut(timeoutMs, { stdout, stderr, files: [out, err] }) {
40
+ const note = timeoutNote(timeoutMs, stdout.total + stderr.total > 0);
41
+ return {
42
+ stdout: formatOutput(stdout, out),
43
+ stderr: withNote(formatOutput(stderr, err), note),
44
+ exitCode: TIMED_OUT_EXIT_CODE
45
+ };
46
+ }
30
47
  function terminateProcessTree(child, killProcess, signal = 'SIGTERM') {
31
48
  if (child.pid !== undefined && killProcess) {
32
49
  try {
@@ -109,7 +126,7 @@ export function runCommand(command, options) {
109
126
  };
110
127
  options.signal?.addEventListener('abort', onAbort, { once: true });
111
128
  const timer = setTimeout(() => {
112
- finish(() => reject(new HarnessError('COMMAND_TIMED_OUT', [timeoutMs])));
129
+ finish((files) => resolve(timedOut(timeoutMs, { stdout, stderr, files })));
113
130
  terminateProcessTree(child, options.killProcess);
114
131
  }, timeoutMs);
115
132
  child.stdout?.on('data', (chunk) => appendOutput(stdout, chunk));