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

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 (74) 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/preparing.js +11 -6
  7. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.d.ts +2 -1
  8. package/dist-lib/lib/capabilities/completion-engine/actors/retrieving.js +19 -11
  9. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +3 -0
  10. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +10 -2
  11. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +3 -0
  12. package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
  13. package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
  14. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
  15. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
  16. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  17. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +2 -0
  18. package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
  19. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +3 -0
  20. package/dist-lib/lib/capabilities/completion-engine/round.js +38 -19
  21. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
  22. package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
  23. package/dist-lib/lib/capabilities/tool-turns.d.ts +1 -0
  24. package/dist-lib/lib/capabilities/tool-turns.js +1 -0
  25. package/dist-lib/lib/connect.js +4 -2
  26. package/dist-lib/lib/contract/completion.d.ts +2 -1
  27. package/dist-lib/lib/contract/knowledge.d.ts +10 -0
  28. package/dist-lib/lib/fold/index.d.ts +3 -2
  29. package/dist-lib/lib/fold/index.js +7 -6
  30. package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
  31. package/dist-lib/lib/helpers/goal-check.js +89 -7
  32. package/dist-lib/lib/helpers/html-helpers.js +9 -6
  33. package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
  34. package/dist-lib/lib/helpers/input-budget.js +9 -0
  35. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  36. package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
  37. package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
  38. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  39. package/dist-lib/lib/machine/completion/rules.js +14 -5
  40. package/dist-lib/lib/machine/completion/types.d.ts +3 -0
  41. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  42. package/dist-lib/lib/plugins/registry.js +49 -10
  43. package/dist-lib/lib/residency/index.js +2 -0
  44. package/dist-lib/lib/serve.js +56 -15
  45. package/dist-lib/lib/tools/files/glob.js +2 -2
  46. package/dist-lib/lib/tools/files/read-file.js +134 -15
  47. package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
  48. package/dist-lib/lib/tools/fs/walk.js +2 -1
  49. package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
  50. package/dist-lib/lib/tools/http-request.js +28 -11
  51. package/dist-lib/lib/tools/office.d.ts +1 -1
  52. package/dist-lib/lib/tools/office.js +34 -12
  53. package/dist-lib/lib/wire.js +23 -3
  54. package/dist-lib/plugins/knowledge/index.js +1 -0
  55. package/dist-lib/plugins/knowledge/manifest.d.ts +29 -0
  56. package/dist-lib/plugins/knowledge/manifest.js +41 -0
  57. package/dist-lib/plugins/knowledge/search-tool.js +8 -8
  58. package/dist-lib/plugins/knowledge/store.d.ts +35 -7
  59. package/dist-lib/plugins/knowledge/store.js +335 -143
  60. package/dist-lib/plugins/mcp/call.js +10 -3
  61. package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
  62. package/dist-lib/plugins/mcp/protocol.js +11 -10
  63. package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
  64. package/dist-lib/plugins/mcp/tool-listing.js +97 -0
  65. package/dist-lib/plugins/music/generate-music.js +2 -2
  66. package/dist-lib/plugins/python/language.js +2 -2
  67. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  68. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  69. package/dist-lib/schema/harness.js +4 -2
  70. package/dist-lib/spec/hrpc/messages.js +19 -4
  71. package/dist-lib/spec/hyperschema/index.js +19 -4
  72. package/dist-lib/spec/hyperschema/schema.json +12 -1
  73. package/dist-lib/spec/hyperschema/types.d.ts +2 -0
  74. package/package.json +5 -1
@@ -19,6 +19,8 @@ export interface ModelRoundRequest {
19
19
  promptPrefix: string;
20
20
  continuationNudge: string;
21
21
  deliveredNudge: string;
22
+ goalNudge?: string | undefined;
23
+ wrapUpNudge?: string | undefined;
22
24
  unforced?: {
23
25
  generationParams?: Partial<LlmGenerationParams> | undefined;
24
26
  } | undefined;
@@ -67,6 +67,8 @@ function servedArgs(request, signal, acquireRound) {
67
67
  failureResults: {},
68
68
  continuationNudge: request.continuationNudge,
69
69
  deliveredNudge: request.deliveredNudge,
70
+ goalNudge: request.goalNudge,
71
+ wrapUpNudge: request.wrapUpNudge,
70
72
  tools: request.tools,
71
73
  generationParams: request.generationParams,
72
74
  responseFormat: request.responseFormat,
@@ -15,6 +15,7 @@ export interface RecoveredRound {
15
15
  final: CompletionFinal;
16
16
  history: CompletionHistoryEntry[];
17
17
  cacheable: boolean;
18
+ keyed: boolean;
18
19
  unproven: string | null;
19
20
  replay: string | null;
20
21
  reasoningDeltas?: number | undefined;
@@ -30,6 +31,8 @@ export interface RoundArgs {
30
31
  failureResults: Readonly<Record<string, FailureResultValue>>;
31
32
  continuationNudge: string;
32
33
  deliveredNudge: string;
34
+ goalNudge?: string | undefined;
35
+ wrapUpNudge?: string | undefined;
33
36
  tools?: SdkTool[] | undefined;
34
37
  generationParams?: Partial<LlmGenerationParams> | undefined;
35
38
  responseFormat?: ResponseFormat | undefined;
@@ -18,6 +18,7 @@ import { detachJson } from '../../helpers/detach-json.js';
18
18
  import { isSkillMentionNudge, materializeCompletionHistory } from '../tool-turns.js';
19
19
  import { completionParams } from '../../helpers/completion-params.js';
20
20
  import { isFailureResultReference } from '../../helpers/failure-result.js';
21
+ import { GOAL_CHECKS_ASK, GOAL_PROOF_ASK } from '../../helpers/goal-check.js';
21
22
  import { Fold } from '../../fold/index.js';
22
23
  import { CompletionMachine } from '../../machine/index.js';
23
24
  import { modelTurns } from './turns.js';
@@ -75,7 +76,9 @@ async function* runRoundTokens({ result, state, cancelThisRound, unsettled, sign
75
76
  const events = splitThinking(bufferBurst(countGenerated(counted, state), BURST_WINDOW_MS), {
76
77
  startInThink
77
78
  });
78
- const thinkingFilter = createMarkupStreamFilter();
79
+ const thinkingFilter = createMarkupStreamFilter({
80
+ onToolCall: watchMarkupCalls(state, knownTools, cancelThisRound)
81
+ });
79
82
  const contentFilter = createMarkupStreamFilter({
80
83
  onToolCall: watchMarkupCalls(state, knownTools, cancelThisRound)
81
84
  });
@@ -312,7 +315,7 @@ function releaseLease(lease) {
312
315
  export async function recordWholeRound(args) {
313
316
  const history = materializeCompletionHistory(args.history, args.failureResults);
314
317
  const origins = historyOrigins(args.history, history);
315
- const params = inferenceParams({ args, modelId: args.modelId, history, cacheable: true });
318
+ const params = inferenceParams({ args, modelId: args.modelId, history });
316
319
  await args.recordRequest?.({ round: args.round, attempt: 0, droppedTurns: 0, params }, failureTurns(args, origins, history));
317
320
  if (args.signal?.aborted) {
318
321
  throw new AbortedError();
@@ -342,10 +345,12 @@ async function* runRecoveredRoundWith(send) {
342
345
  }
343
346
  async function* runLadder({ send, history, origins, fold }) {
344
347
  let lastOverflow = null;
345
- for (const candidate of contextCandidates(history, ...roundNudges(send.args, history))) {
348
+ const candidates = contextCandidates(history, ...harnessTurns(send.args, history));
349
+ for (const candidate of candidates) {
346
350
  const outcome = yield* runCandidateAttempts({ ...send, candidate, history, origins });
347
351
  if ('round' in outcome) {
348
- return { round: recoveredRound({ candidate, attempt: outcome.round, origins }) };
352
+ const cacheable = !send.attempts.uncached;
353
+ return { round: recoveredRound({ candidate, attempt: outcome.round, origins, cacheable }) };
349
354
  }
350
355
  lastOverflow = outcome.overflow;
351
356
  send.attempts.overflows++;
@@ -354,6 +359,9 @@ async function* runLadder({ send, history, origins, fold }) {
354
359
  if (folded) {
355
360
  return { folded };
356
361
  }
362
+ if (candidates.length > 1) {
363
+ await dropShrunkKey(send);
364
+ }
357
365
  }
358
366
  }
359
367
  if (!lastOverflow) {
@@ -375,15 +383,21 @@ async function* foldHistory(send, history, tries) {
375
383
  tries.rounds = true;
376
384
  return foldRounds(send, history);
377
385
  }
378
- function roundNudges(args, history) {
386
+ function harnessTurns(args, history) {
379
387
  const mentions = history.flatMap((message) => message.role === 'user' && isSkillMentionNudge(message.content) ? [message.content] : []);
380
- return [args.continuationNudge, args.deliveredNudge, ...mentions];
388
+ const wrapUp = args.wrapUpNudge === undefined ? [] : [args.wrapUpNudge];
389
+ return [args.continuationNudge, args.deliveredNudge, ...wrapUp, ...goalTurns(args), ...mentions];
390
+ }
391
+ function goalTurns(args) {
392
+ const goal = args.goalNudge === undefined ? [] : [args.goalNudge];
393
+ return [...goal, GOAL_CHECKS_ASK, GOAL_PROOF_ASK];
381
394
  }
382
395
  async function foldRounds(send, history) {
383
396
  const { sdk, args, ctxSize } = send;
384
397
  const spec = args.fold;
385
- const nudges = roundNudges(args, history);
386
- if (!spec || !Fold.roundBoundary(history, { nudges, keeps: keepsLoad })?.foldedRounds) {
398
+ const nudges = harnessTurns(args, history);
399
+ const goals = goalTurns(args);
400
+ if (!spec || !Fold.roundBoundary(history, { nudges, goals, keeps: keepsLoad })?.foldedRounds) {
387
401
  return null;
388
402
  }
389
403
  const instructions = await spec.instructions?.(history);
@@ -391,6 +405,7 @@ async function foldRounds(send, history) {
391
405
  ctxSize,
392
406
  instructions,
393
407
  nudges,
408
+ goals,
394
409
  keeps: keepsLoad
395
410
  });
396
411
  if (args.signal?.aborted) {
@@ -453,6 +468,11 @@ async function* foldChat(send, history) {
453
468
  };
454
469
  return folded;
455
470
  }
471
+ async function dropShrunkKey({ sdk, args, attempts }) {
472
+ if (args.cacheKey && !attempts.uncached) {
473
+ await dropFoldedKey(sdk, args.cacheKey);
474
+ }
475
+ }
456
476
  async function dropFoldedKey(sdk, cacheKey) {
457
477
  Fold.forget(cacheKey);
458
478
  try {
@@ -543,10 +563,9 @@ async function* runCandidateAttempts(input) {
543
563
  modelId,
544
564
  candidate,
545
565
  progress,
546
- baseHistory: history,
547
566
  origins
548
567
  });
549
- return { round: attempts.uncached ? { ...round, cacheable: false } : round };
568
+ return { round };
550
569
  }
551
570
  catch (err) {
552
571
  if (err instanceof AbortedError || args.signal?.aborted) {
@@ -628,14 +647,15 @@ async function flushCandidate(args, progress) {
628
647
  }
629
648
  await raceTimeout(progress.cancel.flush(), { ms: TRUNCATED_FINAL_MS, fallback: undefined });
630
649
  }
631
- function recoveredRound({ candidate, attempt, origins }) {
650
+ function recoveredRound({ candidate, attempt, origins, cacheable }) {
632
651
  const replay = unprovenReplay(attempt.state, attempt.final);
633
652
  logCandidateFinal(attempt, replay);
634
653
  return {
635
654
  contentText: attempt.contentText,
636
655
  final: attempt.final,
637
656
  history: restoreHistory(candidate.history, origins),
638
- cacheable: attempt.cacheable,
657
+ cacheable,
658
+ keyed: attempt.keyed,
639
659
  unproven: attempt.state.unproven,
640
660
  replay,
641
661
  reasoningDeltas: attempt.state.reasoningDeltas || undefined,
@@ -655,16 +675,15 @@ function historyOrigins(entries, messages) {
655
675
  });
656
676
  return origins;
657
677
  }
658
- async function* runCandidate({ sdk, args, modelId, candidate, progress, baseHistory, origins }) {
659
- const cacheable = candidate.history === baseHistory;
660
- const params = inferenceParams({ args, modelId, history: candidate.history, cacheable });
678
+ async function* runCandidate({ sdk, args, modelId, candidate, progress, origins }) {
679
+ const params = inferenceParams({ args, modelId, history: candidate.history });
661
680
  if (args.capture) {
662
681
  yield inferenceCall({
663
682
  args,
664
683
  droppedTurns: candidate.droppedTurns,
665
684
  modelId,
666
685
  params,
667
- cacheKey: cacheable ? args.cacheKey : undefined
686
+ cacheKey: args.cacheKey
668
687
  });
669
688
  }
670
689
  await args.recordRequest?.({
@@ -704,9 +723,9 @@ async function* runCandidate({ sdk, args, modelId, candidate, progress, baseHist
704
723
  if (args.capture) {
705
724
  yield inferenceSent({ args, candidate, final: detachedFinal });
706
725
  }
707
- return { contentText, final: detachedFinal, state, cacheable };
726
+ return { contentText, final: detachedFinal, state, keyed: args.cacheKey !== undefined };
708
727
  }
709
- function inferenceParams({ args, modelId, history, cacheable }) {
728
+ function inferenceParams({ args, modelId, history }) {
710
729
  return completionParams({
711
730
  modelId,
712
731
  history: detachJson(history),
@@ -714,7 +733,7 @@ function inferenceParams({ args, modelId, history, cacheable }) {
714
733
  generationParams: generationParams(args),
715
734
  responseFormat: args.responseFormat ? detachJson(args.responseFormat) : undefined,
716
735
  toolDialect: args.toolDialect,
717
- kvCache: cacheable ? args.cacheKey : undefined
736
+ kvCache: args.cacheKey
718
737
  });
719
738
  }
720
739
  function generationParams(args) {
@@ -1,3 +1,4 @@
1
+ import type { KnowledgeHit, KnowledgeSource } from '../../contract/knowledge.ts';
1
2
  import type { CompletionHistoryEntry, Message, ToolDefinition, TrustedSource, TurnContext } from '../../contract/index.ts';
2
3
  export declare function trustedSourcesFrom(history: readonly Message[]): TrustedSource[];
3
4
  export declare function sanitizeTurn(turn: Message, answered?: boolean): Message;
@@ -26,6 +27,8 @@ interface AssistantToolCall {
26
27
  export declare function assistantToolTurn(contentText: string, calls: ReadonlyArray<AssistantToolCall>): string;
27
28
  export declare function withLastUserNote(messages: readonly CompletionHistoryEntry[], note: string): CompletionHistoryEntry[];
28
29
  export declare function turnText(text: string, { time, excerpts, notes }: TurnContext): string;
30
+ export declare function knowledgeExcerpt({ text, metadata }: KnowledgeHit): string;
31
+ export declare function knowledgeSources(hits: readonly KnowledgeHit[]): KnowledgeSource[];
29
32
  export declare function withTurnContext(messages: readonly Message[], context: TurnContext): Message[];
30
33
  export declare function carriesRunOnlyText(history: readonly CompletionHistoryEntry[]): boolean;
31
34
  export declare function annotateCompletionHistoryLastUserTime(history: readonly CompletionHistoryEntry[], now?: Date): CompletionHistoryEntry[];
@@ -186,6 +186,22 @@ export function turnText(text, { time, excerpts, notes }) {
186
186
  const body = notes === undefined ? `${found}${text}` : `${found}${text}${NOTES_HEAD}${notes}`;
187
187
  return time === undefined ? body : `${time}\n\n${body}`;
188
188
  }
189
+ export function knowledgeExcerpt({ text, metadata }) {
190
+ const title = metadata?.title;
191
+ if (typeof title !== 'string' || !title) {
192
+ return text;
193
+ }
194
+ const page = typeof metadata?.page === 'number' ? `, page ${metadata.page}` : '';
195
+ return `${title}${page}:\n${text}`;
196
+ }
197
+ export function knowledgeSources(hits) {
198
+ return hits.map(({ artifactId, chunkId, score, metadata }) => ({
199
+ artifactId,
200
+ chunkId,
201
+ score,
202
+ metadata
203
+ }));
204
+ }
189
205
  export function withTurnContext(messages, context) {
190
206
  const at = messages.findLastIndex((turn) => turn.role === 'user');
191
207
  const user = messages[at];
@@ -7,6 +7,7 @@ export declare const MAX_TOOL_ROUNDS = 10;
7
7
  export declare const GOAL_ROUNDS = 40;
8
8
  export declare const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
9
9
  export declare const FILE_DELIVERED_NUDGE = "[Tool results above. The file is attached to the chat and shown to the user. Answer now, unless the request still needs a file that is not made yet.]";
10
+ export declare const WRAP_UP_NUDGE = "[Tool results above. No tool can be called for this reply. Answer the user's request now, in plain text.]";
10
11
  export declare function skillMentionNudge(handle: string): string;
11
12
  export declare function isSkillMentionNudge(content: string): boolean;
12
13
  export { TOOL_FAILED_NOTE };
@@ -13,6 +13,7 @@ export const MAX_TOOL_ROUNDS = 10;
13
13
  export const GOAL_ROUNDS = 40;
14
14
  export const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
15
15
  export const FILE_DELIVERED_NUDGE = '[Tool results above. The file is attached to the chat and shown to the user. Answer now, unless the request still needs a file that is not made yet.]';
16
+ export const WRAP_UP_NUDGE = "[Tool results above. No tool can be called for this reply. Answer the user's request now, in plain text.]";
16
17
  const MENTION_NUDGE_PREFIX = '[Tool results above. The user picked @';
17
18
  export function skillMentionNudge(handle) {
18
19
  return `${MENTION_NUDGE_PREFIX}${handle} for this request. If @${handle} cannot do what they asked, or what it works on is not in this chat, call no tool: tell them in one sentence that @${handle} cannot do this, and why. Otherwise continue: call the next tool, or answer.]`;
@@ -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>;