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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist-lib/index.d.ts +2 -12
  3. package/dist-lib/index.js +7 -1
  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/streaming.js +2 -0
  15. package/dist-lib/lib/capabilities/completion-engine/driver.js +3 -2
  16. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +2 -0
  17. package/dist-lib/lib/capabilities/completion-engine/prepare-step.d.ts +2 -1
  18. package/dist-lib/lib/capabilities/completion-engine/round.d.ts +1 -0
  19. package/dist-lib/lib/capabilities/completion-engine/round.js +9 -5
  20. package/dist-lib/lib/capabilities/completion-engine/tool-execution.js +15 -1
  21. package/dist-lib/lib/capabilities/completion-engine/turns.js +5 -2
  22. package/dist-lib/lib/capabilities/skill-entry.d.ts +4 -0
  23. package/dist-lib/lib/capabilities/skill-entry.js +28 -1
  24. package/dist-lib/lib/capabilities/tool-turns.d.ts +3 -0
  25. package/dist-lib/lib/capabilities/tool-turns.js +14 -1
  26. package/dist-lib/lib/context-window.d.ts +1 -0
  27. package/dist-lib/lib/context-window.js +6 -0
  28. package/dist-lib/lib/contract/agent.d.ts +4 -0
  29. package/dist-lib/lib/contract/completion.d.ts +2 -0
  30. package/dist-lib/lib/contract/models.d.ts +3 -1
  31. package/dist-lib/lib/contract/run.d.ts +1 -0
  32. package/dist-lib/lib/machine/completion/actions/completion.d.ts +3 -1
  33. package/dist-lib/lib/machine/completion/actions/completion.js +43 -7
  34. package/dist-lib/lib/machine/completion/actions/tools.js +4 -5
  35. package/dist-lib/lib/machine/completion/context.js +1 -0
  36. package/dist-lib/lib/machine/completion/guards/retry.d.ts +2 -1
  37. package/dist-lib/lib/machine/completion/guards/retry.js +4 -3
  38. package/dist-lib/lib/machine/completion/implementations.d.ts +2 -0
  39. package/dist-lib/lib/machine/completion/implementations.js +7 -3
  40. package/dist-lib/lib/machine/completion/machine.d.ts +6 -0
  41. package/dist-lib/lib/machine/completion/machine.js +12 -1
  42. package/dist-lib/lib/machine/completion/rules.d.ts +1 -0
  43. package/dist-lib/lib/machine/completion/rules.js +3 -0
  44. package/dist-lib/lib/machine/completion/types.d.ts +5 -0
  45. package/dist-lib/lib/machine/index.d.ts +6 -0
  46. package/dist-lib/lib/models/custom-model-cache.d.ts +1 -0
  47. package/dist-lib/lib/models/custom-model-cache.js +3 -0
  48. package/dist-lib/lib/models/gguf-header.d.ts +6 -0
  49. package/dist-lib/lib/models/gguf-header.js +38 -1
  50. package/dist-lib/lib/models/kv-cache.d.ts +2 -0
  51. package/dist-lib/lib/models/kv-cache.js +8 -0
  52. package/dist-lib/lib/models/load-requests.d.ts +9 -0
  53. package/dist-lib/lib/models/load-requests.js +42 -0
  54. package/dist-lib/lib/models/model-handle.d.ts +1 -0
  55. package/dist-lib/lib/models/model-pool.d.ts +2 -1
  56. package/dist-lib/lib/models/model-pool.js +17 -7
  57. package/dist-lib/lib/no-redirect-fetch-impl.d.ts +1 -0
  58. package/dist-lib/lib/no-redirect-fetch-impl.js +32 -1
  59. package/dist-lib/lib/prompt.d.ts +4 -2
  60. package/dist-lib/lib/prompt.js +16 -5
  61. package/dist-lib/lib/residency/completion-runtime.d.ts +6 -5
  62. package/dist-lib/lib/residency/completion-runtime.js +3 -7
  63. package/dist-lib/lib/residency/index.d.ts +8 -0
  64. package/dist-lib/lib/residency/index.js +36 -6
  65. package/dist-lib/lib/skills-host/index.d.ts +1 -0
  66. package/dist-lib/lib/skills-host/index.js +3 -0
  67. package/dist-lib/lib/tools/attachments/staging.d.ts +1 -0
  68. package/dist-lib/lib/tools/attachments/staging.js +11 -0
  69. package/dist-lib/lib/tools/http-request/request.d.ts +3 -1
  70. package/dist-lib/lib/tools/http-request/request.js +2 -1
  71. package/dist-lib/lib/tools/http-request/truncate-response.d.ts +16 -1
  72. package/dist-lib/lib/tools/http-request/truncate-response.js +45 -9
  73. package/dist-lib/lib/tools/http-request.js +12 -6
  74. package/dist-lib/lib/tools/office/ops.d.ts +1 -0
  75. package/dist-lib/lib/tools/office/ops.js +5 -1
  76. package/dist-lib/lib/tools/office.d.ts +1 -0
  77. package/dist-lib/lib/tools/office.js +151 -21
  78. package/dist-lib/lib/tools/operations/compile.js +4 -4
  79. package/dist-lib/lib/tools/skills/credential-check.d.ts +1 -0
  80. package/dist-lib/lib/tools/skills/credential-check.js +3 -0
  81. package/dist-lib/lib/tools/skills/manifest-parse.js +27 -3
  82. package/dist-lib/lib/tools/skills/manifest.d.ts +1 -0
  83. package/dist-lib/plugins/image/edit-image.js +4 -3
  84. package/dist-lib/plugins/image/generate-image.d.ts +3 -2
  85. package/dist-lib/plugins/image/generate-image.js +87 -64
  86. package/dist-lib/plugins/image/index.js +1 -0
  87. package/dist-lib/plugins/music/generate-music.d.ts +3 -2
  88. package/dist-lib/plugins/music/generate-music.js +68 -47
  89. package/dist-lib/plugins/music/index.js +1 -0
  90. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  91. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  92. package/package.json +1 -1
@@ -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
  }
@@ -6,6 +6,8 @@ export declare const MAX_TOOL_ROUNDS = 10;
6
6
  export declare const GOAL_ROUNDS = 40;
7
7
  export declare const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
8
8
  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.]";
9
+ export declare function skillMentionNudge(handle: string): string;
10
+ export declare function isSkillMentionNudge(content: string): boolean;
9
11
  export declare const TOOL_DENIED_MESSAGE: string;
10
12
  export declare const TOOL_CUT_OFF_MESSAGE: string;
11
13
  export declare const TOOL_ROUND_CUT_MESSAGE: string;
@@ -15,6 +17,7 @@ export declare const TOOL_FAILING_MESSAGE: string;
15
17
  export declare const FAILURE_STREAK = 3;
16
18
  export declare const TOOL_UNCHANGED_MESSAGE: string;
17
19
  export declare const GOAL_CONTINUATION_NUDGE: string;
20
+ export declare const GOAL_STALLED_NUDGE: string;
18
21
  export declare function checkMaxToolRounds(rounds: number): number;
19
22
  export declare function checkGoal(goal: RunGoal, responseFormat?: unknown): RunGoal;
20
23
  export declare const TOOL_RESULT_MAX_CHARS = 65536;
@@ -11,6 +11,13 @@ export const MAX_TOOL_ROUNDS = 10;
11
11
  export const GOAL_ROUNDS = 40;
12
12
  export const TOOL_CONTINUATION_NUDGE = "[Tool results above. Continue the user's request: call the next tool, or answer.]";
13
13
  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.]';
14
+ const MENTION_NUDGE_PREFIX = '[Tool results above. The user picked @';
15
+ export function skillMentionNudge(handle) {
16
+ 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.]`;
17
+ }
18
+ export function isSkillMentionNudge(content) {
19
+ return content.startsWith(MENTION_NUDGE_PREFIX);
20
+ }
14
21
  export const TOOL_DENIED_MESSAGE = 'The user declined this call. Do not retry it or call it with different arguments to get ' +
15
22
  'around the refusal. Tell the user plainly what you could not do, and never present a ' +
16
23
  'result you did not obtain.';
@@ -34,6 +41,8 @@ export const GOAL_CONTINUATION_NUDGE = '[The goal is not met yet. Keep working o
34
41
  'update_plan. With no plan yet, write one first: one step per requirement the goal states, ' +
35
42
  'the last step a check of the whole result with a tool. Mark a step done only once a tool ' +
36
43
  'result shows it is done; the goal is met when every step is done.]';
44
+ export const GOAL_STALLED_NUDGE = '[Stalled: {call} kept returning the same result, and another identical run will not change ' +
45
+ 'it. Step back: re-read the goal and the results you have, then try a different approach.]';
37
46
  export function checkMaxToolRounds(rounds) {
38
47
  if (!Number.isSafeInteger(rounds) || rounds < 1) {
39
48
  throw new Error(`maxToolRounds must be an integer of 1 or more, got ${rounds}`);
@@ -91,6 +100,10 @@ export function toolResultTurn(name, id, output) {
91
100
  if (name === TOOL_SEARCH_TOOL_NAME) {
92
101
  return JSON.stringify(payload);
93
102
  }
103
+ if (name === Agent.SKILL_TOOL_NAME && isRecord(shown) && typeof shown.content === 'string') {
104
+ const { content, ...rest } = shown;
105
+ return `[Tool: ${name} (${id})]\n${JSON.stringify(historyPayload(rest))}\n\n${content}${context}`;
106
+ }
94
107
  const text = name === Agent.SKILL_TOOL_NAME ? JSON.stringify(payload) : fitted(payload);
95
108
  return `[Tool: ${name} (${id})]\n${text}${context}`;
96
109
  }
@@ -248,7 +261,7 @@ function skillLoadPayload(turn) {
248
261
  return null;
249
262
  }
250
263
  }
251
- const HOST_ONLY_KEYS = ['data', 'hostNotice'];
264
+ const HOST_ONLY_KEYS = ['data', 'hostNotice', 'mention'];
252
265
  export function historyPayload(output) {
253
266
  if (!output || typeof output !== 'object')
254
267
  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>;
@@ -1,6 +1,7 @@
1
1
  import { assign, enqueueActions } from 'xstate';
2
+ import { isFailureResultReference } from '../../helpers/failure-result.js';
2
3
  import { approveCompletion, requestApproval } from './actions/approval.js';
3
- import { addKnowledge, answerCompletion, continueGoal, continueStop, continueWithInput, failCompletion, finishWrapRound, finishRound, goalTurn, retryCappedSearch, retryCutRound, retryMalformedRound, retryMuteRound, retryNarratedRound, settleGoal, startInitialRound, startNextRound, wrapCompletion, wrapCutCompletion, wrapDeliveredCompletion, wrapExhaustedCompletion, wrapMuteCompletion, wrapSearchCappedCompletion } from './actions/completion.js';
4
+ import { addKnowledge, answerCompletion, continueGoal, continueStalledGoal, continueStop, continueWithInput, failCompletion, finishWrapRound, finishRound, markGoalStalled, retryCappedSearch, retryCutRound, retryMalformedRound, retryMuteRound, retryNarratedRound, settleGoal, startInitialRound, startNextRound, wrapCompletion, wrapCutCompletion, wrapDeliveredCompletion, wrapExhaustedCompletion, wrapMuteCompletion, wrapSearchCappedCompletion } from './actions/completion.js';
4
5
  import { authorizePrepare, requestPrepare, settlePrepare, settlePrepareFailure } from './actions/prepare.js';
5
6
  import { finishBatch, finishDirectTool, finishTool, endRunOnTool, queueDirectSearch, rejectCutOffTool, rejectDeniedApproval, rejectPlanModeWrite, rejectRepeatedTool, rejectTool, resolveTools, selectNextTool, startDirectTool, startTool } from './actions/tools.js';
6
7
  import { allResolvedToolsCapped, canMuteRetry, canRetryCut, canRetryMalformed, canRetryNarrated, canRetrySearchCap, hasQueuedTool, hasRoundsLeft, repeatsBlocked, searchPending } from './guards/retry.js';
@@ -104,6 +105,8 @@ export const completionActions = {
104
105
  addKnowledge: assignAction(addKnowledge),
105
106
  continueStop: assignAction(continueStop),
106
107
  continueGoal: goalAction(continueGoal),
108
+ continueStalledGoal: goalAction(continueStalledGoal),
109
+ markGoalStalled: assignAction(markGoalStalled),
107
110
  settleGoal: goalAction(settleGoal),
108
111
  retryMalformedRound: assignAction(retryMalformedRound),
109
112
  retryMuteRound: assignAction(retryMuteRound),
@@ -212,8 +215,9 @@ function goalAction(action) {
212
215
  turn: goal.turns,
213
216
  round: update.round ?? context.round
214
217
  };
215
- if (goal.status === 'open') {
216
- event.text = goalTurn(context);
218
+ const turn = update.history?.at(-1);
219
+ if (goal.status === 'open' && turn && !isFailureResultReference(turn)) {
220
+ event.text = turn.content;
217
221
  }
218
222
  if (goal.checks.length) {
219
223
  event.checks = goal.checks.map(({ name }) => name);
@@ -135,6 +135,9 @@ declare const createCompletionMachineImplementation: (context?: CompletionContex
135
135
  } | {
136
136
  type: "continueGoal";
137
137
  params: undefined;
138
+ } | {
139
+ type: "continueStalledGoal";
140
+ params: undefined;
138
141
  } | {
139
142
  type: "continueStop";
140
143
  params: import("./types.ts").AnsweredPayload;
@@ -169,6 +172,9 @@ declare const createCompletionMachineImplementation: (context?: CompletionContex
169
172
  } | {
170
173
  type: "finishWrapRound";
171
174
  params: import("./types.ts").RoundDonePayload;
175
+ } | {
176
+ type: "markGoalStalled";
177
+ params: undefined;
172
178
  } | {
173
179
  type: "markTimeUp";
174
180
  params: undefined;
@@ -437,10 +437,21 @@ const createCompletionMachineImplementation = (context, now = noClock) => setup(
437
437
  target: '#completion.active.wrapping',
438
438
  actions: [sameRoundAck, 'wrapDeliveredCompletion']
439
439
  },
440
+ {
441
+ guard: and([
442
+ 'repeatsBlocked',
443
+ 'goalUnmet',
444
+ 'hasRoundsLeft',
445
+ not('timeUp'),
446
+ 'goalTokensLeft'
447
+ ]),
448
+ target: '#completion.active.round',
449
+ actions: [nextRoundAck, 'continueStalledGoal']
450
+ },
440
451
  {
441
452
  guard: 'repeatsBlocked',
442
453
  target: '#completion.active.wrapping',
443
- actions: [sameRoundAck, 'wrapExhaustedCompletion']
454
+ actions: [sameRoundAck, 'wrapExhaustedCompletion', 'markGoalStalled']
444
455
  },
445
456
  {
446
457
  guard: and(['allResolvedToolsCapped', 'canRetrySearchCap', 'hasRoundsLeft']),
@@ -14,6 +14,7 @@ export declare function goalMet({ plan, goal }: Readonly<CompletionContext>): bo
14
14
  export declare function nudgeWithChecks(nudge: string, checks: readonly GoalCheck[], unnamed?: boolean): string;
15
15
  export declare function goalTokensLeft({ goal, metrics }: Readonly<CompletionContext>): boolean;
16
16
  export declare function goalStalled({ outcome }: Readonly<CompletionContext>): boolean;
17
+ export declare function settledSince(settled: CompletionContext['settledResults']): CompletionContext['settledResults'];
17
18
  export declare function retainFailureResults(history: readonly CompletionHistoryEntry[], values: Readonly<Record<string, FailureResultValue>>, failedCalls: Readonly<Record<string, SettledCall>>): Record<string, FailureResultValue>;
18
19
  export declare function activate(activated: string[], names: readonly string[]): string[];
19
20
  export interface ApplyHistorySpliceOptions {
@@ -56,6 +56,9 @@ export function goalTokensLeft({ goal, metrics }) {
56
56
  export function goalStalled({ outcome }) {
57
57
  return outcome === 'exhausted';
58
58
  }
59
+ export function settledSince(settled) {
60
+ return Object.fromEntries(Object.entries(settled).map(([key, result]) => [key, { ...result, repeats: 0 }]));
61
+ }
59
62
  export function retainFailureResults(history, values, failedCalls) {
60
63
  const retained = new Set();
61
64
  for (const entry of history) {
@@ -150,6 +150,7 @@ export interface ToolDonePayload {
150
150
  endedRun?: boolean;
151
151
  answer?: string;
152
152
  delivered?: boolean;
153
+ deliveryEndsRun?: boolean;
153
154
  durationMs?: number;
154
155
  activate?: string;
155
156
  plan?: PlanStep[];
@@ -256,8 +257,10 @@ export interface RunPolicy {
256
257
  unchangedMessage: string;
257
258
  failingMessage?: string;
258
259
  goalNudge: string;
260
+ goalStalledNudge: string;
259
261
  }
260
262
  export interface SettledResult {
263
+ name?: string;
261
264
  digest: string;
262
265
  repeats: number;
263
266
  round: number;
@@ -276,6 +279,7 @@ export interface GoalState {
276
279
  checks: GoalCheck[];
277
280
  checkable?: boolean;
278
281
  named?: boolean;
282
+ stalled?: true;
279
283
  }
280
284
  export interface QueuedInput {
281
285
  id?: string;
@@ -316,6 +320,7 @@ export interface CompletionContext {
316
320
  answer: string | null;
317
321
  delivered: boolean;
318
322
  deliveredThisRound: boolean;
323
+ deliveryEndsRun: boolean;
319
324
  activated: string[];
320
325
  outcome: RunOutcome | 'failed' | null;
321
326
  metrics: CompletionMetrics;
@@ -139,6 +139,9 @@ export declare class CompletionMachine {
139
139
  } | {
140
140
  type: "continueGoal";
141
141
  params: undefined;
142
+ } | {
143
+ type: "continueStalledGoal";
144
+ params: undefined;
142
145
  } | {
143
146
  type: "continueStop";
144
147
  params: import("./completion/types.ts").AnsweredPayload;
@@ -173,6 +176,9 @@ export declare class CompletionMachine {
173
176
  } | {
174
177
  type: "finishWrapRound";
175
178
  params: import("./completion/types.ts").RoundDonePayload;
179
+ } | {
180
+ type: "markGoalStalled";
181
+ params: undefined;
176
182
  } | {
177
183
  type: "markTimeUp";
178
184
  params: undefined;
@@ -9,5 +9,6 @@ export interface CustomShardCache {
9
9
  readonly files: ReadonlyArray<string>;
10
10
  }
11
11
  export declare function customShardCache(src: string, modelsDir: string | undefined): CustomShardCache | null;
12
+ export declare function localWeightFile(src: string, modelsDir: string | undefined): string | null;
12
13
  export declare function customDownloads(entry: CustomModelEntry, modelsDir: string | undefined): Promise<CustomDownloads>;
13
14
  export declare function isCustomModelCached(entry: CustomModelEntry, modelsDir: string | undefined): Promise<boolean>;
@@ -22,6 +22,9 @@ export function customShardCache(src, modelsDir) {
22
22
  const dir = path.join(modelsDir, 'sharded', shortHash(`${set.baseUrl}/${set.base}`));
23
23
  return { dir, files: set.shards.map((shard) => path.join(dir, shard.filename)) };
24
24
  }
25
+ export function localWeightFile(src, modelsDir) {
26
+ return customShardCache(src, modelsDir)?.files[0] ?? customFileCachePath(src, modelsDir);
27
+ }
25
28
  export async function customDownloads(entry, modelsDir) {
26
29
  const remote = sourcesOf(entry).filter(isRemoteSource);
27
30
  const shardDirs = remote.flatMap((src) => customShardCache(src, modelsDir)?.dir ?? []);
@@ -7,6 +7,12 @@ export interface GgufHeader {
7
7
  readonly contextLength?: number;
8
8
  readonly sizeLabel?: string;
9
9
  readonly tags?: ReadonlyArray<string>;
10
+ readonly headDims?: HeadDims;
11
+ readonly chatTemplate?: string;
12
+ }
13
+ export interface HeadDims {
14
+ readonly k?: number;
15
+ readonly v?: number;
10
16
  }
11
17
  export type GgufRangeFetch = (url: string, init: {
12
18
  headers: Record<string, string>;