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

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 (92) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -1
  3. package/dist-lib/index.js +0 -1
  4. package/dist-lib/lib/agent/follow.js +9 -2
  5. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +13 -3
  6. package/dist-lib/lib/capabilities/completion-engine/actors/loading-skill.js +1 -1
  7. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +21 -12
  8. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.d.ts +2 -1
  9. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +19 -11
  10. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +2 -2
  11. package/dist-lib/lib/capabilities/completion-engine/actors/stream.d.ts +1 -1
  12. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +11 -0
  13. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +16 -4
  14. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +8 -2
  15. package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
  16. package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
  17. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
  18. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -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 +2 -0
  21. package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
  22. package/dist-lib/lib/capabilities/completion-engine/ports.js +1 -1
  23. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -0
  24. package/dist-lib/lib/capabilities/completion-engine/round.js +40 -20
  25. package/dist-lib/lib/capabilities/completion-engine/session.d.ts +3 -3
  26. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
  27. package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
  28. package/dist-lib/lib/capabilities/prompt-prefix.d.ts +2 -0
  29. package/dist-lib/lib/capabilities/prompt-prefix.js +8 -0
  30. package/dist-lib/lib/capabilities/sdk-tool.d.ts +1 -1
  31. package/dist-lib/lib/capabilities/sdk-tool.js +17 -2
  32. package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
  33. package/dist-lib/lib/capabilities/tool-turns.js +1 -0
  34. package/dist-lib/lib/capabilities/usage-breakdown.d.ts +1 -0
  35. package/dist-lib/lib/capabilities/usage-breakdown.js +4 -1
  36. package/dist-lib/lib/connect.js +4 -2
  37. package/dist-lib/lib/contract/completion.d.ts +2 -1
  38. package/dist-lib/lib/contract/knowledge.d.ts +10 -0
  39. package/dist-lib/lib/fold/index.d.ts +3 -2
  40. package/dist-lib/lib/fold/index.js +7 -6
  41. package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
  42. package/dist-lib/lib/helpers/goal-check.js +89 -7
  43. package/dist-lib/lib/helpers/html-helpers.js +9 -6
  44. package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
  45. package/dist-lib/lib/helpers/input-budget.js +9 -0
  46. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  47. package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
  48. package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
  49. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  50. package/dist-lib/lib/machine/completion/rules.js +14 -5
  51. package/dist-lib/lib/machine/completion/types.d.ts +3 -0
  52. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  53. package/dist-lib/lib/plugins/registry.js +49 -10
  54. package/dist-lib/lib/residency/index.js +2 -0
  55. package/dist-lib/lib/serve.js +56 -15
  56. package/dist-lib/lib/tools/files/glob.js +2 -2
  57. package/dist-lib/lib/tools/files/read-file.js +134 -15
  58. package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
  59. package/dist-lib/lib/tools/fs/walk.js +2 -1
  60. package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
  61. package/dist-lib/lib/tools/http-request.js +28 -11
  62. package/dist-lib/lib/tools/office.d.ts +1 -1
  63. package/dist-lib/lib/tools/office.js +34 -12
  64. package/dist-lib/lib/wire.js +23 -3
  65. package/dist-lib/plugins/knowledge/index.d.ts +3 -0
  66. package/dist-lib/plugins/knowledge/index.js +5 -0
  67. package/dist-lib/plugins/knowledge/manifest.d.ts +53 -0
  68. package/dist-lib/plugins/knowledge/manifest.js +86 -0
  69. package/dist-lib/plugins/knowledge/search-tool.js +8 -8
  70. package/dist-lib/plugins/knowledge/store.d.ts +45 -8
  71. package/dist-lib/plugins/knowledge/store.js +428 -166
  72. package/dist-lib/plugins/mcp/call.js +10 -3
  73. package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
  74. package/dist-lib/plugins/mcp/protocol.js +11 -10
  75. package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
  76. package/dist-lib/plugins/mcp/tool-listing.js +97 -0
  77. package/dist-lib/plugins/music/generate-music.js +2 -2
  78. package/dist-lib/plugins/obsidian/index.js +14 -4
  79. package/dist-lib/plugins/python/index.d.ts +3 -1
  80. package/dist-lib/plugins/python/index.js +4 -1
  81. package/dist-lib/plugins/python/language.js +2 -2
  82. package/dist-lib/plugins/python/python-adapter.d.ts +2 -1
  83. package/dist-lib/plugins/python/python-adapter.js +8 -1
  84. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  85. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  86. package/dist-lib/schema/harness.js +4 -2
  87. package/dist-lib/spec/hrpc/messages.js +19 -4
  88. package/dist-lib/spec/hyperschema/index.js +19 -4
  89. package/dist-lib/spec/hyperschema/schema.json +12 -1
  90. package/dist-lib/spec/hyperschema/types.d.ts +2 -0
  91. package/package.json +28 -19
  92. package/scripts/addon-externals.cjs +4 -1
@@ -24,4 +24,5 @@ export interface PromptUsagePartsInput {
24
24
  toolSchemas?: ReadonlyArray<unknown> | undefined;
25
25
  }
26
26
  export declare function promptUsageParts({ system, toolSchemas }: PromptUsagePartsInput): PromptUsageChars;
27
+ export declare function toolSchemaChars(toolSchemas?: ReadonlyArray<unknown>): number;
27
28
  export declare function usageBreakdown(chars: PromptUsageChars, totalTokens?: number | null, modelName?: string | null): UsageBreakdown | null;
@@ -13,9 +13,12 @@ export function promptUsageParts({ system, toolSchemas }) {
13
13
  systemPrompt: system.text.length - system.bioChars - system.skillsChars,
14
14
  agentInstructions: system.bioChars,
15
15
  activeSkills: system.skillsChars,
16
- toolSchemas: (toolSchemas ?? []).reduce((total, schema) => total + JSON.stringify(schema).length, 0)
16
+ toolSchemas: toolSchemaChars(toolSchemas)
17
17
  };
18
18
  }
19
+ export function toolSchemaChars(toolSchemas) {
20
+ return (toolSchemas ?? []).reduce((total, schema) => total + JSON.stringify(schema).length, 0);
21
+ }
19
22
  export function usageBreakdown(chars, totalTokens, modelName) {
20
23
  if (!totalTokens || totalTokens <= 0)
21
24
  return null;
@@ -133,7 +133,8 @@ export class RemoteHarness extends EventEmitter {
133
133
  payload.explicitEmptyIdentity = explicitEmptyIdentity;
134
134
  }
135
135
  if (context.knowledge) {
136
- payload.knowledge = { scopes: [...context.knowledge.scopes] };
136
+ const { scopes, focus, k } = context.knowledge;
137
+ payload.knowledge = { scopes: [...scopes], focus: focus && [...focus], k };
137
138
  }
138
139
  if (context.planMode) {
139
140
  payload.planMode = true;
@@ -852,7 +853,8 @@ export class RemoteHarness extends EventEmitter {
852
853
  const response = await client.knowledgeSearch({
853
854
  text: query.text,
854
855
  scopes: [...query.scopes],
855
- k: query.k
856
+ k: query.k,
857
+ focus: query.focus && [...query.focus]
856
858
  });
857
859
  return response.hits.map(fromKnowledgeHitWire);
858
860
  }
@@ -6,7 +6,7 @@ import type { CapabilityProfile } from '../models/model-catalog-constants.ts';
6
6
  import type { DriveRoot } from '../tools/fs/scope.ts';
7
7
  import type { CliValidator } from '../tools/skills/cli-schema-types.ts';
8
8
  import type { UsageBreakdown } from '../capabilities/usage-breakdown.ts';
9
- import type { KnowledgeGrant } from './knowledge.ts';
9
+ import type { KnowledgeGrant, KnowledgeSource } from './knowledge.ts';
10
10
  import type { AccessPolicy, CompiledPolicy } from './policy.ts';
11
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 };
@@ -316,6 +316,7 @@ export type ContextEvent = {
316
316
  type: 'context';
317
317
  id?: string;
318
318
  context: TurnContext;
319
+ sources?: KnowledgeSource[];
319
320
  round: number;
320
321
  };
321
322
  export type InputRejectedEvent = {
@@ -23,6 +23,7 @@ export interface KnowledgeUpsertResult {
23
23
  export interface KnowledgeQuery {
24
24
  text: string;
25
25
  scopes: readonly string[];
26
+ focus?: readonly string[];
26
27
  k?: number;
27
28
  signal?: BareAbortSignal;
28
29
  }
@@ -34,6 +35,12 @@ export interface KnowledgeHit {
34
35
  score: number;
35
36
  metadata?: Record<string, unknown>;
36
37
  }
38
+ export interface KnowledgeSource {
39
+ artifactId: string;
40
+ chunkId: string;
41
+ score: number;
42
+ metadata?: Record<string, unknown>;
43
+ }
37
44
  export interface KnowledgeArtifactStatus {
38
45
  artifactId: string;
39
46
  version?: string;
@@ -44,10 +51,13 @@ export interface KnowledgeStatus {
44
51
  model: string;
45
52
  dimensions: number;
46
53
  chunks: number;
54
+ pending: number;
47
55
  artifacts: KnowledgeArtifactStatus[];
48
56
  }
49
57
  export interface KnowledgeGrant {
50
58
  scopes: string[];
59
+ focus?: string[];
60
+ k?: number;
51
61
  }
52
62
  export interface KnowledgeRemoved {
53
63
  removed: number;
@@ -35,6 +35,7 @@ export interface RoundsBoundary {
35
35
  }
36
36
  export interface RoundsOptions extends FoldOptions {
37
37
  nudges: readonly string[];
38
+ goals?: readonly string[] | undefined;
38
39
  keeps: (message: Message) => boolean;
39
40
  }
40
41
  export type RoundsResult = {
@@ -58,7 +59,7 @@ export declare class Fold {
58
59
  static turn(summary: string): string;
59
60
  static isSummary(message: Pick<Message, 'role' | 'content'>): boolean;
60
61
  static isTurn(message: Pick<Message, 'role' | 'content'>, nudges: readonly string[]): boolean;
61
- static carriesPlan(message: Pick<Message, 'role' | 'content'>, nudges: readonly string[]): boolean;
62
+ static carriesState(message: Pick<Message, 'role' | 'content'>, nudges: readonly string[]): boolean;
62
63
  static ratio(ctxSize: number): number;
63
64
  static fits(ctxSize: number | undefined): boolean;
64
65
  static due({ cacheTokens, ctxSize, cutOff }: FoldReading): boolean;
@@ -66,7 +67,7 @@ export declare class Fold {
66
67
  static reading(cacheKey: string): FoldReading | undefined;
67
68
  static forget(cacheKey: string): void;
68
69
  static boundary(messages: readonly Message[], keepTurns?: number): FoldBoundary | null;
69
- static roundBoundary(messages: readonly Message[], { nudges, keeps }: Pick<RoundsOptions, 'nudges' | 'keeps'>, most?: number): RoundsBoundary | null;
70
+ static roundBoundary(messages: readonly Message[], { nudges, goals, keeps }: Pick<RoundsOptions, 'nudges' | 'goals' | 'keeps'>, most?: number): RoundsBoundary | null;
70
71
  static prompt(messages: readonly Message[], instructions?: string): string;
71
72
  static shrinks(folded: readonly Message[], summary: string): boolean;
72
73
  run(messages: readonly Message[], options?: FoldOptions): AsyncGenerator<FoldEvent, FoldResult>;
@@ -26,11 +26,11 @@ export class Fold {
26
26
  return (message.role === 'user' &&
27
27
  !Fold.isSummary(message) &&
28
28
  !nudges.includes(message.content) &&
29
- !Fold.carriesPlan(message, nudges));
29
+ !Fold.carriesState(message, nudges));
30
30
  }
31
- static carriesPlan(message, nudges) {
31
+ static carriesState(message, nudges) {
32
32
  return (message.role === 'user' &&
33
- nudges.some((nudge) => message.content.startsWith(`${nudge}\nPlan:\n`)));
33
+ nudges.some((nudge) => nudge !== '' && message.content.startsWith(`${nudge}\n`)));
34
34
  }
35
35
  static ratio(ctxSize) {
36
36
  return TIERS.find(([below]) => ctxSize < below)?.[1] ?? Fold.RATIO;
@@ -62,14 +62,15 @@ export class Fold {
62
62
  const end = users[users.length - keepTurns];
63
63
  return end > 0 ? { end, foldedTurns: users.length - keepTurns } : null;
64
64
  }
65
- static roundBoundary(messages, { nudges, keeps }, most = Infinity) {
65
+ static roundBoundary(messages, { nudges, goals = [], keeps }, most = Infinity) {
66
66
  const task = messages.findLastIndex((message) => Fold.isTurn(message, nudges));
67
67
  if (task === -1) {
68
68
  return null;
69
69
  }
70
70
  const starts = messages.flatMap((message, at) => at > task && message.role === 'assistant' ? [at] : []);
71
- const plan = messages.findLastIndex((message, at) => at > task && Fold.carriesPlan(message, nudges));
72
- const kept = (from, to) => (plan >= from && plan < to) || messages.slice(from, to).some(keeps);
71
+ const latest = (among) => messages.findLastIndex((message, at) => at > task && Fold.carriesState(message, among));
72
+ const states = [latest(goals), latest(nudges)];
73
+ const kept = (from, to) => states.some((at) => at >= from && at < to) || messages.slice(from, to).some(keeps);
73
74
  const rounds = starts
74
75
  .map((from, index) => [from, starts[index + 1] ?? messages.length])
75
76
  .slice(0, Math.max(0, starts.length - Fold.KEEP_ROUNDS))
@@ -1,6 +1,18 @@
1
1
  export declare const MAX_GOAL_CHECKS = 8;
2
2
  export declare const GOAL_CHECKS_ASK: string;
3
3
  export declare const GOAL_PROOF_ASK: string;
4
+ export declare const MAX_PROOF_ASKS = 2;
5
+ export interface AskedGoal {
6
+ checkable?: boolean;
7
+ named?: boolean;
8
+ checks: readonly {
9
+ name: string;
10
+ }[];
11
+ turns: number;
12
+ }
13
+ export declare function asksChecks(goal: AskedGoal): boolean;
14
+ export declare function existenceOnly(checks: readonly string[]): boolean;
15
+ export declare function provesResult(command: string): string | undefined;
4
16
  export declare function namedChecks(text: string): string[];
5
17
  export declare function mergeChecks(host: readonly string[], named: readonly string[]): string[];
6
18
  export declare function runsCheck(command: string, check: string): boolean;
@@ -2,6 +2,19 @@ const SHELL_OPERATOR = /(&&|\|\||;|\||\n)/;
2
2
  const RUNNER = /^(python[\d.]*|bash|sh|node|bun|pytest)$/;
3
3
  const CHECKS_HEADING = /^[\s*#_]*checks:?[\s*_]*$/i;
4
4
  const CHECK_LINE = /^\s*(?:[-*]|\d+[.)])?\s*`([^`]+)`\s*$/;
5
+ const FILE_TEST = /^-[sfed]$/;
6
+ const NOT_A_PATH = /^(-\w+|!|!?=+|<|>|\]\]?)$/;
7
+ const COMPARISON = /^(!?=+|-(eq|ne|lt|le|gt|ge))$/;
8
+ const TEST_SCRIPT = /^(tests?|checks?|verify|validate)(?=[_.-]|$)/;
9
+ const PACKAGE_TEST = /^tests?(?=[:_.-]|$)/;
10
+ const PACKAGE_MANAGER = /^(npm|yarn|pnpm|bun)$/;
11
+ const PYTHON = /^python[\d.]*$/;
12
+ const TEST_PROGRAM = /^(pytest|ctest|diff|cmp)$/;
13
+ const QUIET = /^(-[a-zA-Z]*q[a-zA-Z]*|--quiet)$/;
14
+ const BRACKETS = new Map([
15
+ ['[', ']'],
16
+ ['[[', ']]']
17
+ ]);
5
18
  export const MAX_GOAL_CHECKS = 8;
6
19
  export const GOAL_CHECKS_ASK = '[This goal has no checks yet. Name the commands that will prove the task is done: write a ' +
7
20
  'line `Checks:`, then one command per line in backticks, such as `test -s /app/result.json` ' +
@@ -12,6 +25,69 @@ export const GOAL_PROOF_ASK = '[The checks this goal has so far may only show th
12
25
  "and comparing with what the task asks, or the task's own tests: write a line `Checks:`, " +
13
26
  'then one command per line in backticks, with no pipe, ; or && in it. A command that repeats ' +
14
27
  'one of those checks does not count. The goal is met only once each check ran on its own and exited 0.]';
28
+ export const MAX_PROOF_ASKS = 2;
29
+ export function asksChecks(goal) {
30
+ return (!!goal.checkable &&
31
+ !goal.named &&
32
+ (!goal.checks.length ||
33
+ existenceOnly(goal.checks.map((check) => check.name)) ||
34
+ goal.turns < MAX_PROOF_ASKS));
35
+ }
36
+ export function existenceOnly(checks) {
37
+ return (checks.length > 0 &&
38
+ checks.every((check) => check
39
+ .split(SHELL_OPERATOR)
40
+ .filter((part, at) => at % 2 === 0 && part.trim())
41
+ .every((part) => testsExistence(words(part)))));
42
+ }
43
+ function testsExistence(tokens) {
44
+ const close = BRACKETS.get(tokens[0]);
45
+ if ((tokens[0] !== 'test' && !close) || (close && tokens.at(-1) !== close)) {
46
+ return false;
47
+ }
48
+ const path = tokens.slice(2, close ? -1 : undefined);
49
+ return (FILE_TEST.test(tokens[1] ?? '') &&
50
+ path.length > 0 &&
51
+ !path.some((token) => NOT_A_PATH.test(token)));
52
+ }
53
+ export function provesResult(command) {
54
+ return exitSegments(command).find(proves);
55
+ }
56
+ function proves(segment) {
57
+ if (segment.split('"').length % 2 === 0 || segment.split("'").length % 2 === 0) {
58
+ return false;
59
+ }
60
+ const all = words(segment);
61
+ const tokens = all.slice(Math.max(commandStart(all), 0));
62
+ const program = tokens[0]?.split('/').at(-1) ?? '';
63
+ const [, next = '', third = ''] = tokens;
64
+ const python = PYTHON.test(program);
65
+ if (program === 'test' || program === '[' || program === '[[') {
66
+ return tokens.some((token) => COMPARISON.test(token));
67
+ }
68
+ if ((python && tokens.includes('-c')) || (program === 'node' && tokens.includes('-e'))) {
69
+ return /\bassert\b/.test(segment);
70
+ }
71
+ const module = tokens.indexOf('-m');
72
+ return (TEST_PROGRAM.test(program) ||
73
+ (program === 'grep' && tokens.some((token) => QUIET.test(token))) ||
74
+ (PACKAGE_MANAGER.test(program) && PACKAGE_TEST.test(next === 'run' ? third : next)) ||
75
+ ((program === 'cargo' || program === 'go') && next === 'test') ||
76
+ (program === 'make' && (next === 'test' || next === 'check')) ||
77
+ (program === 'node' && tokens.includes('--test')) ||
78
+ (python && module > 0 && /^(pytest|unittest)$/.test(tokens[module + 1] ?? '')) ||
79
+ TEST_SCRIPT.test(scriptOf(tokens) ?? ''));
80
+ }
81
+ function scriptOf(tokens) {
82
+ let at = 0;
83
+ if (RUNNER.test(tokens[0]?.split('/').at(-1) ?? '')) {
84
+ at++;
85
+ while (tokens[at]?.startsWith('-')) {
86
+ at++;
87
+ }
88
+ }
89
+ return tokens[at]?.split('/').at(-1);
90
+ }
15
91
  export function namedChecks(text) {
16
92
  const lines = text.split('\n');
17
93
  const heading = lines.findIndex((line) => CHECKS_HEADING.test(line));
@@ -47,22 +123,25 @@ function normalize(command) {
47
123
  return command.trim().replace(/\s+/g, ' ');
48
124
  }
49
125
  export function runsCheck(command, check) {
50
- const wanted = words(check);
126
+ const named = words(check);
127
+ const wanted = named.slice(Math.max(commandStart(named), 0));
128
+ return exitSegments(command).some((segment) => invokes(words(segment), wanted));
129
+ }
130
+ function exitSegments(command) {
51
131
  const parts = command.split(SHELL_OPERATOR);
52
132
  for (let at = parts.length - 1; at >= 0; at -= 2) {
53
133
  if (!parts[at].trim()) {
54
134
  parts.splice(at === parts.length - 1 ? Math.max(at - 1, 0) : at, 2);
55
135
  }
56
136
  }
137
+ const segments = [];
57
138
  for (let at = 0; at < parts.length; at += 2) {
58
139
  const after = parts.slice(at + 1).filter((_, n) => n % 2 === 0);
59
- if (parts[at - 1] !== '||' &&
60
- after.every((operator) => operator === '&&') &&
61
- invokes(words(parts[at]), wanted)) {
62
- return true;
140
+ if (parts[at - 1] !== '||' && after.every((operator) => operator === '&&')) {
141
+ segments.push(parts[at].trim());
63
142
  }
64
143
  }
65
- return false;
144
+ return segments;
66
145
  }
67
146
  function words(text) {
68
147
  return text
@@ -72,7 +151,7 @@ function words(text) {
72
151
  .map((word) => word.replace(/^['"]|['"]$/g, ''));
73
152
  }
74
153
  function invokes(tokens, wanted) {
75
- let start = tokens.findIndex((token) => !/^\w+=/.test(token));
154
+ let start = commandStart(tokens);
76
155
  if (start < 0) {
77
156
  return false;
78
157
  }
@@ -88,6 +167,9 @@ function invokes(tokens, wanted) {
88
167
  }
89
168
  return leads(tokens.slice(start), wanted);
90
169
  }
170
+ function commandStart(tokens) {
171
+ return tokens.findIndex((token) => !/^\w+=/.test(token));
172
+ }
91
173
  function leads(tokens, wanted) {
92
174
  return (wanted.length > 0 &&
93
175
  wanted.every((word, at) => tokens[at] !== undefined && samePath(tokens[at], word)));
@@ -1,11 +1,14 @@
1
1
  export function stripHtmlTags(text) {
2
- let out = text;
3
- let prev = '';
4
- while (out !== prev) {
5
- prev = out;
6
- out = out.replace(/<[^>]*>/g, '');
2
+ const lastClose = text.lastIndexOf('>');
3
+ let out = '';
4
+ let at = 0;
5
+ let open = text.indexOf('<');
6
+ while (open !== -1 && open < lastClose) {
7
+ out += text.slice(at, open);
8
+ at = text.indexOf('>', open) + 1;
9
+ open = text.indexOf('<', at);
7
10
  }
8
- return out;
11
+ return out + text.slice(at);
9
12
  }
10
13
  const NAMED_ENTITIES = {
11
14
  '&lt;': '<',
@@ -0,0 +1,8 @@
1
+ export declare const MAX_PENDING_INPUTS = 64;
2
+ export declare const MAX_PENDING_INPUT_BYTES: number;
3
+ export declare function inputBytes<T extends {
4
+ text: string;
5
+ }>(input: T): number;
6
+ export declare function acceptsInput<T extends {
7
+ text: string;
8
+ }>(count: number, bytes: number, input: T): boolean;
@@ -0,0 +1,9 @@
1
+ import b4a from 'b4a';
2
+ export const MAX_PENDING_INPUTS = 64;
3
+ export const MAX_PENDING_INPUT_BYTES = 256 * 1024;
4
+ export function inputBytes(input) {
5
+ return b4a.byteLength(JSON.stringify(input), 'utf8');
6
+ }
7
+ export function acceptsInput(count, bytes, input) {
8
+ return count < MAX_PENDING_INPUTS && bytes + inputBytes(input) <= MAX_PENDING_INPUT_BYTES;
9
+ }
@@ -19,7 +19,7 @@ export declare function continueStop({ context, params }: CompletionActionArgs<A
19
19
  export declare function settleGoal({ context }: CompletionActionArgs): Partial<CompletionContext>;
20
20
  export declare function finishRound({ context, params }: CompletionActionArgs<RoundDonePayload>): Partial<CompletionContext>;
21
21
  export declare function finishWrapRound({ context, params }: CompletionActionArgs<RoundDonePayload>): Partial<CompletionContext>;
22
- export declare function wrapCompletion({ params }: CompletionActionArgs<RunOutcome>): Partial<CompletionContext>;
22
+ export declare function wrapCompletion({ context, params }: CompletionActionArgs<RunOutcome>): Partial<CompletionContext>;
23
23
  export declare function wrapMuteCompletion(args: CompletionActionArgs<AnsweredPayload>): Partial<CompletionContext>;
24
24
  export declare function wrapSearchCappedCompletion({ context }: CompletionActionArgs): Partial<CompletionContext>;
25
25
  export declare function wrapDeliveredCompletion({ context }: CompletionActionArgs): Partial<CompletionContext>;
@@ -1,5 +1,5 @@
1
1
  import { hasRoundsLeft, stuckResult } from '../guards/retry.js';
2
- import { mergeChecks, namedChecks } from '../../../helpers/goal-check.js';
2
+ import { asksChecks, mergeChecks, namedChecks } from '../../../helpers/goal-check.js';
3
3
  import { activate, applyHistorySplice, applySplice, foldMetrics, goalMet, goalTokensLeft, nudgeWithChecks, nudgeWithPlan, retainFailureResults, settledSince } from '../rules.js';
4
4
  export function startInitialRound({ context, params }) {
5
5
  return applyPreparation(context, params);
@@ -102,21 +102,27 @@ function closeFailureMemo(context) {
102
102
  roundProgressed: false
103
103
  };
104
104
  }
105
- function endToolRound(context) {
105
+ function endToolRound(context, { last = false } = {}) {
106
106
  return {
107
- history: [...context.history, ...continuation(context)],
107
+ history: [...context.history, ...continuation(context, { last })],
108
108
  steering: [],
109
109
  delivered: context.delivered || context.deliveryEndsRun,
110
110
  deliveredThisRound: false,
111
111
  deliveryEndsRun: false
112
112
  };
113
113
  }
114
- function continuation(context) {
115
- const { policy, deliveredThisRound, plan } = context;
116
- const nudge = deliveredThisRound ? policy.deliveredNudge : policy.continuationNudge;
114
+ function continuation(context, { last = false } = {}) {
115
+ const { plan } = context;
117
116
  return context.steering.length
118
117
  ? userTurns(context.steering)
119
- : [{ role: 'user', content: nudgeWithPlan(nudge, plan) }];
118
+ : [{ role: 'user', content: nudgeWithPlan(roundNudge(context, last), plan) }];
119
+ }
120
+ function roundNudge(context, last) {
121
+ const { policy, deliveredThisRound } = context;
122
+ if (deliveredThisRound) {
123
+ return policy.deliveredNudge;
124
+ }
125
+ return last ? (policy.wrapUpNudge ?? policy.continuationNudge) : policy.continuationNudge;
120
126
  }
121
127
  function userTurns(queued) {
122
128
  return queued.map(({ text, content }) => ({ role: 'user', content: content ?? text }));
@@ -153,7 +159,7 @@ export function addKnowledge({ context, params }) {
153
159
  }
154
160
  export function goalTurn({ policy, goal, plan }, stall) {
155
161
  const nudge = stall ? `${policy.goalNudge}\n${stall}` : policy.goalNudge;
156
- return nudgeWithChecks(nudgeWithPlan(`${nudge}\nGoal: ${goal?.objective ?? ''}`, plan), goal?.checks ?? [], goal?.checkable && !goal.named);
162
+ return nudgeWithChecks(nudgeWithPlan(`${nudge}\nGoal: ${goal?.objective ?? ''}`, plan), goal?.checks ?? [], !!goal && asksChecks(goal));
157
163
  }
158
164
  export function continueStalledGoal({ context }) {
159
165
  const { goal, policy } = context;
@@ -268,20 +274,34 @@ function settledAfterSend(context, params) {
268
274
  }
269
275
  : {};
270
276
  }
271
- export function wrapCompletion({ params }) {
272
- return { outcome: params };
277
+ export function wrapCompletion({ context, params }) {
278
+ return { ...swapStandingNudge(context), outcome: params };
279
+ }
280
+ function swapStandingNudge(context) {
281
+ const last = context.history.at(-1);
282
+ const [standing] = continuation(context);
283
+ if (!last || !standing || !('role' in last) || !('role' in standing)) {
284
+ return {};
285
+ }
286
+ if (last.role !== 'user' || last.content !== standing.content) {
287
+ return {};
288
+ }
289
+ return { history: [...context.history.slice(0, -1), ...continuation(context, { last: true })] };
273
290
  }
274
291
  export function wrapMuteCompletion(args) {
275
- return { ...silentTurn(args), outcome: 'mute' };
292
+ const turns = args.params.cutOff
293
+ ? swapStandingNudge(args.context)
294
+ : silentTurn(args, continuation(args.context, { last: true }));
295
+ return { ...turns, outcome: 'mute' };
276
296
  }
277
297
  export function wrapSearchCappedCompletion({ context }) {
278
- return { ...endToolRound(context), outcome: 'search-capped' };
298
+ return { ...endToolRound(context, { last: true }), outcome: 'search-capped' };
279
299
  }
280
300
  export function wrapDeliveredCompletion({ context }) {
281
- return { ...endToolRound(context), outcome: 'delivered' };
301
+ return { ...endToolRound(context, { last: true }), outcome: 'delivered' };
282
302
  }
283
303
  export function wrapExhaustedCompletion({ context }) {
284
- return { ...endToolRound(context), outcome: 'exhausted' };
304
+ return { ...endToolRound(context, { last: true }), outcome: 'exhausted' };
285
305
  }
286
306
  export function answerCompletion({ context, params }) {
287
307
  const historyState = applyHistorySplice(context, params.history);
@@ -1,6 +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
5
  export function resolveTools({ context, params }) {
5
6
  return {
6
7
  toolQueue: [...params.calls],
@@ -214,7 +215,7 @@ function applyToolResult(context, payload, call) {
214
215
  metrics: recordTool(context, call, payload.durationMs),
215
216
  activated: activate(context.activated, payload.activate ? [payload.activate] : []),
216
217
  plan: payload.plan ?? context.plan,
217
- goal: applyChecks(context.goal, payload.checked),
218
+ goal: applyChecks(adoptProof(context.goal, payload.proved), payload.checked),
218
219
  planMode: context.planMode && payload.leftPlanMode !== true,
219
220
  pendingCall: null,
220
221
  approval: { status: 'idle', key: null },
@@ -297,3 +298,20 @@ function applyChecks(goal, checked) {
297
298
  checks: goal.checks.map((check) => checked.find(({ name }) => name === check.name) ?? check)
298
299
  };
299
300
  }
301
+ function adoptProof(goal, proved) {
302
+ if (!goal ||
303
+ !proved ||
304
+ !asksChecks(goal) ||
305
+ !existenceOnly(goal.checks.map((check) => check.name))) {
306
+ return goal;
307
+ }
308
+ const names = mergeChecks(goal.checks.map((check) => check.name), [proved.name]);
309
+ if (!names.length) {
310
+ return goal;
311
+ }
312
+ return {
313
+ ...goal,
314
+ checks: names.map((name) => goal.checks.find((check) => check.name === name) ?? proved),
315
+ named: true
316
+ };
317
+ }
@@ -42,6 +42,7 @@ export interface FinishedRound {
42
42
  ctxSize?: number | undefined;
43
43
  overflows?: number | undefined;
44
44
  reasoningDeltas?: number | undefined;
45
+ keyed?: boolean | undefined;
45
46
  }
46
47
  export declare function foldMetrics(state: MetricsState, round: number, finished: FinishedRound): void;
47
48
  type StoppedRound = Pick<FinishedRound, 'stats' | 'stopReason'> & {
@@ -1,5 +1,5 @@
1
1
  import { isFailureResultReference } from '../../helpers/failure-result.js';
2
- import { GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../helpers/goal-check.js';
2
+ import { asksChecks, 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,7 +35,7 @@ function planDone(plan) {
35
35
  }
36
36
  export function goalMet({ plan, goal }) {
37
37
  const checks = goal?.checks ?? [];
38
- return (planDone(plan) && (goal?.named || !goal?.checkable) && checks.every((check) => check.passed));
38
+ return planDone(plan) && !(goal && asksChecks(goal)) && checks.every((check) => check.passed);
39
39
  }
40
40
  export function nudgeWithChecks(nudge, checks, unnamed) {
41
41
  if (!checks.length) {
@@ -96,6 +96,9 @@ export function foldMetrics(state, round, finished) {
96
96
  state.ctxSize = finished.ctxSize;
97
97
  }
98
98
  if (!stats) {
99
+ if (finished.keyed === false) {
100
+ delete state.cacheTokens;
101
+ }
99
102
  return;
100
103
  }
101
104
  if (state.ttft === undefined && stats.timeToFirstToken) {
@@ -108,12 +111,15 @@ export function foldMetrics(state, round, finished) {
108
111
  state.timedTokens += stats.generatedTokens;
109
112
  }
110
113
  }
111
- if (stats.promptTokens) {
114
+ if (stats.promptTokens !== undefined) {
112
115
  state.promptTokens = stats.promptTokens;
113
116
  }
114
- if (stats.cacheTokens) {
117
+ if (stats.cacheTokens !== undefined) {
115
118
  state.cacheTokens = stats.cacheTokens;
116
119
  }
120
+ if (finished.keyed === false && stats.cacheTokens === undefined) {
121
+ delete state.cacheTokens;
122
+ }
117
123
  }
118
124
  const ROUND_STATS = [
119
125
  'promptTokens',
@@ -123,7 +129,7 @@ const ROUND_STATS = [
123
129
  'tokensPerSecond',
124
130
  'timeToFirstToken'
125
131
  ];
126
- function roundSpeed(round, { stats, stopReason, durationMs, overflows, reasoningDeltas }) {
132
+ function roundSpeed(round, { stats, stopReason, durationMs, overflows, reasoningDeltas, keyed }) {
127
133
  const speed = { round, durationMs: durationMs ?? 0 };
128
134
  for (const key of ROUND_STATS) {
129
135
  const value = stats?.[key];
@@ -131,6 +137,9 @@ function roundSpeed(round, { stats, stopReason, durationMs, overflows, reasoning
131
137
  speed[key] = value;
132
138
  }
133
139
  }
140
+ if (keyed === false) {
141
+ speed.cacheTokens = 0;
142
+ }
134
143
  if (stopReason) {
135
144
  speed.stopReason = stopReason;
136
145
  }
@@ -81,6 +81,7 @@ export interface RoundDonePayload {
81
81
  response?: string;
82
82
  history?: HistorySplice;
83
83
  cacheable?: boolean;
84
+ keyed?: boolean;
84
85
  fallbackResponse?: string;
85
86
  cut?: string;
86
87
  }
@@ -156,6 +157,7 @@ export interface ToolDonePayload {
156
157
  plan?: PlanStep[];
157
158
  leftPlanMode?: boolean;
158
159
  checked?: GoalCheck[];
160
+ proved?: GoalCheck;
159
161
  }
160
162
  export interface BatchDonePayload {
161
163
  history?: HistorySplice;
@@ -249,6 +251,7 @@ export interface RunPolicy {
249
251
  maxToolRounds: number;
250
252
  continuationNudge: string;
251
253
  deliveredNudge: string;
254
+ wrapUpNudge?: string;
252
255
  deniedMessage: string;
253
256
  cutOffMessage: string;
254
257
  contextBoundaryMessage: string;
@@ -115,6 +115,7 @@ export declare class PluginRegistry {
115
115
  private _ownDispose;
116
116
  private _setUp;
117
117
  private _drop;
118
+ private _forget;
118
119
  private _check;
119
120
  private _removable;
120
121
  private _swap;