Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 33 additions & 32 deletions docs/api-reference/veryfront/chat.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions docs/api-reference/veryfront/provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ import {
| `createStreamRetentionBudget` | Create an empty retention budget. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/provider/runtime-loader/stream-retention.ts) |
| `createWarningCollector` | Create warning collector. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/provider/runtime-loader.ts) |
| `fileInputBaseName` | The base name of a file part's filename, or `undefined` when none is usable. Requests and errors leave the machine, so a local path must not. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/provider/runtime-loader/inline-file.ts) |
| `findActiveSkillCallIndex` | Find the assistant message that loaded the active skill, or return -1. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/skill/active-skill.ts) |
| `getAnthropicMessagesUrl` | Return Anthropic messages URL. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/provider/runtime-loader/provider-endpoints.ts) |
| `getGoogleEmbeddingUrl` | Return Google embedding URL. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/provider/runtime-loader/provider-endpoints.ts) |
| `getGoogleGenerateContentUrl` | Return Google generate content URL. | [source](https://github.com/veryfront/veryfront-code/blob/main/src/provider/runtime-loader/provider-endpoints.ts) |
Expand Down
117 changes: 117 additions & 0 deletions extensions/ext-llm-anthropic/src/anthropic-request-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4897,6 +4897,123 @@ describe("ext-llm-anthropic/anthropic-request-builder", () => {
assertEquals(body.thinking, { type: "enabled", budget_tokens: 4096 });
});

it("keeps the active skill round when it compacts completed historical tool rounds", () => {
const round = (toolCallId: string, instructions: string): RuntimePromptMessage[] => [
{
role: "assistant",
content: [{
type: "tool-call",
toolCallId,
toolName: "veryfront__load_skill",
input: { skillId: "plan" },
}],
},
{
role: "tool",
content: [{
type: "tool-result",
toolCallId,
toolName: "veryfront__load_skill",
output: { type: "json", value: { skillId: "plan", instructions } },
}],
},
];
const prompt: RuntimePromptMessage[] = [
{ role: "user", content: [{ type: "text", text: "Load the plan." }] },
...round("old", "OLD_SKILL"),
...round("active", "ACTIVE_SKILL"),
...round("repeat", 'Skill "plan" is already loaded in this turn.'),
{ role: "assistant", content: [{ type: "text", text: "Loaded." }] },
{ role: "user", content: [{ type: "text", text: "Continue." }] },
];

const body = buildAnthropicMessagesRequest(
"claude-sonnet-4-6",
"anthropic",
{ prompt },
false,
createWarningCollector(),
);

const serialized = JSON.stringify(body.messages);
assertEquals(serialized.includes("ACTIVE_SKILL"), true);
assertEquals(serialized.includes("OLD_SKILL"), false);
assertEquals(
body.messages.flatMap(({ content }: { content: Array<Record<string, unknown>> }) =>
content.flatMap((block) =>
block.type === "tool_use"
? [`use:${block.id}`]
: block.type === "tool_result"
? [`result:${block.tool_use_id}`]
: []
)
),
["use:active", "result:active"],
);
});

it("replays thinking with the active skill round and its result", () => {
const body = buildAnthropicMessagesRequest(
"claude-sonnet-4-6",
"anthropic",
{
prompt: [
{ role: "user", content: [{ type: "text", text: "Load the plan." }] },
{
role: "assistant",
content: [{
type: "tool-call",
toolCallId: "active",
toolName: "load_skill",
input: { skillId: "plan" },
}],
providerMetadata: {
anthropic: {
rawAssistantMessages: [[
{ type: "thinking", thinking: "Load it.", signature: "signed" },
{
type: "tool_use",
id: "active",
name: "load_skill",
input: { skillId: "plan" },
},
]],
},
},
},
{
role: "tool",
content: [{
type: "tool-result",
toolCallId: "active",
toolName: "load_skill",
output: { type: "json", value: { skillId: "plan", instructions: "ACTIVE" } },
}],
},
{ role: "assistant", content: [{ type: "text", text: "Loaded." }] },
{ role: "user", content: [{ type: "text", text: "Continue." }] },
],
},
false,
createWarningCollector(),
);

assertEquals(JSON.parse(JSON.stringify(body.messages)).slice(1, 3), [{
role: "assistant",
content: [
{ type: "thinking", thinking: "Load it.", signature: "signed" },
{ type: "tool_use", id: "active", name: "load_skill", input: { skillId: "plan" } },
],
}, {
role: "user",
content: [{
type: "tool_result",
tool_use_id: "active",
content: '{"skillId":"plan","instructions":"ACTIVE"}',
}],
}]);
});

it("compacts completed historical tool rounds before replaying later user turns", () => {
const prompt: RuntimePromptMessage[] = [
{ role: "user", content: [{ type: "text", text: "Build a briefing." }] },
Expand Down
13 changes: 13 additions & 0 deletions extensions/ext-llm-anthropic/src/anthropic-request-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
assertProviderFetchablePayloadFileUrls,
canIdentifyProxyWithoutHooks,
closeSchemaForOutputConfig,
findActiveSkillCallIndex,
isImageFileInput,
isProxyWithoutHooks,
jsonValuesEqual,
Expand Down Expand Up @@ -856,8 +857,10 @@
message: Extract<ModelRuntimePromptMessage, { readonly role: "assistant" }>,
index: number,
lastHistoricalAssistantTextIndex: number,
activeSkillCallIndex: number,
): boolean {
return index < lastHistoricalAssistantTextIndex &&
index !== activeSkillCallIndex &&
Comment thread
kojiwakayama marked this conversation as resolved.
Resolved
message.content.some((part) => part.type === "tool-call");
}

Expand Down Expand Up @@ -961,6 +964,7 @@
rawAssistantMessagesByIndex: ReadonlyMap<number, unknown[]>,
lastUserIndex: number,
lastHistoricalAssistantTextIndex: number,
activeSkillCallIndex: number,
state: AnthropicReplayPlanState,
): void {
if (message.role === "system" || message.role === "user") {
Expand All @@ -975,6 +979,7 @@
message,
index,
lastHistoricalAssistantTextIndex,
activeSkillCallIndex,
);
if (shouldCompactCompletedToolRound) state.compactedToolRoundIndices.add(index);
if (
Expand Down Expand Up @@ -1020,6 +1025,7 @@
rawAssistantMessagesByIndex: ReadonlyMap<number, unknown[]>,
lastUserIndex: number,
lastHistoricalAssistantTextIndex: number,
activeSkillCallIndex: number,
): {
exactReplayIndices: Set<number>;
thinkingOnlyReplayIndices: Set<number>;
Expand Down Expand Up @@ -1049,6 +1055,7 @@
rawAssistantMessagesByIndex,
lastUserIndex,
lastHistoricalAssistantTextIndex,
activeSkillCallIndex,
state,
);
}
Expand Down Expand Up @@ -1325,10 +1332,11 @@
appendAnthropicReplayMessages(messages, compactedMessages, state);
}

function appendAnthropicAssistantMessage(

Check warning on line 1335 in extensions/ext-llm-anthropic/src/anthropic-request-builder.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Function 'appendAnthropicAssistantMessage' has too many parameters (8). Maximum allowed is 7.

See more on https://sonarcloud.io/project/issues?id=veryfront_veryfront-code&issues=AaI-TwrQqwLG209tsLkT&open=AaI-TwrQqwLG209tsLkT&pullRequest=5667
message: Extract<ModelRuntimePromptMessage, { readonly role: "assistant" }>,
index: number,
lastHistoricalAssistantTextIndex: number,
activeSkillCallIndex: number,
rawAssistantMessagesByIndex: ReadonlyMap<number, unknown[]>,
rawReplayPlan: ReturnType<typeof planAnthropicRawAssistantReplay>,
messages: AnthropicCompatibleMessage[],
Expand All @@ -1339,6 +1347,7 @@
message,
index,
lastHistoricalAssistantTextIndex,
activeSkillCallIndex,
);
const rawAssistantMessages = rawAssistantMessagesByIndex.get(index);
if (rawAssistantMessages && rawReplayPlan.exactReplayIndices.has(index)) {
Expand Down Expand Up @@ -1540,6 +1549,8 @@
message.role === "assistant" &&
message.content.some((part) => part.type === "text" && part.text.length > 0)
);
// The model still follows the active skill, so its instructions stay in the request.
const activeSkillCallIndex = findActiveSkillCallIndex(prompt);
const rawAssistantMessagesByIndex = new Map<number, unknown[]>();
for (const [index, message] of prompt.entries()) {
if (message.role !== "assistant") continue;
Expand All @@ -1553,6 +1564,7 @@
rawAssistantMessagesByIndex,
lastUserIndex,
lastHistoricalAssistantTextIndex,
activeSkillCallIndex,
);
const state: AnthropicPromptConversionState = {
skippingHistoricalToolResults: false,
Expand Down Expand Up @@ -1588,6 +1600,7 @@
message,
index,
lastHistoricalAssistantTextIndex,
activeSkillCallIndex,
rawAssistantMessagesByIndex,
rawReplayPlan,
messages,
Expand Down
117 changes: 117 additions & 0 deletions src/agent/hosted/active-skill-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { findActiveSkill } from "#veryfront/skill/active-skill.ts";
import { stringifyChatJson } from "#veryfront/chat/json-value.ts";
import type { HistoricalToolOutputCompactionDiagnostic } from "#veryfront/chat/message-prep.ts";
import { estimateTokens } from "#veryfront/chat/message-prep-budget.ts";
import type { AgentRuntimeMessage, AgentRuntimeMessagePart } from "../runtime/message-adapter.ts";
import { isToolResultPart } from "../runtime/tool-result-part.ts";

type ActiveSkillPair = {
callIndex: number;
toolCallId: string;
toolName: string;
result: unknown;
messages: AgentRuntimeMessage[];
};

function hasToolCallId(part: AgentRuntimeMessagePart, toolCallId: string): boolean {
return "toolCallId" in part && part.toolCallId === toolCallId;
}

/**
* Copy a message with only one part. The part object is reused, so its trust mark
* is neither added nor lost. The new id keeps a partial copy from matching a
* provider replay checkpoint, which expects the complete message.
*/
function keepOnlyPart(
message: AgentRuntimeMessage,
part: AgentRuntimeMessagePart,
): AgentRuntimeMessage {
return { ...message, id: `active_skill_context:${message.id}`, parts: [part] };
}

/** Find the active skill call and result in messages that are about to be summarized. */
function findSummarizedSkillPair(
messages: readonly AgentRuntimeMessage[],
tailStartIndex: number,
): ActiveSkillPair | undefined {
const active = findActiveSkill(
messages,
(part) => isToolResultPart(part) ? { toolName: part.toolName, value: part.result } : undefined,
);
if (!active || active.messageIndex >= tailStartIndex || !isToolResultPart(active.part)) {
return undefined;
}
const { toolCallId, toolName, result } = active.part;
for (let index = active.messageIndex - 1; index >= 0; index--) {
const message = messages[index]!;
// A tool call and its result always belong to the same turn.
if (message.role === "user") return undefined;
if (message.role !== "assistant") continue;
const call = message.parts.find((part) =>
part.type !== "tool-result" && hasToolCallId(part, toolCallId)
);
if (!call) continue;
return {
callIndex: index,
toolCallId,
toolName,
result,
messages: [
keepOnlyPart(message, call),
keepOnlyPart(messages[active.messageIndex]!, active.part),
],
};
}
return undefined;
}

/** @internal Put a summarized active skill back into compacted context when it fits. */
export function restoreActiveSkillPair(input: {
messages: readonly AgentRuntimeMessage[];
tailStartIndex: number;
summaryMessage: AgentRuntimeMessage;
retainedMessages: readonly AgentRuntimeMessage[];
preservedRequest?: AgentRuntimeMessage;
usableBudget: number;
}): {
messages: AgentRuntimeMessage[];
droppedActiveSkill?: HistoricalToolOutputCompactionDiagnostic;
} {
const { messages, summaryMessage, retainedMessages, preservedRequest } = input;
const compacted = [summaryMessage, ...retainedMessages];
const pair = findSummarizedSkillPair(messages, input.tailStartIndex);
if (!pair) return { messages: compacted };

const drop = (reason: HistoricalToolOutputCompactionDiagnostic["reason"]) => ({
messages: compacted,
droppedActiveSkill: {
source: "provider" as const,
toolName: pair.toolName,
toolCallId: pair.toolCallId,
originalOutputChars: stringifyChatJson(pair.result).length,
retainedOutputChars: 0,
reason,
},
});
// Two calls with one id are invalid for a provider once the turns between them are gone.
if (
retainedMessages.some((message) =>
message.parts.some((part) => hasToolCallId(part, pair.toolCallId))
Comment thread
kojiwakayama marked this conversation as resolved.
Resolved
)
) {
return drop("active_skill_tool_call_conflict");
}

// Keep the original order: a preserved request can come before or after the skill call.
const requestIsFirst = preservedRequest !== undefined &&
messages.indexOf(preservedRequest) < pair.callIndex;
const insertAt = requestIsFirst ? 2 : 1;
const restored = [
...compacted.slice(0, insertAt),
...pair.messages,
...compacted.slice(insertAt),
];
return estimateTokens(restored) <= input.usableBudget
? { messages: restored }
: drop("active_skill_over_token_budget");
}
Loading
Loading