@qvac/harness 1.0.0-rc.11 → 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 (79) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -1
  3. package/dist-lib/index.js +1 -2
  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.d.ts +3 -2
  10. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +21 -3
  11. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +11 -2
  12. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +4 -0
  13. package/dist-lib/lib/capabilities/completion-engine/driver.js +2 -1
  14. package/dist-lib/lib/capabilities/completion-engine/engine.js +39 -23
  15. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.d.ts +20 -0
  16. package/dist-lib/lib/capabilities/completion-engine/event-mailbox.js +110 -0
  17. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +1 -0
  18. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +4 -1
  19. package/dist-lib/lib/capabilities/completion-engine/model-round.js +2 -0
  20. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +11 -0
  21. package/dist-lib/lib/capabilities/completion-engine/round.js +41 -22
  22. package/dist-lib/lib/capabilities/completion-engine/turns.d.ts +3 -0
  23. package/dist-lib/lib/capabilities/completion-engine/turns.js +16 -0
  24. package/dist-lib/lib/capabilities/tool-failed-note.d.ts +1 -0
  25. package/dist-lib/lib/capabilities/tool-failed-note.js +1 -0
  26. package/dist-lib/lib/capabilities/tool-turns.d.ts +3 -1
  27. package/dist-lib/lib/capabilities/tool-turns.js +8 -1
  28. package/dist-lib/lib/connect.js +4 -2
  29. package/dist-lib/lib/contract/completion.d.ts +2 -1
  30. package/dist-lib/lib/contract/knowledge.d.ts +10 -0
  31. package/dist-lib/lib/fold/index.d.ts +3 -2
  32. package/dist-lib/lib/fold/index.js +7 -6
  33. package/dist-lib/lib/helpers/goal-check.d.ts +12 -0
  34. package/dist-lib/lib/helpers/goal-check.js +89 -7
  35. package/dist-lib/lib/helpers/html-helpers.js +9 -6
  36. package/dist-lib/lib/helpers/input-budget.d.ts +8 -0
  37. package/dist-lib/lib/helpers/input-budget.js +9 -0
  38. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  39. package/dist-lib/lib/machine/completion/actions/completion.js +34 -14
  40. package/dist-lib/lib/machine/completion/actions/tools.js +19 -1
  41. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  42. package/dist-lib/lib/machine/completion/rules.js +14 -5
  43. package/dist-lib/lib/machine/completion/types.d.ts +3 -0
  44. package/dist-lib/lib/plugins/registry.d.ts +1 -0
  45. package/dist-lib/lib/plugins/registry.js +49 -10
  46. package/dist-lib/lib/residency/index.d.ts +1 -1
  47. package/dist-lib/lib/residency/index.js +4 -2
  48. package/dist-lib/lib/serve.js +56 -15
  49. package/dist-lib/lib/tools/files/glob.js +2 -2
  50. package/dist-lib/lib/tools/files/read-file.js +134 -15
  51. package/dist-lib/lib/tools/fs/walk.d.ts +1 -0
  52. package/dist-lib/lib/tools/fs/walk.js +2 -1
  53. package/dist-lib/lib/tools/http-request/truncate-response.js +11 -2
  54. package/dist-lib/lib/tools/http-request.js +28 -11
  55. package/dist-lib/lib/tools/office.d.ts +1 -1
  56. package/dist-lib/lib/tools/office.js +34 -12
  57. package/dist-lib/lib/wire.js +23 -3
  58. package/dist-lib/plugins/knowledge/index.js +1 -0
  59. package/dist-lib/plugins/knowledge/manifest.d.ts +29 -0
  60. package/dist-lib/plugins/knowledge/manifest.js +41 -0
  61. package/dist-lib/plugins/knowledge/search-tool.js +8 -8
  62. package/dist-lib/plugins/knowledge/store.d.ts +35 -7
  63. package/dist-lib/plugins/knowledge/store.js +335 -143
  64. package/dist-lib/plugins/mcp/call.js +10 -3
  65. package/dist-lib/plugins/mcp/protocol.d.ts +4 -1
  66. package/dist-lib/plugins/mcp/protocol.js +11 -10
  67. package/dist-lib/plugins/mcp/tool-listing.d.ts +6 -0
  68. package/dist-lib/plugins/mcp/tool-listing.js +97 -0
  69. package/dist-lib/plugins/music/generate-music.js +2 -2
  70. package/dist-lib/plugins/python/language.js +2 -2
  71. package/dist-lib/plugins/run-report/story.js +4 -1
  72. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  73. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  74. package/dist-lib/schema/harness.js +4 -2
  75. package/dist-lib/spec/hrpc/messages.js +19 -4
  76. package/dist-lib/spec/hyperschema/index.js +19 -4
  77. package/dist-lib/spec/hyperschema/schema.json +12 -1
  78. package/dist-lib/spec/hyperschema/types.d.ts +2 -0
  79. package/package.json +9 -1
@@ -0,0 +1,110 @@
1
+ import b4a from 'b4a';
2
+ export const EVENT_MAILBOX_MAX_EVENTS = 512;
3
+ export const EVENT_MAILBOX_MAX_BYTES = 1024 * 1024;
4
+ export const EVENT_MAILBOX_TEXT_CHUNK = 8192;
5
+ export class EventMailbox {
6
+ notify() { }
7
+ onOverflow() { }
8
+ _events = [];
9
+ _head = 0;
10
+ _bytes = 0;
11
+ _failure = null;
12
+ get size() {
13
+ return this._events.length - this._head;
14
+ }
15
+ get failure() {
16
+ return this._failure;
17
+ }
18
+ get bytes() {
19
+ return this._bytes;
20
+ }
21
+ push(event) {
22
+ if (this._failure) {
23
+ return false;
24
+ }
25
+ if (isLongText(event)) {
26
+ return this.pushText(event);
27
+ }
28
+ return this.pushEvent(event);
29
+ }
30
+ pushText(event) {
31
+ let offset = 0;
32
+ while (offset < event.text.length) {
33
+ let end = Math.min(offset + EVENT_MAILBOX_TEXT_CHUNK, event.text.length);
34
+ if (end < event.text.length && isHighSurrogate(event.text.charCodeAt(end - 1))) {
35
+ end--;
36
+ }
37
+ if (!this.pushEvent({ ...event, text: event.text.slice(offset, end) })) {
38
+ return false;
39
+ }
40
+ offset = end;
41
+ }
42
+ return true;
43
+ }
44
+ pushEvent(event) {
45
+ if (this._failure) {
46
+ return false;
47
+ }
48
+ const tail = this.size ? this._events[this._events.length - 1] : undefined;
49
+ if (tail && canCoalesce(tail, event)) {
50
+ const joined = `${tail.text ?? ''}${event.text ?? ''}`;
51
+ if (joined.length <= EVENT_MAILBOX_TEXT_CHUNK) {
52
+ const nextBytes = this._bytes - eventBytes(tail) + eventBytes({ ...tail, text: joined });
53
+ if (nextBytes <= EVENT_MAILBOX_MAX_BYTES) {
54
+ this._events[this._events.length - 1] = { ...tail, text: joined };
55
+ this._bytes = nextBytes;
56
+ return true;
57
+ }
58
+ }
59
+ }
60
+ const bytes = eventBytes(event);
61
+ if (this.size >= EVENT_MAILBOX_MAX_EVENTS || this._bytes + bytes > EVENT_MAILBOX_MAX_BYTES) {
62
+ this._failure = new Error('Completion output buffer limit exceeded');
63
+ this.onOverflow();
64
+ return false;
65
+ }
66
+ this._events.push(event);
67
+ this._bytes += bytes;
68
+ return true;
69
+ }
70
+ emit(event) {
71
+ this.push(event);
72
+ this.notify();
73
+ }
74
+ shift() {
75
+ if (this._head === this._events.length) {
76
+ return undefined;
77
+ }
78
+ const event = this._events[this._head++];
79
+ this._bytes -= eventBytes(event);
80
+ if (this._head === this._events.length) {
81
+ this._events.length = 0;
82
+ this._head = 0;
83
+ return event;
84
+ }
85
+ if (this._head >= 128 && this._head * 2 >= this._events.length) {
86
+ this._events.splice(0, this._head);
87
+ this._head = 0;
88
+ }
89
+ return event;
90
+ }
91
+ }
92
+ function isLongText(event) {
93
+ return ((event.type === 'content' || event.type === 'thinking') &&
94
+ typeof event.text === 'string' &&
95
+ event.text.length > EVENT_MAILBOX_TEXT_CHUNK);
96
+ }
97
+ function isHighSurrogate(code) {
98
+ return code >= 0xd800 && code <= 0xdbff;
99
+ }
100
+ function canCoalesce(left, right) {
101
+ return ((left.type === 'content' || left.type === 'thinking') &&
102
+ left.type === right.type &&
103
+ left.runId === right.runId &&
104
+ left.round === right.round &&
105
+ typeof left.text === 'string' &&
106
+ typeof right.text === 'string');
107
+ }
108
+ function eventBytes(event) {
109
+ return b4a.byteLength(JSON.stringify(event), 'utf8');
110
+ }
@@ -53,6 +53,7 @@ export interface CompletionArgs {
53
53
  wording?: {
54
54
  toolContinuation?: string;
55
55
  fileDelivered?: string;
56
+ wrapUp?: string;
56
57
  toolDenied?: string;
57
58
  toolCutOff?: string;
58
59
  toolRoundCut?: string;
@@ -1,13 +1,14 @@
1
1
  import type { CompletionFinal, Tool as SdkTool, ToolDialect } from '@qvac/inference';
2
2
  import { type AbortSignal as BareAbortSignal } from 'bare-abort-controller';
3
3
  import type { TextEvent } from '../../helpers/thinking.ts';
4
- import type { CompletionSdk, LlmGenerationParams, Message, ResponseFormat, RoundModelLease, RunLifecycleEvent } from '../../contract/index.ts';
4
+ import type { AgentConfig, CompletionSdk, LlmGenerationParams, Message, ResponseFormat, RoundModelLease, RunLifecycleEvent } from '../../contract/index.ts';
5
5
  export interface ModelRoundRequest {
6
6
  runId: string;
7
7
  round: number;
8
8
  kind: 'streaming' | 'wrap-up';
9
9
  attempt: number;
10
10
  modelId: string;
11
+ load?: Pick<AgentConfig, 'ctxSize' | 'kvCacheK' | 'kvCacheV'> | undefined;
11
12
  history: Message[];
12
13
  tools?: SdkTool[] | undefined;
13
14
  toolSet?: string | undefined;
@@ -18,6 +19,8 @@ export interface ModelRoundRequest {
18
19
  promptPrefix: string;
19
20
  continuationNudge: string;
20
21
  deliveredNudge: string;
22
+ goalNudge?: string | undefined;
23
+ wrapUpNudge?: string | undefined;
21
24
  unforced?: {
22
25
  generationParams?: Partial<LlmGenerationParams> | undefined;
23
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;
@@ -69,6 +72,14 @@ type RoundReset = Extract<RunLifecycleEvent, {
69
72
  type: 'round-reset';
70
73
  }>;
71
74
  export type RoundEvent = TextEvent | InferenceCallEvent | InferenceSentEvent | RoundReset | FoldEvent;
75
+ interface CallCapture {
76
+ args: RoundArgs;
77
+ droppedTurns: number;
78
+ modelId: string;
79
+ params: CompletionParams;
80
+ cacheKey: string | undefined;
81
+ }
72
82
  export declare function runRecoveredRound(sdk: CompletionSdk | undefined, args: RoundArgs): AsyncGenerator<RoundEvent, RecoveredRound>;
73
83
  export declare function recordWholeRound(args: RoundArgs): Promise<CompletionParams>;
84
+ export declare function inferenceCall({ args, droppedTurns, modelId, params, cacheKey }: CallCapture): InferenceCallEvent;
74
85
  export {};
@@ -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
- candidate,
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) {
@@ -724,12 +743,12 @@ function generationParams(args) {
724
743
  const sent = args.generationParams ? host : undefined;
725
744
  return args.tools?.length ? { parallel_tool_calls: true, ...sent } : sent;
726
745
  }
727
- function inferenceCall({ args, candidate, modelId, params, cacheKey }) {
746
+ export function inferenceCall({ args, droppedTurns, modelId, params, cacheKey }) {
728
747
  return {
729
748
  type: 'inference-call',
730
749
  call: {
731
750
  round: args.round,
732
- droppedTurns: candidate.droppedTurns,
751
+ droppedTurns,
733
752
  modelId,
734
753
  messages: params.history,
735
754
  tools: params.tools,
@@ -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];
@@ -0,0 +1 @@
1
+ export declare const TOOL_FAILED_NOTE = "[This call failed: say so, and never state a value it would have produced.]";
@@ -0,0 +1 @@
1
+ export const TOOL_FAILED_NOTE = '[This call failed: say so, and never state a value it would have produced.]';
@@ -1,13 +1,16 @@
1
1
  import type { CompletionHistoryEntry, Message, RunGoal, SdkMessage } from '../contract/index.ts';
2
2
  import { type FailureResultValue } from '../helpers/failure-result.ts';
3
+ import { TOOL_FAILED_NOTE } from './tool-failed-note.ts';
3
4
  export declare const DIRECT_CALL_ID = "call-direct";
4
5
  export declare const PRELOAD_ID_PREFIX = "preload-";
5
6
  export declare const MAX_TOOL_ROUNDS = 10;
6
7
  export declare const GOAL_ROUNDS = 40;
7
8
  export declare const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
8
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.]";
9
11
  export declare function skillMentionNudge(handle: string): string;
10
12
  export declare function isSkillMentionNudge(content: string): boolean;
13
+ export { TOOL_FAILED_NOTE };
11
14
  export declare const TOOL_DENIED_MESSAGE: string;
12
15
  export declare const TOOL_CUT_OFF_MESSAGE: string;
13
16
  export declare const TOOL_ROUND_CUT_MESSAGE: string;
@@ -43,4 +46,3 @@ export declare function attachmentTurn(name: string, result: unknown): string |
43
46
  export declare function loadedSkillsFrom(messages: readonly Message[]): Set<string>;
44
47
  export declare function loadedSkillFilesFrom(messages: readonly Message[]): Map<string, Set<string>>;
45
48
  export declare function historyPayload(output: unknown): unknown;
46
- export {};
@@ -1,16 +1,19 @@
1
1
  import { isRecord } from '../guards.js';
2
2
  import { Agent } from '../agent/index.js';
3
3
  import { headTail } from '../helpers/head-tail.js';
4
+ import { MALFORMED_CALL_ID } from '../helpers/tool-call-markup.js';
4
5
  import { MAX_GOAL_CHECKS } from '../helpers/goal-check.js';
5
6
  import { compactContent } from '../context-window.js';
6
7
  import { TOOL_SEARCH_TOOL_NAME } from './sdk-tool.js';
7
8
  import { isFailureResultReference, readFailureResult } from '../helpers/failure-result.js';
9
+ import { TOOL_FAILED_NOTE } from './tool-failed-note.js';
8
10
  export const DIRECT_CALL_ID = 'call-direct';
9
11
  export const PRELOAD_ID_PREFIX = 'preload-';
10
12
  export const MAX_TOOL_ROUNDS = 10;
11
13
  export const GOAL_ROUNDS = 40;
12
14
  export const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
13
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.]";
14
17
  const MENTION_NUDGE_PREFIX = '[Tool results above. The user picked @';
15
18
  export function skillMentionNudge(handle) {
16
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.]`;
@@ -18,6 +21,7 @@ export function skillMentionNudge(handle) {
18
21
  export function isSkillMentionNudge(content) {
19
22
  return content.startsWith(MENTION_NUDGE_PREFIX);
20
23
  }
24
+ export { TOOL_FAILED_NOTE };
21
25
  export const TOOL_DENIED_MESSAGE = 'The user declined this call. Do not retry it or call it with different arguments to get ' +
22
26
  'around the refusal. Tell the user plainly what you could not do, and never present a ' +
23
27
  'result you did not obtain.';
@@ -105,7 +109,10 @@ export function toolResultTurn(name, id, output) {
105
109
  return `[Tool: ${name} (${id})]\n${JSON.stringify(historyPayload(rest))}\n\n${content}${context}`;
106
110
  }
107
111
  const text = name === Agent.SKILL_TOOL_NAME ? JSON.stringify(payload) : fitted(payload);
108
- return `[Tool: ${name} (${id})]\n${text}${context}`;
112
+ const failed = id !== MALFORMED_CALL_ID && isRecord(shown) && 'error' in shown && shown.guidance !== true
113
+ ? `\n${TOOL_FAILED_NOTE}`
114
+ : '';
115
+ return `[Tool: ${name} (${id})]\n${text}${context}${failed}`;
109
116
  }
110
117
  function fitted(payload) {
111
118
  const whole = JSON.stringify(payload);
@@ -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;