@qvac/harness 1.0.0-rc.4 → 1.0.0-rc.6

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 (73) hide show
  1. package/CHANGELOG.md +115 -18
  2. package/dist-lib/index.d.ts +4 -1
  3. package/dist-lib/index.js +42 -1
  4. package/dist-lib/lib/capabilities/completion-engine/actors/inspecting.js +13 -3
  5. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +8 -1
  6. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +62 -36
  7. package/dist-lib/lib/capabilities/completion-engine/actors/resolving.js +11 -4
  8. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +20 -11
  9. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +10 -1
  10. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +7 -3
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +8 -17
  12. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.d.ts +1 -1
  13. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +12 -12
  14. package/dist-lib/lib/capabilities/completion-engine/driver.js +1 -2
  15. package/dist-lib/lib/capabilities/completion-engine/engine.d.ts +4 -1
  16. package/dist-lib/lib/capabilities/completion-engine/engine.js +14 -1
  17. package/dist-lib/lib/capabilities/completion-engine/index.d.ts +3 -1
  18. package/dist-lib/lib/capabilities/completion-engine/index.js +2 -0
  19. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  20. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +14 -1
  21. package/dist-lib/lib/capabilities/completion-engine/model-round.js +52 -0
  22. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -3
  23. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -5
  24. package/dist-lib/lib/capabilities/completion-engine/turns.js +29 -25
  25. package/dist-lib/lib/capabilities/sdk-tool.d.ts +9 -1
  26. package/dist-lib/lib/capabilities/sdk-tool.js +21 -2
  27. package/dist-lib/lib/capabilities/tool-plan.d.ts +4 -0
  28. package/dist-lib/lib/capabilities/tool-plan.js +15 -0
  29. package/dist-lib/lib/connect.js +16 -2
  30. package/dist-lib/lib/contract/completion.d.ts +8 -2
  31. package/dist-lib/lib/contract/drive.d.ts +4 -0
  32. package/dist-lib/lib/contract/drive.js +1 -0
  33. package/dist-lib/lib/contract/index.d.ts +2 -0
  34. package/dist-lib/lib/contract/managed-skills.d.ts +1 -0
  35. package/dist-lib/lib/contract/managed-skills.js +1 -0
  36. package/dist-lib/lib/contract/run.d.ts +8 -0
  37. package/dist-lib/lib/contract-types.d.ts +4 -1
  38. package/dist-lib/lib/errors.d.ts +4 -0
  39. package/dist-lib/lib/errors.js +6 -0
  40. package/dist-lib/lib/hardware/cpu-placement.d.ts +8 -0
  41. package/dist-lib/lib/hardware/cpu-placement.js +48 -0
  42. package/dist-lib/lib/helpers/goal-check.d.ts +2 -0
  43. package/dist-lib/lib/helpers/goal-check.js +18 -0
  44. package/dist-lib/lib/machine/completion/actions/completion.js +33 -13
  45. package/dist-lib/lib/machine/completion/context.js +3 -1
  46. package/dist-lib/lib/machine/completion/implementations.js +16 -4
  47. package/dist-lib/lib/machine/completion/machine.d.ts +2 -0
  48. package/dist-lib/lib/machine/completion/rules.d.ts +1 -1
  49. package/dist-lib/lib/machine/completion/rules.js +7 -8
  50. package/dist-lib/lib/machine/completion/types.d.ts +8 -1
  51. package/dist-lib/lib/machine/index.d.ts +2 -0
  52. package/dist-lib/lib/models/model-pool.d.ts +4 -0
  53. package/dist-lib/lib/models/model-pool.js +4 -1
  54. package/dist-lib/lib/prompt.d.ts +2 -1
  55. package/dist-lib/lib/prompt.js +12 -12
  56. package/dist-lib/lib/residency/completion-runtime.d.ts +9 -1
  57. package/dist-lib/lib/residency/completion-runtime.js +29 -26
  58. package/dist-lib/lib/residency/index.d.ts +4 -0
  59. package/dist-lib/lib/residency/index.js +6 -1
  60. package/dist-lib/lib/serve.js +12 -5
  61. package/dist-lib/lib/tools/http-request.js +1 -0
  62. package/dist-lib/lib/wire.js +5 -0
  63. package/dist-lib/plugins/mcp/server.js +1 -1
  64. package/dist-lib/plugins/obsidian/readiness.js +2 -2
  65. package/dist-lib/plugins/obsidian/vault-read.js +17 -16
  66. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  67. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  68. package/dist-lib/schema/harness.js +5 -2
  69. package/dist-lib/spec/hrpc/messages.js +19 -5
  70. package/dist-lib/spec/hyperschema/index.js +19 -5
  71. package/dist-lib/spec/hyperschema/schema.json +14 -0
  72. package/dist-lib/spec/hyperschema/types.d.ts +3 -1
  73. package/package.json +2 -2
@@ -26,6 +26,7 @@ import { asToolset } from './tools/toolsets.js';
26
26
  import { fromDownloadWire, fromKnowledgeHitWire, fromKnowledgeStatusWire, fromKnowledgeUpsertResultWire, fromWire, toKnowledgeUpsertWire, unpackVectors } from './wire.js';
27
27
  export const HARNESS_DIED = 'HARNESS_DIED';
28
28
  const PAUSE_GRACE_MS = 10_000;
29
+ const IN_PROCESS_ONLY_FIELDS = ['modelRound', 'roundCut'];
29
30
  export function connectHarness(transport, options = {}) {
30
31
  return new RemoteHarness(transport, options);
31
32
  }
@@ -116,6 +117,7 @@ export class RemoteHarness extends EventEmitter {
116
117
  : this._hop(context);
117
118
  }
118
119
  async *_hop(context) {
120
+ refuseInProcessOnly(context);
119
121
  const runId = context.runId ?? b4a.toHex(randomBytes(16));
120
122
  if (context.signal?.aborted) {
121
123
  yield { type: 'aborted', runId };
@@ -148,6 +150,9 @@ export class RemoteHarness extends EventEmitter {
148
150
  if (context.typedText !== undefined) {
149
151
  payload.typedText = context.typedText;
150
152
  }
153
+ if (context.replaysContext) {
154
+ payload.replaysContext = true;
155
+ }
151
156
  if (context.maxToolRounds !== undefined && context.maxToolRounds !== 0) {
152
157
  payload.maxToolRounds = checkMaxToolRounds(context.maxToolRounds);
153
158
  }
@@ -163,14 +168,16 @@ export class RemoteHarness extends EventEmitter {
163
168
  generationParams: context.generationParams,
164
169
  responseFormat: context.responseFormat,
165
170
  captureInferenceCalls: context.captureInferenceCalls,
166
- messages: context.messages?.map(({ role, content, attachments, toolCalls, toolCallId, name, id }) => ({
171
+ messages: context.messages?.map(({ role, content, attachments, toolCalls, toolCallId, name, id, context: added, sentAt }) => ({
167
172
  role,
168
173
  content,
169
174
  attachments: attachments?.map(({ path: file }) => ({ path: file })),
170
175
  toolCalls,
171
176
  toolCallId,
172
177
  name,
173
- id
178
+ id,
179
+ context: added,
180
+ sentAt
174
181
  })),
175
182
  toolConfigs: context.toolConfigs,
176
183
  grantedDirs: context.grantedDirs,
@@ -964,6 +971,13 @@ function died(message) {
964
971
  return Object.assign(new Error(message), { code: HARNESS_DIED });
965
972
  }
966
973
  const noop = () => { };
974
+ function refuseInProcessOnly(context) {
975
+ for (const field of IN_PROCESS_ONLY_FIELDS) {
976
+ if (context[field] !== undefined) {
977
+ throw new HarnessError('CAPABILITY_UNSUPPORTED', [field]);
978
+ }
979
+ }
980
+ }
967
981
  function abortable(promise, signal) {
968
982
  if (!signal)
969
983
  return promise;
@@ -8,7 +8,7 @@ import type { CliValidator } from '../tools/skills/cli-schema-types.ts';
8
8
  import type { UsageBreakdown } from '../capabilities/usage-breakdown.ts';
9
9
  import type { KnowledgeGrant } from './knowledge.ts';
10
10
  import type { AccessPolicy, CompiledPolicy } from './policy.ts';
11
- import type { GoalStatus, HistoryToolCall, HookRejection, Message, ResourceDescriptor, RoundSpeed, RunBackendUse, RunBudget, RunLifecycleEvent, RunOutcome, ToolActivityEvent, ToolCallDisplay, ToolDecision, ToolEffect, ToolSpeed, TrustedSource, TrustedSourceFacts } from './run.ts';
11
+ import type { GoalStatus, HistoryToolCall, HookRejection, Message, ResourceDescriptor, RoundSpeed, RunBackendUse, RunBudget, RunLifecycleEvent, RunOutcome, ToolActivityEvent, ToolCallDisplay, ToolDecision, ToolEffect, ToolSpeed, TrustedSource, TrustedSourceFacts, TurnContext } from './run.ts';
12
12
  export type { CliValidator, DriveRoot, LlmGenerationParams };
13
13
  export interface OutboundGuard {
14
14
  facts(origin: TrustedSourceFacts['origin'], text: string): TrustedSourceFacts;
@@ -311,6 +311,12 @@ export type InputEvent = {
311
311
  text: string;
312
312
  round: number;
313
313
  };
314
+ export type ContextEvent = {
315
+ type: 'context';
316
+ id?: string;
317
+ context: TurnContext;
318
+ round: number;
319
+ };
314
320
  export type InputRejectedEvent = {
315
321
  type: 'input-rejected';
316
322
  reason: string;
@@ -347,7 +353,7 @@ export interface InferenceTokens {
347
353
  cached?: number | undefined;
348
354
  timeToFirstToken?: number | undefined;
349
355
  }
350
- export type CompletionEvent = (RunLifecycleEvent | TextEvent | ToolCallEvent | ToolResultEvent | ToolActivityEvent | ErrorEvent | AbortedEvent | MetricsEvent | InferenceCallEvent | InferenceSentEvent | TransferEvent | InputEvent | InputRejectedEvent | GoalEvent | FoldEvent) & {
356
+ export type CompletionEvent = (RunLifecycleEvent | TextEvent | ToolCallEvent | ToolResultEvent | ToolActivityEvent | ErrorEvent | AbortedEvent | MetricsEvent | InferenceCallEvent | InferenceSentEvent | TransferEvent | InputEvent | ContextEvent | InputRejectedEvent | GoalEvent | FoldEvent) & {
351
357
  runId?: string;
352
358
  round?: number;
353
359
  callId?: string;
@@ -0,0 +1,4 @@
1
+ export type { DriveDir, DriveEntry } from '../tools/fs/drive.ts';
2
+ export type { DriveOpFn, GrantedDrive } from '../tools/fs/remote.ts';
3
+ export type { DriveEntryRequest, DriveGetRequest, DriveListRequest, DriveReadRequest, DriveRequest, DriveResponse, DriveSearchQuery, DriveSearchRequest, DriveWriteRequest } from '../tools/fs/remote-protocol.ts';
4
+ export type { SearchHit } from '../tools/fs/search.ts';
@@ -0,0 +1 @@
1
+ export {};
@@ -1,6 +1,8 @@
1
1
  export type * from './agent.ts';
2
2
  export type * from './completion.ts';
3
+ export type * from './drive.ts';
3
4
  export type * from './hooks.ts';
5
+ export type * from './managed-skills.ts';
4
6
  export type * from './policy.ts';
5
7
  export type * from './run.ts';
6
8
  export type * from './skill-readiness.ts';
@@ -0,0 +1 @@
1
+ export type { CopyBaseResult, DeleteOverlayResult, ManagedSkill, SkillFileContent } from '../tools/skills/overlay-crud.ts';
@@ -0,0 +1 @@
1
+ export {};
@@ -17,8 +17,15 @@ export interface Message {
17
17
  toolCallId?: string | null;
18
18
  name?: string | null;
19
19
  id?: string | null;
20
+ context?: TurnContext | null;
21
+ sentAt?: number | undefined;
20
22
  [key: string]: unknown;
21
23
  }
24
+ export interface TurnContext {
25
+ time?: string;
26
+ excerpts?: string[];
27
+ notes?: string;
28
+ }
22
29
  export interface FailureResultReference {
23
30
  type: 'qvac-failure-result-ref';
24
31
  ref: string;
@@ -47,6 +54,7 @@ export interface RunGoal {
47
54
  ms?: number;
48
55
  tokens?: number;
49
56
  checks?: string[];
57
+ checksProve?: boolean;
50
58
  }
51
59
  export type ToolEffect = 'read' | 'write';
52
60
  export type ToolDecision = 'auto' | 'allowed' | 'denied' | 'skip-all' | 'blocked';
@@ -14,7 +14,7 @@ import type { ManagedSkill, SkillFileContent } from './tools/skills/overlay-crud
14
14
  import type { DriveOpFn, GrantedDrive } from './tools/fs/remote.ts';
15
15
  import type { SpeakResult } from './contract/speech.ts';
16
16
  import type { RunInput } from './contract/completion.ts';
17
- import type { RunGoal } from './contract/run.ts';
17
+ import type { RunGoal, TurnContext } from './contract/run.ts';
18
18
  import type { KnowledgeArtifact, KnowledgeGrant, KnowledgeHit, KnowledgeQuery, KnowledgeRemoved, KnowledgeStatus, KnowledgeUpsertResult } from './contract/knowledge.ts';
19
19
  import type { ResolvedSkillCatalogEntry } from './tools/skills/catalog.ts';
20
20
  import type { InstallStep, SkillSetup } from './tools/skills/manifest.ts';
@@ -32,6 +32,8 @@ export type ChatMessage = {
32
32
  toolCallId?: string | null;
33
33
  name?: string | null;
34
34
  id?: string | null;
35
+ context?: TurnContext | null;
36
+ sentAt?: number | undefined;
35
37
  };
36
38
  export interface AgentKnobs {
37
39
  id?: string;
@@ -67,6 +69,7 @@ export interface CompletionContext {
67
69
  messages: ChatMessage[];
68
70
  typedText?: string;
69
71
  cacheKey?: string;
72
+ replaysContext?: boolean;
70
73
  session?: string;
71
74
  thinkingDefault?: string;
72
75
  toolConfigs?: Record<string, Record<string, unknown>>;
@@ -200,6 +200,10 @@ declare const HARNESS_ERRORS: {
200
200
  readonly code: 102610;
201
201
  readonly message: (filePath: string) => string;
202
202
  };
203
+ readonly OBSIDIAN_PATH_IS_FOLDER: {
204
+ readonly code: 102611;
205
+ readonly message: (folder: string) => string;
206
+ };
203
207
  readonly SKILL_FILE_NOT_FOUND: {
204
208
  readonly code: 102701;
205
209
  readonly message: (name: string, file: string) => string;
@@ -145,6 +145,12 @@ const HARNESS_ERRORS = {
145
145
  code: 102610,
146
146
  message: (filePath) => `Destination already exists: ${filePath}`
147
147
  },
148
+ OBSIDIAN_PATH_IS_FOLDER: {
149
+ code: 102611,
150
+ message: (folder) => `"${folder || '.'}" is a folder, not a note. List it with ` +
151
+ (folder ? `\`obsidian files folder="${folder}"\`` : '`obsidian files`') +
152
+ ', then read one note by its path.'
153
+ },
148
154
  SKILL_FILE_NOT_FOUND: {
149
155
  code: 102701,
150
156
  message: (name, file) => `ENOENT: ${name}/${file}`
@@ -0,0 +1,8 @@
1
+ export interface CpuPlacement {
2
+ threads: number;
3
+ mask: string;
4
+ }
5
+ export type ReadSysFile = (path: string) => string | null;
6
+ export declare function parseCpuList(list: string): number[];
7
+ export declare function performanceCorePlacement(read?: ReadSysFile, hostPlatform?: string): CpuPlacement | undefined;
8
+ export declare function androidCpuPlacement(): CpuPlacement | undefined;
@@ -0,0 +1,48 @@
1
+ import fs from 'fs';
2
+ import { platform } from 'os';
3
+ const CPU_ROOT = '/sys/devices/system/cpu';
4
+ function readSysFile(path) {
5
+ try {
6
+ return String(fs.readFileSync(path, 'utf8'));
7
+ }
8
+ catch {
9
+ return null;
10
+ }
11
+ }
12
+ function cpuRange(part) {
13
+ const [from, to = from] = part.split('-').map(Number);
14
+ if (!Number.isInteger(from) || !Number.isInteger(to) || to < from) {
15
+ return null;
16
+ }
17
+ return Array.from({ length: to - from + 1 }, (_, i) => from + i);
18
+ }
19
+ export function parseCpuList(list) {
20
+ const ranges = list.trim().split(',').map(cpuRange);
21
+ return ranges.some((range) => range === null) ? [] : ranges.flat().filter((cpu) => cpu !== null);
22
+ }
23
+ function readCores(read, possible) {
24
+ return parseCpuList(possible).flatMap((cpu) => {
25
+ const maxFreq = Number(read(`${CPU_ROOT}/cpu${cpu}/cpufreq/cpuinfo_max_freq`)?.trim());
26
+ return Number.isFinite(maxFreq) && maxFreq > 0 ? [{ cpu, maxFreq }] : [];
27
+ });
28
+ }
29
+ function placementOf(cores) {
30
+ const slowest = Math.min(...cores.map((core) => core.maxFreq));
31
+ const fast = cores.filter((core) => core.maxFreq > slowest);
32
+ if (fast.length === 0) {
33
+ return undefined;
34
+ }
35
+ const mask = fast.reduce((bits, core) => bits | (1n << BigInt(core.cpu)), 0n);
36
+ return { threads: fast.length, mask: mask.toString(16) };
37
+ }
38
+ export function performanceCorePlacement(read = readSysFile, hostPlatform = platform()) {
39
+ if (hostPlatform !== 'android')
40
+ return undefined;
41
+ const possible = read(`${CPU_ROOT}/possible`);
42
+ return possible === null ? undefined : placementOf(readCores(read, possible));
43
+ }
44
+ let cached = null;
45
+ export function androidCpuPlacement() {
46
+ cached ??= { placement: performanceCorePlacement() };
47
+ return cached.placement;
48
+ }
@@ -1,4 +1,6 @@
1
1
  export declare const MAX_GOAL_CHECKS = 8;
2
2
  export declare const GOAL_CHECKS_ASK: string;
3
+ export declare const GOAL_PROOF_ASK: string;
3
4
  export declare function namedChecks(text: string): string[];
5
+ export declare function mergeChecks(host: readonly string[], named: readonly string[]): string[];
4
6
  export declare function runsCheck(command: string, check: string): boolean;
@@ -7,6 +7,11 @@ export const GOAL_CHECKS_ASK = '[This goal has no checks yet. Name the commands
7
7
  'line `Checks:`, then one command per line in backticks, such as `test -s /app/result.json` ' +
8
8
  'or `python3 check.py`. Each must exit 0 only once the task is done, with no pipe, ; or && ' +
9
9
  'in it. The goal is met only once each of them ran on its own and exited 0.]';
10
+ export const GOAL_PROOF_ASK = '[The checks this goal has so far may only show that the output exists, not that it is right. Name the ' +
11
+ 'commands that will prove the result is correct, such as running the program on an input ' +
12
+ "and comparing with what the task asks, or the task's own tests: write a line `Checks:`, " +
13
+ 'then one command per line in backticks, with no pipe, ; or && in it. A command that repeats ' +
14
+ 'one of those checks does not count. The goal is met only once each check ran on its own and exited 0.]';
10
15
  export function namedChecks(text) {
11
16
  const lines = text.split('\n');
12
17
  const heading = lines.findIndex((line) => CHECKS_HEADING.test(line));
@@ -28,6 +33,19 @@ export function namedChecks(text) {
28
33
  }
29
34
  return named.slice(0, MAX_GOAL_CHECKS);
30
35
  }
36
+ export function mergeChecks(host, named) {
37
+ const known = new Set(host.map(normalize));
38
+ const fresh = named
39
+ .filter((name) => !known.has(normalize(name)))
40
+ .slice(0, host.length ? MAX_GOAL_CHECKS - 1 : MAX_GOAL_CHECKS);
41
+ if (!fresh.length) {
42
+ return [];
43
+ }
44
+ return [...host.slice(0, MAX_GOAL_CHECKS - fresh.length), ...fresh];
45
+ }
46
+ function normalize(command) {
47
+ return command.trim().replace(/\s+/g, ' ');
48
+ }
31
49
  export function runsCheck(command, check) {
32
50
  const wanted = words(check);
33
51
  const parts = command.split(SHELL_OPERATOR);
@@ -1,5 +1,5 @@
1
1
  import { hasRoundsLeft } from '../guards/retry.js';
2
- import { namedChecks } from '../../../helpers/goal-check.js';
2
+ import { mergeChecks, namedChecks } from '../../../helpers/goal-check.js';
3
3
  import { activate, applyHistorySplice, applySplice, foldMetrics, goalMet, goalStalled, goalTokensLeft, nudgeWithChecks, nudgeWithPlan, retainFailureResults } from '../rules.js';
4
4
  export function startInitialRound({ context, params }) {
5
5
  return applyPreparation(context, params);
@@ -19,9 +19,18 @@ export function startNextRound({ context }) {
19
19
  }
20
20
  export function retryMuteRound(args) {
21
21
  const { context } = args;
22
- return { ...silentTurn(args), mute: context.mute + 1, round: context.round + 1 };
22
+ return {
23
+ ...silentTurn(args, muteReAsk(context)),
24
+ mute: context.mute + 1,
25
+ round: context.round + 1
26
+ };
27
+ }
28
+ function muteReAsk(context) {
29
+ return context.goal && !context.steering.length && !goalMet(context)
30
+ ? [{ role: 'user', content: goalTurn(context) }]
31
+ : continuation(context);
23
32
  }
24
- function silentTurn({ context, params }) {
33
+ function silentTurn({ context, params }, reAsk = continuation(context)) {
25
34
  if (params.cutOff) {
26
35
  return {};
27
36
  }
@@ -29,7 +38,7 @@ function silentTurn({ context, params }) {
29
38
  history: [
30
39
  ...context.history,
31
40
  { role: 'assistant', content: params.response?.trim() ?? '' },
32
- ...continuation(context)
41
+ ...reAsk
33
42
  ],
34
43
  steering: []
35
44
  };
@@ -109,7 +118,7 @@ function continuation(context) {
109
118
  : [{ role: 'user', content: nudgeWithPlan(nudge, plan) }];
110
119
  }
111
120
  function userTurns(queued) {
112
- return queued.map(({ text }) => ({ role: 'user', content: text }));
121
+ return queued.map(({ text, content }) => ({ role: 'user', content: content ?? text }));
113
122
  }
114
123
  function continueAfterAnswer(context, turns) {
115
124
  return {
@@ -131,7 +140,8 @@ export function continueWithInput({ context }) {
131
140
  ...userTurns(context.followUps)
132
141
  ]),
133
142
  steering: [],
134
- followUps: []
143
+ followUps: [],
144
+ edgeInputs: [...context.steering, ...context.followUps]
135
145
  };
136
146
  }
137
147
  export function addKnowledge({ context, params }) {
@@ -141,7 +151,7 @@ export function addKnowledge({ context, params }) {
141
151
  };
142
152
  }
143
153
  export function goalTurn({ policy, goal, plan }) {
144
- return nudgeWithChecks(nudgeWithPlan(`${policy.goalNudge}\nGoal: ${goal?.objective ?? ''}`, plan), goal?.checks ?? [], goal?.checkable);
154
+ return nudgeWithChecks(nudgeWithPlan(`${policy.goalNudge}\nGoal: ${goal?.objective ?? ''}`, plan), goal?.checks ?? [], goal?.checkable && !goal.named);
145
155
  }
146
156
  export function continueGoal({ context }) {
147
157
  const { goal } = context;
@@ -200,13 +210,16 @@ export function finishWrapRound({ context, params }) {
200
210
  };
201
211
  }
202
212
  function adoptChecks(goal, text) {
203
- if (!goal?.checkable || goal.checks.length) {
213
+ if (!goal?.checkable || goal.named) {
214
+ return goal;
215
+ }
216
+ const host = goal.checks.map((check) => check.name);
217
+ const names = mergeChecks(host, namedChecks(text));
218
+ if (!names.length) {
204
219
  return goal;
205
220
  }
206
- const named = namedChecks(text);
207
- return named.length
208
- ? { ...goal, checks: named.map((name) => ({ name, passed: false, output: null })) }
209
- : goal;
221
+ const checks = names.map((name) => goal.checks.find((check) => check.name === name) ?? { name, passed: false, output: null });
222
+ return { ...goal, checks, named: true };
210
223
  }
211
224
  function settledAfterSend(context, params) {
212
225
  return params.history && params.history.at < context.history.length
@@ -248,9 +261,16 @@ export function answerCompletion({ context, params }) {
248
261
  : history,
249
262
  response: params.response || context.response,
250
263
  metrics,
251
- outcome: context.outcome ?? 'answered'
264
+ outcome: metGoalAnswered(context) ? 'answered' : (context.outcome ?? 'answered')
252
265
  };
253
266
  }
267
+ function metGoalAnswered(context) {
268
+ const round = context.lastRound;
269
+ return (context.outcome === 'mute' &&
270
+ context.goal !== null &&
271
+ goalMet(context) &&
272
+ Boolean(round?.contentText.trim() || round?.replay?.trim()));
273
+ }
254
274
  export function failCompletion({ params }) {
255
275
  const failure = 'tag' in params
256
276
  ? params
@@ -56,6 +56,7 @@ export function emptyCompletionContext(opts) {
56
56
  failMessage: null,
57
57
  steering: [],
58
58
  followUps: [],
59
+ edgeInputs: [],
59
60
  plan: opts.plan ?? [],
60
61
  planMode: opts.planMode ?? false,
61
62
  goal: opts.goal
@@ -64,7 +65,8 @@ export function emptyCompletionContext(opts) {
64
65
  tokens: opts.goal.tokens ?? null,
65
66
  turns: 0,
66
67
  status: 'open',
67
- checks: (opts.goal.checks ?? []).map((name) => ({ name, passed: false, output: null }))
68
+ checks: (opts.goal.checks ?? []).map((name) => ({ name, passed: false, output: null })),
69
+ named: (opts.goal.checksProve && Boolean(opts.goal.checks?.length)) || undefined
68
70
  }
69
71
  : null
70
72
  };
@@ -162,7 +162,10 @@ export const completionActions = {
162
162
  : durable
163
163
  };
164
164
  }),
165
- ackSteering: ackAction(({ context }, params) => context.steering.map((queued) => inputEvent(context.runId, queued, params.round))),
165
+ ackSteering: ackAction(({ context }, params) => context.steering.flatMap((queued) => [
166
+ inputEvent(context.runId, queued, params.round),
167
+ ...contextEvent(context.runId, queued, params.round)
168
+ ])),
166
169
  resetCutRound: ackAction(({ context }, params) => params.cutOff
167
170
  ? [
168
171
  {
@@ -177,7 +180,7 @@ export const completionActions = {
177
180
  queueInput: assign(({ context, event }) => {
178
181
  if (event.type !== 'INPUT')
179
182
  return {};
180
- const queued = event.id === undefined ? { text: event.text } : { id: event.id, text: event.text };
183
+ const queued = queuedOf(event);
181
184
  return event.mode === 'steer'
182
185
  ? { steering: [...context.steering, queued] }
183
186
  : { followUps: [...context.followUps, queued] };
@@ -218,6 +221,15 @@ function goalAction(action) {
218
221
  enqueue.emit(event);
219
222
  });
220
223
  }
221
- function inputEvent(runId, queued, round) {
222
- return { type: 'input', runId, ...queued, round };
224
+ function inputEvent(runId, { id, text }, round) {
225
+ return { type: 'input', runId, ...idOf(id), text, round };
226
+ }
227
+ function contextEvent(runId, { id, context }, round) {
228
+ return context ? [{ type: 'context', runId, ...idOf(id), context, round }] : [];
229
+ }
230
+ function queuedOf({ id, text, context, content }) {
231
+ return context === undefined ? { ...idOf(id), text } : { ...idOf(id), text, context, content };
232
+ }
233
+ function idOf(id) {
234
+ return id === undefined ? {} : { id };
223
235
  }
@@ -34,6 +34,8 @@ declare const createCompletionMachineImplementation: (context?: CompletionContex
34
34
  mode: 'steer' | 'follow-up';
35
35
  id?: string;
36
36
  text: string;
37
+ context?: import("../../contract/run.ts").TurnContext;
38
+ content?: string;
37
39
  }, {
38
40
  [x: string]: import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<void, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").AnsweredPayload, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").BatchDonePayload, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").InspectingOutput, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").PrepareInspectionOutput, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").PreparingOutput, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").RetrievingOutput, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").RoundDonePayload, InvocationInput> | import("xstate").PromiseActorLogic<SearchingOutput, InvocationInput> | import("xstate").PromiseActorLogic<import("./types.ts").ToolDonePayload, InvocationInput> | import("xstate").PromiseActorLogic<{
39
41
  approved: boolean;
@@ -11,7 +11,7 @@ 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
13
  export declare function goalMet({ plan, goal }: Readonly<CompletionContext>): boolean;
14
- export declare function nudgeWithChecks(nudge: string, checks: readonly GoalCheck[], checkable?: boolean): string;
14
+ export declare function nudgeWithChecks(nudge: string, checks: readonly GoalCheck[], unnamed?: boolean): string;
15
15
  export declare function goalTokensLeft({ goal, metrics }: Readonly<CompletionContext>): boolean;
16
16
  export declare function goalStalled({ outcome }: Readonly<CompletionContext>): boolean;
17
17
  export declare function retainFailureResults(history: readonly CompletionHistoryEntry[], values: Readonly<Record<string, FailureResultValue>>, failedCalls: Readonly<Record<string, SettledCall>>): Record<string, FailureResultValue>;
@@ -1,5 +1,5 @@
1
1
  import { isFailureResultReference } from '../../helpers/failure-result.js';
2
- import { GOAL_CHECKS_ASK } from '../../helpers/goal-check.js';
2
+ import { 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;
@@ -35,20 +35,19 @@ function planDone(plan) {
35
35
  }
36
36
  export function goalMet({ plan, goal }) {
37
37
  const checks = goal?.checks ?? [];
38
- return (planDone(plan) &&
39
- (checks.length > 0 || !goal?.checkable) &&
40
- checks.every((check) => check.passed));
38
+ return (planDone(plan) && (goal?.named || !goal?.checkable) && checks.every((check) => check.passed));
41
39
  }
42
- export function nudgeWithChecks(nudge, checks, checkable) {
40
+ export function nudgeWithChecks(nudge, checks, unnamed) {
43
41
  if (!checks.length) {
44
- return checkable ? `${nudge}\n${GOAL_CHECKS_ASK}` : nudge;
42
+ return unnamed ? `${nudge}\n${GOAL_CHECKS_ASK}` : nudge;
45
43
  }
44
+ const asked = unnamed ? `${nudge}\n${GOAL_PROOF_ASK}` : nudge;
46
45
  const open = checks.filter((check) => !check.passed);
47
46
  if (!open.length) {
48
- return nudge;
47
+ return asked;
49
48
  }
50
49
  const lines = open.map(({ name, output }) => output === null ? `- ${name}: not run yet` : `- ${name}: failed. Its last output:\n${output}`);
51
- return (`${nudge}\nChecks: the goal is met only once each of these runs as its own command and ` +
50
+ return (`${asked}\nChecks: the goal is met only once each of these runs as its own command and ` +
52
51
  `exits 0, with no pipe or ; after it to hide its exit code.\n${lines.join('\n')}`);
53
52
  }
54
53
  export function goalTokensLeft({ goal, metrics }) {
@@ -1,4 +1,4 @@
1
- import type { CompletionHistoryEntry, GoalStatus, HistorySplice, HookRejection, Operation, PlanStep, ResourceDescriptor, RoundSpeed, RunBackendUse, RunBudget, RunOutcome, ToolActivityEvent, ToolCallDisplay, ToolEffect, ToolExecutionOutcome, ToolSpeed, TrustedSourceFacts } from '../../contract/run.ts';
1
+ import type { CompletionHistoryEntry, GoalStatus, HistorySplice, HookRejection, Operation, PlanStep, ResourceDescriptor, RoundSpeed, RunBackendUse, RunBudget, RunOutcome, ToolActivityEvent, ToolCallDisplay, ToolEffect, ToolExecutionOutcome, ToolSpeed, TrustedSourceFacts, TurnContext } from '../../contract/run.ts';
2
2
  import type { EngineError } from '../../helpers/engine-error.ts';
3
3
  import type { FailureResultValue } from '../../helpers/failure-result.ts';
4
4
  export interface CompletionStats {
@@ -22,6 +22,7 @@ export interface EngineEvent {
22
22
  status?: GoalStatus;
23
23
  turn?: number;
24
24
  checks?: string[];
25
+ context?: TurnContext;
25
26
  }
26
27
  export interface EngineFacts extends Record<string, unknown> {
27
28
  runBudget: RunBudget;
@@ -273,10 +274,13 @@ export interface GoalState {
273
274
  status: GoalStatus;
274
275
  checks: GoalCheck[];
275
276
  checkable?: boolean;
277
+ named?: boolean;
276
278
  }
277
279
  export interface QueuedInput {
278
280
  id?: string;
279
281
  text: string;
282
+ context?: TurnContext;
283
+ content?: string;
280
284
  }
281
285
  export interface CompletionContext {
282
286
  runId: string;
@@ -334,6 +338,7 @@ export interface CompletionContext {
334
338
  failMessage: string | null;
335
339
  steering: QueuedInput[];
336
340
  followUps: QueuedInput[];
341
+ edgeInputs: QueuedInput[];
337
342
  plan: PlanStep[];
338
343
  planMode: boolean;
339
344
  goal: GoalState | null;
@@ -449,4 +454,6 @@ export type CompletionMachineEvent = {
449
454
  mode: 'steer' | 'follow-up';
450
455
  id?: string;
451
456
  text: string;
457
+ context?: TurnContext;
458
+ content?: string;
452
459
  };
@@ -38,6 +38,8 @@ export declare class CompletionMachine {
38
38
  mode: 'steer' | 'follow-up';
39
39
  id?: string;
40
40
  text: string;
41
+ context?: import("../contract/run.ts").TurnContext;
42
+ content?: string;
41
43
  }, {
42
44
  [x: string]: import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<void, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").AnsweredPayload, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").BatchDonePayload, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").InspectingOutput, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").PrepareInspectionOutput, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").PreparingOutput, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").RetrievingOutput, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").RoundDonePayload, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").SearchingOutput, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<import("./completion/types.ts").ToolDonePayload, import("./index.ts").InvocationInput> | import("xstate").PromiseActorLogic<{
43
45
  approved: boolean;
@@ -1,6 +1,7 @@
1
1
  import ResourcePuddle from 'resource-puddle';
2
2
  import { ModelHandle } from './model-handle.ts';
3
3
  import { type ModelSrc } from './context.ts';
4
+ import type { CpuPlacement } from '../hardware/cpu-placement.ts';
4
5
  import { type ModelAddon } from './model-source.ts';
5
6
  import type { GpuFaultState } from './sdk-faults.ts';
6
7
  import type { LoadedModelInfo } from '@qvac/sdk';
@@ -55,6 +56,7 @@ export interface LlmDeviceConfig {
55
56
  slots?: number;
56
57
  contextFor?: (key: string) => number | undefined;
57
58
  slotsFor?: (key: string) => number | undefined;
59
+ cpuPlacement?: () => CpuPlacement | undefined;
58
60
  }
59
61
  export type TrackedLoad = Promise<string> & {
60
62
  requestId?: string;
@@ -89,6 +91,8 @@ export type ModelLifecycleSdk = Pick<SdkModule, 'unloadModel' | 'modelRegistrySe
89
91
  gpu_layers?: number;
90
92
  'main-gpu'?: string;
91
93
  openclCacheDir?: string;
94
+ threads?: number;
95
+ 'cpu-mask'?: string;
92
96
  };
93
97
  onProgress?: (progress: Record<string, unknown>) => void;
94
98
  }): TrackedLoad;
@@ -423,6 +423,7 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
423
423
  const openclCache = deviceConfig.device !== 'cpu' && deviceConfig.openclCacheDir
424
424
  ? deviceConfig.openclCacheDir()
425
425
  : undefined;
426
+ const placement = deviceConfig.device === 'cpu' ? deviceConfig.cpuPlacement?.() : undefined;
426
427
  const config = definedFields({
427
428
  ...resolved.llama,
428
429
  verbosity: llmVerbosity(),
@@ -436,7 +437,9 @@ export function createModelPool(loadSdk, notify, { deviceConfig = {}, loads = cr
436
437
  device: deviceConfig.device,
437
438
  gpu_layers: deviceConfig.gpuLayers,
438
439
  'main-gpu': mainGpu,
439
- openclCacheDir: openclCache || undefined
440
+ openclCacheDir: openclCache || undefined,
441
+ threads: resolved.llama?.threads ?? placement?.threads,
442
+ 'cpu-mask': placement?.mask
440
443
  });
441
444
  const pending = { key, model, modelSrc, modelType: 'llamacpp-completion' };
442
445
  const chosen = contextSize(model, modelSrc, { opts: resolved, deviceConfig });
@@ -2,9 +2,10 @@ import type { Message, SystemPromptParts } from './contract/index.ts';
2
2
  export declare const RAG_CITATION_LINE = "After your answer, add one final line naming the files you used, written exactly as [Sources: file-a.pdf, file-b.md] - or [Sources: none] if the excerpts did not answer the question. This line is required, it is the only place square brackets belong, and it is removed before the user sees it.";
3
3
  export declare function currentTimeAnnotation(now?: Date): string;
4
4
  export declare function lastUserContent(messages: Message[]): string;
5
- export declare function annotateLastUserTime<T extends {
5
+ export declare function annotateUserTimes<T extends {
6
6
  role: string;
7
7
  content: string;
8
+ sentAt?: number | undefined;
8
9
  }>(turns: ReadonlyArray<T>, now?: Date): T[];
9
10
  export declare function toolGuidelines(name: string): string[];
10
11
  export interface SystemPromptInput {