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

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 (99) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist-lib/index.d.ts +2 -12
  3. package/dist-lib/index.js +8 -2
  4. package/dist-lib/lib/agent/resolve.js +9 -2
  5. package/dist-lib/lib/agent/tools.d.ts +1 -0
  6. package/dist-lib/lib/agent/tools.js +1 -1
  7. package/dist-lib/lib/capabilities/agent-ports.d.ts +1 -1
  8. package/dist-lib/lib/capabilities/agent-ports.js +7 -1
  9. package/dist-lib/lib/capabilities/completion-engine/actors/executing.js +4 -1
  10. package/dist-lib/lib/capabilities/completion-engine/actors/execution-plan.js +3 -1
  11. package/dist-lib/lib/capabilities/completion-engine/actors/preparing.js +12 -5
  12. package/dist-lib/lib/capabilities/completion-engine/actors/run-prepare.js +36 -22
  13. package/dist-lib/lib/capabilities/completion-engine/actors/skill-step.js +24 -5
  14. package/dist-lib/lib/capabilities/completion-engine/actors/stream.d.ts +3 -2
  15. package/dist-lib/lib/capabilities/completion-engine/actors/stream.js +18 -3
  16. package/dist-lib/lib/capabilities/completion-engine/actors/streaming.js +3 -0
  17. package/dist-lib/lib/capabilities/completion-engine/actors/wrap-up.js +1 -0
  18. package/dist-lib/lib/capabilities/completion-engine/driver.js +3 -2
  19. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +2 -0
  20. package/dist-lib/lib/capabilities/completion-engine/model-round.d.ts +2 -1
  21. package/dist-lib/lib/capabilities/completion-engine/prepare-step.d.ts +2 -1
  22. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +9 -0
  23. package/dist-lib/lib/capabilities/completion-engine/round.js +12 -8
  24. package/dist-lib/lib/capabilities/completion-engine/tool-execution.js +15 -1
  25. package/dist-lib/lib/capabilities/completion-engine/turns.js +5 -2
  26. package/dist-lib/lib/capabilities/skill-entry.d.ts +4 -0
  27. package/dist-lib/lib/capabilities/skill-entry.js +28 -1
  28. package/dist-lib/lib/capabilities/tool-failed-note.d.ts +1 -0
  29. package/dist-lib/lib/capabilities/tool-failed-note.js +1 -0
  30. package/dist-lib/lib/capabilities/tool-turns.d.ts +5 -1
  31. package/dist-lib/lib/capabilities/tool-turns.js +21 -2
  32. package/dist-lib/lib/context-window.d.ts +1 -0
  33. package/dist-lib/lib/context-window.js +6 -0
  34. package/dist-lib/lib/contract/agent.d.ts +4 -0
  35. package/dist-lib/lib/contract/completion.d.ts +2 -0
  36. package/dist-lib/lib/contract/models.d.ts +3 -1
  37. package/dist-lib/lib/contract/run.d.ts +1 -0
  38. package/dist-lib/lib/machine/completion/actions/completion.d.ts +3 -1
  39. package/dist-lib/lib/machine/completion/actions/completion.js +43 -7
  40. package/dist-lib/lib/machine/completion/actions/tools.js +4 -5
  41. package/dist-lib/lib/machine/completion/context.js +1 -0
  42. package/dist-lib/lib/machine/completion/guards/retry.d.ts +2 -1
  43. package/dist-lib/lib/machine/completion/guards/retry.js +4 -3
  44. package/dist-lib/lib/machine/completion/implementations.d.ts +2 -0
  45. package/dist-lib/lib/machine/completion/implementations.js +7 -3
  46. package/dist-lib/lib/machine/completion/machine.d.ts +6 -0
  47. package/dist-lib/lib/machine/completion/machine.js +12 -1
  48. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  49. package/dist-lib/lib/machine/completion/rules.js +3 -0
  50. package/dist-lib/lib/machine/completion/types.d.ts +5 -0
  51. package/dist-lib/lib/machine/index.d.ts +6 -0
  52. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  53. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  54. package/dist-lib/lib/models/gguf-header.d.ts +6 -0
  55. package/dist-lib/lib/models/gguf-header.js +38 -1
  56. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  57. package/dist-lib/lib/models/kv-cache.js +8 -0
  58. package/dist-lib/lib/models/load-requests.d.ts +9 -0
  59. package/dist-lib/lib/models/load-requests.js +42 -0
  60. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  61. package/dist-lib/lib/models/model-pool.d.ts +2 -1
  62. package/dist-lib/lib/models/model-pool.js +17 -7
  63. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  64. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  65. package/dist-lib/lib/prompt.d.ts +4 -2
  66. package/dist-lib/lib/prompt.js +16 -5
  67. package/dist-lib/lib/residency/completion-runtime.d.ts +6 -5
  68. package/dist-lib/lib/residency/completion-runtime.js +3 -7
  69. package/dist-lib/lib/residency/index.d.ts +9 -1
  70. package/dist-lib/lib/residency/index.js +38 -8
  71. package/dist-lib/lib/skills-host/index.d.ts +1 -0
  72. package/dist-lib/lib/skills-host/index.js +3 -0
  73. package/dist-lib/lib/tools/attachments/staging.d.ts +1 -0
  74. package/dist-lib/lib/tools/attachments/staging.js +11 -0
  75. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  76. package/dist-lib/lib/tools/http-request/request.js +2 -1
  77. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +16 -1
  78. package/dist-lib/lib/tools/http-request/truncate-response.js +45 -9
  79. package/dist-lib/lib/tools/http-request.js +12 -6
  80. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  81. package/dist-lib/lib/tools/office/ops.js +5 -1
  82. package/dist-lib/lib/tools/office.d.ts +1 -0
  83. package/dist-lib/lib/tools/office.js +151 -21
  84. package/dist-lib/lib/tools/operations/compile.js +4 -4
  85. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  86. package/dist-lib/lib/tools/skills/credential-check.js +3 -0
  87. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  88. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  89. package/dist-lib/plugins/image/edit-image.js +4 -3
  90. package/dist-lib/plugins/image/generate-image.d.ts +3 -2
  91. package/dist-lib/plugins/image/generate-image.js +87 -64
  92. package/dist-lib/plugins/image/index.js +1 -0
  93. package/dist-lib/plugins/music/generate-music.d.ts +3 -2
  94. package/dist-lib/plugins/music/generate-music.js +68 -47
  95. package/dist-lib/plugins/music/index.js +1 -0
  96. package/dist-lib/plugins/run-report/story.js +4 -1
  97. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  98. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  99. package/package.json +5 -1
@@ -28,6 +28,7 @@ export interface CompletionArgs {
28
28
  requestMessages?: Message[];
29
29
  tools?: ToolDefinition[];
30
30
  skillCatalog?: readonly CompletionSkillEntry[];
31
+ platform?: string | undefined;
31
32
  approve?: ApproveFn;
32
33
  attach?: AttachFn;
33
34
  fetchAttachment?: FetchAttachmentFn;
@@ -60,6 +61,7 @@ export interface CompletionArgs {
60
61
  toolUnchanged?: string;
61
62
  toolFailing?: string;
62
63
  goalContinuation?: string;
64
+ goalStalled?: string;
63
65
  };
64
66
  }
65
67
  export declare function labelOf(name: string, args: Record<string, unknown>, emoji: string | null): ToolCallDisplay;
@@ -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;
@@ -9,7 +9,7 @@ export interface PrepareSettleInput {
9
9
  context: CompletionContext;
10
10
  step: PrepareStep;
11
11
  result: unknown;
12
- announce(): void;
12
+ announce(result: unknown): void;
13
13
  }
14
14
  export interface PrepareFailInput {
15
15
  deps: CompletionDeps;
@@ -21,6 +21,7 @@ export interface PrepareStepSource {
21
21
  readonly label: string;
22
22
  propose(deps: CompletionDeps, agent: ResolvedAgent<CompletionSkillEntry>): PrepareCall | null;
23
23
  display(deps: CompletionDeps, step: PrepareStep): ToolCallDisplay;
24
+ refusal?(deps: CompletionDeps, step: PrepareStep): string | null;
24
25
  settle(input: PrepareSettleInput): PrepareRunOutput;
25
26
  fail(input: PrepareFailInput): PrepareFailure;
26
27
  }
@@ -24,6 +24,7 @@ export interface RecoveredRound {
24
24
  }
25
25
  export interface RoundArgs {
26
26
  modelId: string;
27
+ canThink?: boolean | undefined;
27
28
  acquireRound?: ((signal?: BareAbortSignal) => Promise<RoundModelLease>) | undefined;
28
29
  history: CompletionHistoryEntry[];
29
30
  failureResults: Readonly<Record<string, FailureResultValue>>;
@@ -68,6 +69,14 @@ type RoundReset = Extract<RunLifecycleEvent, {
68
69
  type: 'round-reset';
69
70
  }>;
70
71
  export type RoundEvent = TextEvent | InferenceCallEvent | InferenceSentEvent | RoundReset | FoldEvent;
72
+ interface CallCapture {
73
+ args: RoundArgs;
74
+ droppedTurns: number;
75
+ modelId: string;
76
+ params: CompletionParams;
77
+ cacheKey: string | undefined;
78
+ }
71
79
  export declare function runRecoveredRound(sdk: CompletionSdk | undefined, args: RoundArgs): AsyncGenerator<RoundEvent, RecoveredRound>;
72
80
  export declare function recordWholeRound(args: RoundArgs): Promise<CompletionParams>;
81
+ export declare function inferenceCall({ args, droppedTurns, modelId, params, cacheKey }: CallCapture): InferenceCallEvent;
73
82
  export {};
@@ -15,7 +15,7 @@ import { isContextOverflowError, isForcedCallFault, isKvCacheSaveFault, isSdkMod
15
15
  import { copy } from '../../helpers/copy.js';
16
16
  import { stableStringify } from '../../helpers/stable-stringify.js';
17
17
  import { detachJson } from '../../helpers/detach-json.js';
18
- import { materializeCompletionHistory } from '../tool-turns.js';
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
21
  import { Fold } from '../../fold/index.js';
@@ -270,7 +270,7 @@ export async function* runRecoveredRound(sdk, args) {
270
270
  const attempts = { sent: 0, uncached: false, overflows: 0, unsettled };
271
271
  const round = yield* runRecoveredRoundWith({
272
272
  sdk: roundSdk,
273
- args,
273
+ args: lease?.canThink === undefined ? args : { ...args, canThink: lease.canThink },
274
274
  modelId: lease?.modelId ?? args.modelId,
275
275
  ctxSize,
276
276
  attempts
@@ -342,7 +342,7 @@ async function* runRecoveredRoundWith(send) {
342
342
  }
343
343
  async function* runLadder({ send, history, origins, fold }) {
344
344
  let lastOverflow = null;
345
- for (const candidate of contextCandidates(history, send.args.continuationNudge, send.args.deliveredNudge)) {
345
+ for (const candidate of contextCandidates(history, ...roundNudges(send.args, history))) {
346
346
  const outcome = yield* runCandidateAttempts({ ...send, candidate, history, origins });
347
347
  if ('round' in outcome) {
348
348
  return { round: recoveredRound({ candidate, attempt: outcome.round, origins }) };
@@ -375,10 +375,14 @@ async function* foldHistory(send, history, tries) {
375
375
  tries.rounds = true;
376
376
  return foldRounds(send, history);
377
377
  }
378
+ function roundNudges(args, history) {
379
+ const mentions = history.flatMap((message) => message.role === 'user' && isSkillMentionNudge(message.content) ? [message.content] : []);
380
+ return [args.continuationNudge, args.deliveredNudge, ...mentions];
381
+ }
378
382
  async function foldRounds(send, history) {
379
383
  const { sdk, args, ctxSize } = send;
380
384
  const spec = args.fold;
381
- const nudges = [args.continuationNudge, args.deliveredNudge];
385
+ const nudges = roundNudges(args, history);
382
386
  if (!spec || !Fold.roundBoundary(history, { nudges, keeps: keepsLoad })?.foldedRounds) {
383
387
  return null;
384
388
  }
@@ -657,7 +661,7 @@ async function* runCandidate({ sdk, args, modelId, candidate, progress, baseHist
657
661
  if (args.capture) {
658
662
  yield inferenceCall({
659
663
  args,
660
- candidate,
664
+ droppedTurns: candidate.droppedTurns,
661
665
  modelId,
662
666
  params,
663
667
  cacheKey: cacheable ? args.cacheKey : undefined
@@ -720,12 +724,12 @@ function generationParams(args) {
720
724
  const sent = args.generationParams ? host : undefined;
721
725
  return args.tools?.length ? { parallel_tool_calls: true, ...sent } : sent;
722
726
  }
723
- function inferenceCall({ args, candidate, modelId, params, cacheKey }) {
727
+ export function inferenceCall({ args, droppedTurns, modelId, params, cacheKey }) {
724
728
  return {
725
729
  type: 'inference-call',
726
730
  call: {
727
731
  round: args.round,
728
- droppedTurns: candidate.droppedTurns,
732
+ droppedTurns,
729
733
  modelId,
730
734
  messages: params.history,
731
735
  tools: params.tools,
@@ -749,7 +753,7 @@ function inferenceSent({ args, candidate, final }) {
749
753
  }
750
754
  async function* streamCandidateTokens({ result, state, args, progress }) {
751
755
  let contentText = '';
752
- const startInThink = (args.generationParams?.reasoning_budget ?? 0) !== 0;
756
+ const startInThink = (args.generationParams?.reasoning_budget ?? 0) !== 0 && args.canThink !== false;
753
757
  for await (const event of runRoundTokens({
754
758
  result,
755
759
  state,
@@ -282,8 +282,22 @@ export async function resolveToolCalls(toolCalls, enabled, { runId, agentId, pip
282
282
  }
283
283
  const tool = enabled.find((t) => t.name === call.name);
284
284
  const rawCall = call.raw === undefined ? {} : { rawCall: clipRawCall(call.raw) };
285
+ const object = isRecord(call.arguments) && !Array.isArray(call.arguments);
285
286
  if (!tool) {
286
- resolved.push({ call, args: detachJson(takeToolIntent(call.arguments).args), ...rawCall });
287
+ const args = object ? takeToolIntent(call.arguments).args : {};
288
+ resolved.push({ call, args: detachJson(args), ...rawCall });
289
+ continue;
290
+ }
291
+ if (!object) {
292
+ const error = `${tool.name} takes an object of arguments.`;
293
+ const rejection = {
294
+ kind: 'hook-rejection',
295
+ hook: 'arguments',
296
+ phase: 'preToolCall',
297
+ error,
298
+ guidance: true
299
+ };
300
+ resolved.push({ call, tool, args: {}, rejection, ...rawCall });
287
301
  continue;
288
302
  }
289
303
  const taken = INTENT_PARAM in tool.parameters.properties
@@ -2,7 +2,7 @@ import { stripControlTokens } from '../../helpers/control-tokens.js';
2
2
  import { isRecord } from '../../guards.js';
3
3
  import { stripToolCallMarkup, toolCallMarkup } from '../../helpers/tool-call-markup.js';
4
4
  import { Agent } from '../../agent/index.js';
5
- import { DIRECT_CALL_ID, PRELOAD_ID_PREFIX, skillLoadedTurn, toolResultHistoryEntry, toolResultTurn } from '../tool-turns.js';
5
+ import { DIRECT_CALL_ID, PRELOAD_ID_PREFIX, skillLoadedTurn, skillMentionNudge, toolResultHistoryEntry, toolResultTurn } from '../tool-turns.js';
6
6
  import { annotateUserTimes, currentTimeAnnotation } from '../../prompt.js';
7
7
  import { isFailureResultReference } from '../../helpers/failure-result.js';
8
8
  export function trustedSourcesFrom(history) {
@@ -64,7 +64,10 @@ function preloadTurns({ messages, at, nudge, consumed }) {
64
64
  return [
65
65
  { role: 'assistant', content: assistantToolTurn('', [call]) },
66
66
  sanitizeTurn({ role: 'tool', content: toolResultTurn(call.name, call.id, output) }),
67
- { role: 'user', content: nudge }
67
+ {
68
+ role: 'user',
69
+ content: typeof output.mention === 'string' ? skillMentionNudge(output.mention) : nudge
70
+ }
68
71
  ];
69
72
  });
70
73
  }
@@ -1,3 +1,4 @@
1
+ import type { PromptSkill } from '../prompt.ts';
1
2
  import type { SkillCatalogEntry } from '../tools/skills/catalog.ts';
2
3
  import { type SkillState } from '../tools/skills/skill-state-constants.ts';
3
4
  export type CompletionSkillEntry = SkillCatalogEntry & {
@@ -6,3 +7,6 @@ export type CompletionSkillEntry = SkillCatalogEntry & {
6
7
  export declare function skillInContext(entry: CompletionSkillEntry): boolean;
7
8
  export declare function unreadySkillState(name: string, catalog: readonly CompletionSkillEntry[]): SkillState | null;
8
9
  export declare function unreadySkillMessage(name: string, state: string): string;
10
+ export declare function fixableInSkills(entry: CompletionSkillEntry): boolean;
11
+ export declare function promptSkill(entry: CompletionSkillEntry): PromptSkill;
12
+ export declare function mentionHandle(entry: CompletionSkillEntry): string;
@@ -1,3 +1,4 @@
1
+ import { skillMentionHandle } from '../tools/skills/mention.js';
1
2
  import { SKILL_STATE, isAvailableState } from '../tools/skills/skill-state-constants.js';
2
3
  export function skillInContext(entry) {
3
4
  return entry.status === undefined || isAvailableState(entry.status);
@@ -10,5 +11,31 @@ export function unreadySkillMessage(name, state) {
10
11
  if (state === SKILL_STATE.incompatibleModel) {
11
12
  return `skill "${name}" needs a larger model than the one loaded. Tell the user to pick a larger model to use it; do not retry.`;
12
13
  }
13
- return `skill "${name}" is ${state} and cannot be used yet. Tell the user to open it in Skills and finish its setup; do not retry.`;
14
+ return (`skill "${name}" is ${state} and cannot be used yet. Tell the user to ${unreadyRemedy(state)}, ` +
15
+ `and do not do this task with another tool.`);
16
+ }
17
+ const FIXABLE_STATES = new Set([
18
+ SKILL_STATE.disconnected,
19
+ SKILL_STATE.needsSetup
20
+ ]);
21
+ export function fixableInSkills(entry) {
22
+ return entry.status !== undefined && FIXABLE_STATES.has(entry.status);
23
+ }
24
+ function unreadyRemedy(state) {
25
+ if (state === SKILL_STATE.disconnected)
26
+ return 'reconnect it in Skills';
27
+ if (state === SKILL_STATE.needsSetup)
28
+ return 'set it up in Skills';
29
+ return 'open it in Skills to see what it needs';
30
+ }
31
+ export function promptSkill(entry) {
32
+ const state = skillInContext(entry) ? undefined : entry.status;
33
+ return {
34
+ name: entry.name,
35
+ description: entry.description,
36
+ note: state ? `${state} — tell the user to ${unreadyRemedy(state)}` : undefined
37
+ };
38
+ }
39
+ export function mentionHandle(entry) {
40
+ return skillMentionHandle(entry);
14
41
  }
@@ -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,11 +1,15 @@
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 function skillMentionNudge(handle: string): string;
11
+ export declare function isSkillMentionNudge(content: string): boolean;
12
+ export { TOOL_FAILED_NOTE };
9
13
  export declare const TOOL_DENIED_MESSAGE: string;
10
14
  export declare const TOOL_CUT_OFF_MESSAGE: string;
11
15
  export declare const TOOL_ROUND_CUT_MESSAGE: string;
@@ -15,6 +19,7 @@ export declare const TOOL_FAILING_MESSAGE: string;
15
19
  export declare const FAILURE_STREAK = 3;
16
20
  export declare const TOOL_UNCHANGED_MESSAGE: string;
17
21
  export declare const GOAL_CONTINUATION_NUDGE: string;
22
+ export declare const GOAL_STALLED_NUDGE: string;
18
23
  export declare function checkMaxToolRounds(rounds: number): number;
19
24
  export declare function checkGoal(goal: RunGoal, responseFormat?: unknown): RunGoal;
20
25
  export declare const TOOL_RESULT_MAX_CHARS = 65536;
@@ -40,4 +45,3 @@ export declare function attachmentTurn(name: string, result: unknown): string |
40
45
  export declare function loadedSkillsFrom(messages: readonly Message[]): Set<string>;
41
46
  export declare function loadedSkillFilesFrom(messages: readonly Message[]): Map<string, Set<string>>;
42
47
  export declare function historyPayload(output: unknown): unknown;
43
- export {};
@@ -1,16 +1,26 @@
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
+ const MENTION_NUDGE_PREFIX = '[Tool results above. The user picked @';
17
+ export function skillMentionNudge(handle) {
18
+ 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.]`;
19
+ }
20
+ export function isSkillMentionNudge(content) {
21
+ return content.startsWith(MENTION_NUDGE_PREFIX);
22
+ }
23
+ export { TOOL_FAILED_NOTE };
14
24
  export const TOOL_DENIED_MESSAGE = 'The user declined this call. Do not retry it or call it with different arguments to get ' +
15
25
  'around the refusal. Tell the user plainly what you could not do, and never present a ' +
16
26
  'result you did not obtain.';
@@ -34,6 +44,8 @@ export const GOAL_CONTINUATION_NUDGE = '[The goal is not met yet. Keep working o
34
44
  'update_plan. With no plan yet, write one first: one step per requirement the goal states, ' +
35
45
  'the last step a check of the whole result with a tool. Mark a step done only once a tool ' +
36
46
  'result shows it is done; the goal is met when every step is done.]';
47
+ export const GOAL_STALLED_NUDGE = '[Stalled: {call} kept returning the same result, and another identical run will not change ' +
48
+ 'it. Step back: re-read the goal and the results you have, then try a different approach.]';
37
49
  export function checkMaxToolRounds(rounds) {
38
50
  if (!Number.isSafeInteger(rounds) || rounds < 1) {
39
51
  throw new Error(`maxToolRounds must be an integer of 1 or more, got ${rounds}`);
@@ -91,8 +103,15 @@ export function toolResultTurn(name, id, output) {
91
103
  if (name === TOOL_SEARCH_TOOL_NAME) {
92
104
  return JSON.stringify(payload);
93
105
  }
106
+ if (name === Agent.SKILL_TOOL_NAME && isRecord(shown) && typeof shown.content === 'string') {
107
+ const { content, ...rest } = shown;
108
+ return `[Tool: ${name} (${id})]\n${JSON.stringify(historyPayload(rest))}\n\n${content}${context}`;
109
+ }
94
110
  const text = name === Agent.SKILL_TOOL_NAME ? JSON.stringify(payload) : fitted(payload);
95
- return `[Tool: ${name} (${id})]\n${text}${context}`;
111
+ const failed = id !== MALFORMED_CALL_ID && isRecord(shown) && 'error' in shown && shown.guidance !== true
112
+ ? `\n${TOOL_FAILED_NOTE}`
113
+ : '';
114
+ return `[Tool: ${name} (${id})]\n${text}${context}${failed}`;
96
115
  }
97
116
  function fitted(payload) {
98
117
  const whole = JSON.stringify(payload);
@@ -248,7 +267,7 @@ function skillLoadPayload(turn) {
248
267
  return null;
249
268
  }
250
269
  }
251
- const HOST_ONLY_KEYS = ['data', 'hostNotice'];
270
+ const HOST_ONLY_KEYS = ['data', 'hostNotice', 'mention'];
252
271
  export function historyPayload(output) {
253
272
  if (!output || typeof output !== 'object')
254
273
  return output;
@@ -1,5 +1,6 @@
1
1
  import type { Message } from './contract/index.ts';
2
2
  export declare const TOOL_RESULT_TRUNCATION_MARKER = "\n[tool result truncated for context]\n";
3
+ export declare function responseRoomChars(ctxSize: number | undefined, cacheTokens: number | undefined): number | undefined;
3
4
  export declare const TOOL_SEARCH_RESULT = "{\"tool_search\":";
4
5
  export declare function compactedFrom(message: Message): Message | undefined;
5
6
  export interface ContextCandidate {
@@ -1,5 +1,11 @@
1
1
  import { Fold } from './fold/index.js';
2
2
  export const TOOL_RESULT_TRUNCATION_MARKER = '\n[tool result truncated for context]\n';
3
+ export function responseRoomChars(ctxSize, cacheTokens) {
4
+ if (!ctxSize || !cacheTokens) {
5
+ return undefined;
6
+ }
7
+ return Math.floor(Math.max(0, ctxSize - cacheTokens) / 2);
8
+ }
3
9
  export const TOOL_SEARCH_RESULT = '{"tool_search":';
4
10
  const compactedSources = new WeakMap();
5
11
  export function compactedFrom(message) {
@@ -31,6 +31,7 @@ export interface AgentPorts<Skill extends AgentSkill = AgentSkill> {
31
31
  bio: string | null | undefined;
32
32
  toolNames: readonly string[];
33
33
  skills: readonly Skill[];
34
+ platform?: string | undefined;
34
35
  }): SystemPromptParts;
35
36
  mention(text: string, skills: readonly Skill[]): Skill | null;
36
37
  implicitSkill(text: string, skills: readonly Skill[]): Skill | null;
@@ -46,6 +47,8 @@ export interface AgentRequest<Skill extends AgentSkill = AgentSkill> {
46
47
  readonly userText: string;
47
48
  readonly tools: readonly ToolDefinition[];
48
49
  readonly skills: readonly Skill[];
50
+ readonly unreadySkills?: readonly Skill[] | undefined;
51
+ readonly platform?: string | undefined;
49
52
  readonly loadedSkills: ReadonlySet<string>;
50
53
  readonly fsRoots: readonly DriveRoot[];
51
54
  readonly fsWriteRoots: readonly DriveRoot[];
@@ -58,6 +61,7 @@ export interface ResolvedAgent<Skill extends AgentSkill = AgentSkill> {
58
61
  readonly system: SystemPromptParts;
59
62
  readonly activation: SkillActivation;
60
63
  readonly activeSkills: Skill[];
64
+ readonly listedSkills: Skill[];
61
65
  readonly mention: Skill | null;
62
66
  readonly preload: Skill | null;
63
67
  readonly grantedOps: Map<string, CliValidator[]>;
@@ -221,6 +221,7 @@ export interface ToolDefinition {
221
221
  endsRun?: true;
222
222
  concurrent?: true;
223
223
  stableRead?: boolean;
224
+ deliversMany?: true;
224
225
  callsTools?: true;
225
226
  defer?: true;
226
227
  group?: string;
@@ -408,6 +409,7 @@ export interface RoundModelLease {
408
409
  modelId: string;
409
410
  ctxSize?: number | undefined;
410
411
  slots?: number | undefined;
412
+ canThink?: boolean | undefined;
411
413
  sdk?: CompletionSdk;
412
414
  release: () => void;
413
415
  }
@@ -2,13 +2,15 @@ import type { createVectorIndex, loadVectorIndex } from '@qvac/inference';
2
2
  import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
3
3
  import type { ModelSrc } from '../models/context.ts';
4
4
  import type { HoldFn } from '../models/download-gate.ts';
5
+ import type { LoadRequests } from '../models/load-requests.ts';
5
6
  import type { CancelSdk, ModelState, PendingLoad, TrackedLoad } from '../models/model-pool.ts';
6
- export type { CancelSdk, HoldFn, ModelState, TrackedLoad };
7
+ export type { CancelSdk, HoldFn, LoadRequests, ModelState, TrackedLoad };
7
8
  export interface ModelHost {
8
9
  sdk(): Promise<unknown>;
9
10
  track(load: TrackedLoad, sdk?: Partial<CancelSdk>): TrackedLoad;
10
11
  makeRoom(signal: BareAbortSignal | undefined, busy: string | Error, srcs?: ReadonlyArray<string>): Promise<void>;
11
12
  hold: HoldFn;
13
+ readonly requests: LoadRequests;
12
14
  completionModel(model: string, signal?: BareAbortSignal): Promise<BorrowedModel>;
13
15
  emit(state: ModelState): void;
14
16
  progressState(model: string, progress: Record<string, unknown>): ModelState;
@@ -1,6 +1,7 @@
1
1
  export interface RunBudget {
2
2
  readonly deadlineMs: number;
3
3
  outputBytesUsed: number;
4
+ responseRoomChars?: number | undefined;
4
5
  }
5
6
  export interface HistoryToolCall {
6
7
  id: string;
@@ -11,7 +11,9 @@ export declare function retryCutRound({ context }: CompletionActionArgs): Partia
11
11
  export declare function wrapCutCompletion({ context }: CompletionActionArgs): Partial<CompletionContext>;
12
12
  export declare function continueWithInput({ context }: CompletionActionArgs): Partial<CompletionContext>;
13
13
  export declare function addKnowledge({ context, params }: CompletionActionArgs<RetrievingOutput>): Partial<CompletionContext>;
14
- export declare function goalTurn({ policy, goal, plan }: Readonly<CompletionContext>): string;
14
+ export declare function goalTurn({ policy, goal, plan }: Readonly<CompletionContext>, stall?: string): string;
15
+ export declare function continueStalledGoal({ context }: CompletionActionArgs): Partial<CompletionContext>;
16
+ export declare function markGoalStalled({ context }: CompletionActionArgs): Partial<CompletionContext>;
15
17
  export declare function continueGoal({ context }: CompletionActionArgs): Partial<CompletionContext>;
16
18
  export declare function continueStop({ context, params }: CompletionActionArgs<AnsweredPayload>): Partial<CompletionContext>;
17
19
  export declare function settleGoal({ context }: CompletionActionArgs): Partial<CompletionContext>;
@@ -1,6 +1,6 @@
1
- import { hasRoundsLeft } from '../guards/retry.js';
1
+ import { hasRoundsLeft, stuckResult } from '../guards/retry.js';
2
2
  import { mergeChecks, namedChecks } from '../../../helpers/goal-check.js';
3
- import { activate, applyHistorySplice, applySplice, foldMetrics, goalMet, goalStalled, goalTokensLeft, nudgeWithChecks, nudgeWithPlan, retainFailureResults } from '../rules.js';
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);
6
6
  }
@@ -106,8 +106,9 @@ function endToolRound(context) {
106
106
  return {
107
107
  history: [...context.history, ...continuation(context)],
108
108
  steering: [],
109
- delivered: context.delivered || context.deliveredThisRound,
110
- deliveredThisRound: false
109
+ delivered: context.delivered || context.deliveryEndsRun,
110
+ deliveredThisRound: false,
111
+ deliveryEndsRun: false
111
112
  };
112
113
  }
113
114
  function continuation(context) {
@@ -150,8 +151,40 @@ export function addKnowledge({ context, params }) {
150
151
  sources: params.sources ? [...context.sources, ...params.sources] : context.sources
151
152
  };
152
153
  }
153
- export function goalTurn({ policy, goal, plan }) {
154
- return nudgeWithChecks(nudgeWithPlan(`${policy.goalNudge}\nGoal: ${goal?.objective ?? ''}`, plan), goal?.checks ?? [], goal?.checkable && !goal.named);
154
+ export function goalTurn({ policy, goal, plan }, stall) {
155
+ const nudge = stall ? `${policy.goalNudge}\n${stall}` : policy.goalNudge;
156
+ return nudgeWithChecks(nudgeWithPlan(`${nudge}\nGoal: ${goal?.objective ?? ''}`, plan), goal?.checks ?? [], goal?.checkable && !goal.named);
157
+ }
158
+ export function continueStalledGoal({ context }) {
159
+ const { goal, policy } = context;
160
+ const name = stuckResult(context)?.name;
161
+ const stall = policy.goalStalledNudge.replaceAll('{call}', name ? `\`${name}\`` : 'your recent calls');
162
+ return {
163
+ ...applyPreparation(context),
164
+ ...closeFailureMemo(context),
165
+ history: [
166
+ ...context.history,
167
+ ...userTurns(context.steering),
168
+ { role: 'user', content: goalTurn(context, stall) }
169
+ ],
170
+ steering: [],
171
+ delivered: context.delivered || context.deliveredThisRound,
172
+ deliveredThisRound: false,
173
+ blockedRepeats: 0,
174
+ roundProgressed: false,
175
+ settledResults: settledSince(context.settledResults),
176
+ round: context.round + 1,
177
+ mute: 0,
178
+ cuts: 0,
179
+ narrated: false,
180
+ malformed: false,
181
+ cappedRounds: 0,
182
+ goal: goal && { ...goal, turns: goal.turns + 1 }
183
+ };
184
+ }
185
+ export function markGoalStalled({ context }) {
186
+ const { goal } = context;
187
+ return goal ? { goal: { ...goal, stalled: true } } : {};
155
188
  }
156
189
  export function continueGoal({ context }) {
157
190
  const { goal } = context;
@@ -171,6 +204,9 @@ function goalStatus(context) {
171
204
  if (goalMet(context)) {
172
205
  return 'met';
173
206
  }
207
+ if (context.goal?.stalled) {
208
+ return 'stalled';
209
+ }
174
210
  if (!hasRoundsLeft(context)) {
175
211
  return 'rounds';
176
212
  }
@@ -180,7 +216,7 @@ function goalStatus(context) {
180
216
  if (!goalTokensLeft(context)) {
181
217
  return 'tokens';
182
218
  }
183
- return goalStalled(context) ? 'stalled' : 'open';
219
+ return 'open';
184
220
  }
185
221
  export function finishRound({ context, params }) {
186
222
  const metrics = { ...context.metrics };
@@ -1,4 +1,4 @@
1
- import { activate, applyHistorySplice, applySplice, cutOffMessage, recordTool, retainFailureResults } from '../rules.js';
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
4
  export function resolveTools({ context, params }) {
@@ -146,7 +146,8 @@ export function finishDirectTool({ context, params }) {
146
146
  function roundResult(context, payload) {
147
147
  return {
148
148
  answer: context.answer ?? payload.answer ?? null,
149
- deliveredThisRound: context.deliveredThisRound || payload.delivered === true
149
+ deliveredThisRound: context.deliveredThisRound || payload.delivered === true,
150
+ deliveryEndsRun: context.deliveryEndsRun || payload.deliveryEndsRun === true
150
151
  };
151
152
  }
152
153
  function unchangedRound(context, payload) {
@@ -155,9 +156,6 @@ function unchangedRound(context, payload) {
155
156
  !folded &&
156
157
  !Object.entries(context.settledResults).some(([key, { repeats, round }]) => key !== payload.settled?.key && round === context.round && repeats > 0));
157
158
  }
158
- function settledSince(settled) {
159
- return Object.fromEntries(Object.entries(settled).map(([key, result]) => [key, { ...result, repeats: 0 }]));
160
- }
161
159
  function failureStreaks(context, payload) {
162
160
  const streaks = context.failureStreaks;
163
161
  if (payload.failed) {
@@ -200,6 +198,7 @@ function applyToolResult(context, payload, call) {
200
198
  ? {
201
199
  ...(payload.progressed ? settledSince(context.settledResults) : context.settledResults),
202
200
  [payload.settled.key]: {
201
+ name: call?.name,
203
202
  digest: payload.settled.digest,
204
203
  repeats: payload.unchanged
205
204
  ? (context.settledResults[payload.settled.key]?.repeats ?? 0) + 1
@@ -30,6 +30,7 @@ export function emptyCompletionContext(opts) {
30
30
  answer: null,
31
31
  delivered: false,
32
32
  deliveredThisRound: false,
33
+ deliveryEndsRun: false,
33
34
  activated: [],
34
35
  outcome: null,
35
36
  metrics: {
@@ -1,8 +1,9 @@
1
- import type { CompletionContext } from '../types.ts';
1
+ import type { CompletionContext, SettledResult } from '../types.ts';
2
2
  export declare function canMuteRetry(ctx: CompletionContext): boolean;
3
3
  export declare function canRetryCut(ctx: CompletionContext): boolean;
4
4
  export declare function canRetrySearchCap(ctx: CompletionContext): boolean;
5
5
  export declare function repeatsBlocked(ctx: CompletionContext): boolean;
6
+ export declare function stuckResult(ctx: CompletionContext): SettledResult | undefined;
6
7
  export declare function hasRoundsLeft(ctx: CompletionContext): boolean;
7
8
  export declare function canRetryNarrated(ctx: CompletionContext): boolean;
8
9
  export declare function canRetryMalformed(ctx: CompletionContext): boolean;
@@ -9,10 +9,11 @@ export function canRetrySearchCap(ctx) {
9
9
  return ctx.cappedRounds < MAX_CAPPED_ROUNDS;
10
10
  }
11
11
  export function repeatsBlocked(ctx) {
12
- return (!ctx.roundProgressed && ctx.blockedRepeats >= MAX_BLOCKED_REPEATS) || resultStuck(ctx);
12
+ return ((!ctx.roundProgressed && ctx.blockedRepeats >= MAX_BLOCKED_REPEATS) ||
13
+ stuckResult(ctx) !== undefined);
13
14
  }
14
- function resultStuck(ctx) {
15
- return Object.values(ctx.settledResults).some(({ repeats, round }) => round === ctx.round && repeats >= MAX_UNCHANGED_RESULTS);
15
+ export function stuckResult(ctx) {
16
+ return Object.values(ctx.settledResults).find(({ repeats, round }) => round === ctx.round && repeats >= MAX_UNCHANGED_RESULTS);
16
17
  }
17
18
  export function hasRoundsLeft(ctx) {
18
19
  return ctx.round + 1 < ctx.policy.maxToolRounds;
@@ -65,6 +65,8 @@ export declare const completionActions: {
65
65
  addKnowledge: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, import("./types.ts").RetrievingOutput, never, never, never, never, never>;
66
66
  continueStop: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, import("./types.ts").AnsweredPayload, never, never, never, never, never>;
67
67
  continueGoal: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, EngineEvent>;
68
+ continueStalledGoal: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, EngineEvent>;
69
+ markGoalStalled: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, never>;
68
70
  settleGoal: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, undefined, never, never, never, never, EngineEvent>;
69
71
  retryMalformedRound: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, import("./types.ts").AnsweredPayload, never, never, never, never, never>;
70
72
  retryMuteRound: import("xstate").ActionFunction<CompletionContext, CompletionMachineEvent, CompletionMachineEvent, import("./types.ts").AnsweredPayload, never, never, never, never, never>;