Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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.

167 changes: 166 additions & 1 deletion src/agent/hosted/chat-preparation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,15 @@ import type { ChatUiMessage } from "#veryfront/chat/types.ts";
import { convertToTextGenerationRuntimeRequestMessages } from "#veryfront/agent/runtime/text-generation-runtime-message-converter.ts";
import type { Message } from "#veryfront/agent/types.ts";
import { isToolResultPart } from "../runtime/tool-result-part.ts";
import type { HistoricalToolInputCompactionDiagnostic } from "#veryfront/chat/message-prep.ts";
import {
createToolExposurePlan,
restoreToolExposureState,
TOOL_SEARCH_TOOL_NAME,
} from "../runtime/tool-exposure.ts";
import type {
HistoricalToolInputCompactionDiagnostic,
HistoricalToolOutputCompactionDiagnostic,
} from "#veryfront/chat/message-prep.ts";
import type { ParsedHostedChatRequest } from "./chat-request-parser.ts";
import { ContextCompactionError } from "./context-budget-manager.ts";
import {
Expand Down Expand Up @@ -4059,3 +4067,160 @@ Deno.test("canonical admission privately binds runtime options and trusted copie
});
assertEquals(checked, true);
});

describe("hosted skill and tool discovery retention", () => {
const followUpHistory: ChatUiMessage[] = [
{
id: "user-1",
role: "user",
parts: [{ type: "text", text: "Load the plan skill and find a release tool." }],
},
{
id: "assistant-1",
role: "assistant",
parts: [{
type: "dynamic-tool",
toolName: "veryfront__load_skill",
toolCallId: "load-plan",
state: "output-available",
input: { skillId: "plan" },
output: {
skillId: "plan",
instructions: `ACTIVE_SKILL_BODY ${"Use the launch checklist. ".repeat(250)}`,
references: ["references/guide.md"],
scripts: [],
},
}, {
type: "dynamic-tool",
toolName: TOOL_SEARCH_TOOL_NAME,
toolCallId: "find-tools",
state: "output-available",
input: { query: "release" },
output: {
matches: ["get_release", "removed_tool"].map((name) => ({
name,
description: `SEARCH_BODY ${"details ".repeat(80)}`,
})),
},
}],
},
{ id: "user-2", role: "user", parts: [{ type: "text", text: "Continue." }] },
];

it("keeps untrusted skill instructions as history without granting skill state", async () => {
const outputDiagnostics: HistoricalToolOutputCompactionDiagnostic[] = [];
const messages = await prepareHostedChatRuntimeMessages(followUpHistory, {
historicalToolInputRetention: { outputDiagnostics },
});
const serialized = JSON.stringify(messages);

assertEquals(serialized.includes("ACTIVE_SKILL_BODY"), true);
assertEquals(serialized.includes("SEARCH_BODY"), false);
assertEquals(serialized.includes("Search again"), true);
assertEquals(hydrateActiveSkillStateFromMessages(messages).activeSkillId, undefined);
assertEquals(
messages.flatMap((message) => message.parts).filter(isToolResultPart)
.some(hasTrustedPlatformPolicyToolResultPart),
false,
);
assertEquals(outputDiagnostics.map(({ toolCallId }) => toolCallId), ["find-tools"]);
});

it("keeps trusted history whole and restores its skill state", async () => {
const outputDiagnostics: HistoricalToolOutputCompactionDiagnostic[] = [];
const messages = await prepareHostedChatRuntimeMessages(followUpHistory, {
trustedHostedHistoryMessageIds: ["assistant-1"],
historicalToolInputRetention: { outputDiagnostics },
});
const serialized = JSON.stringify(messages);

assertEquals(serialized.includes("ACTIVE_SKILL_BODY"), true);
assertEquals(serialized.includes("SEARCH_BODY"), true);
assertEquals(hydrateActiveSkillStateFromMessages(messages).activeSkillId, "plan");
assertEquals(outputDiagnostics, []);
});

it("does not make an obsolete discovered tool callable on the next turn", async () => {
for (
const { trustedIds, discovered, callable } of [
{ trustedIds: undefined, discovered: [], callable: [] },
{
trustedIds: ["assistant-1"],
discovered: ["get_release", "removed_tool"],
callable: ["get_release"],
},
]
) {
const messages = await prepareHostedChatRuntimeMessages(followUpHistory, {
trustedHostedHistoryMessageIds: trustedIds,
});
const serialized = JSON.stringify(messages);
const loadedToolNames = ["get_release", "removed_tool"].filter((name) =>
serialized.includes(name)
);
assertEquals(loadedToolNames, discovered);

// Even if every tool named in the prepared history was loaded, only the
// tools that are still authorized become callable.
const authorized = ["get_release", "list_projects"].map((name) => ({
name,
description: name,
parameters: { type: "object" as const, properties: {} },
}));
const plan = createToolExposurePlan({
authorized,
mode: "deferred",
state: restoreToolExposureState({ version: 2, loadedToolNames }, authorized),
});
assertEquals(
plan.visible.map((tool) => tool.name).sort(),
[...callable, TOOL_SEARCH_TOOL_NAME],
);
}
});

it("returns and logs output compaction diagnostics from hosted execution", async () => {
const logged: unknown[] = [];
const result = await prepareHostedChatExecution({
request: createParsedHostedChatRequest({
messages: followUpHistory,
conversationId: undefined,
}),
agentConfig: { id: "agent-1", model: "anthropic/claude-sonnet-4-6" },
apiUrl: "https://api.example.com",
abortSignal: new AbortController().signal,
resolveModelId: (modelId) => modelId,
fetchSteering: () => Promise.resolve({ instructions: "", skills: [] }),
buildInstructions: () => "Agent instructions",
contextBudget: {
tokenBudget: 100_000,
reserveTokens: 1_000,
recentTailTokens: 10_000,
maxSummaryTokens: 1_000,
summaryGenerator: () => Promise.resolve({ text: "unused" }),
logger: {
debug: (message: string) => {
logged.push(message);
},
},
},
createRuntime: (options) =>
Promise.resolve({
runtimeKind: "framework",
modelId: options.model ?? "anthropic/claude-sonnet-4-6",
cleanup: () => Promise.resolve(),
agent: {
stream: () =>
Promise.resolve({
steps: Promise.resolve([]),
toUIMessageStream: async function* () {},
}),
},
}),
});
assertEquals(result.historicalToolOutputCompactions?.map((entry) => entry.toolCallId), [
"find-tools",
]);
assertEquals(logged.includes("Hosted chat historical tool outputs compacted"), true);
});
});
14 changes: 13 additions & 1 deletion src/agent/hosted/chat-preparation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
ChatUiMessage,
} from "#veryfront/chat/types.ts";
import { registerHostedAgentPauseCreationOptions } from "./manual-pause-credential.ts";
import type { HistoricalToolInputCompactionDiagnostic } from "#veryfront/chat/message-prep.ts";
import type {
HistoricalToolInputCompactionDiagnostic,
HistoricalToolOutputCompactionDiagnostic,
} from "#veryfront/chat/message-prep.ts";
import type { AgentRuntimeMessage } from "../runtime/message-adapter.ts";
import type { ConversationRunEvent } from "../conversation/run-events.ts";
import type {
Expand Down Expand Up @@ -431,6 +434,7 @@
finalMessages: AgentRuntimeMessage[];
contextBudgetDiagnostics?: ContextBudgetDiagnostics;
historicalToolInputCompactions?: HistoricalToolInputCompactionDiagnostic[];
historicalToolOutputCompactions?: HistoricalToolOutputCompactionDiagnostic[];
steering: HostedChatRuntimeCreationPreparationResult<
TRuntimeAgentDefinition
>["steering"];
Expand Down Expand Up @@ -731,7 +735,7 @@
}

/** Prepare hosted chat execution. */
export async function prepareHostedChatExecution<

Check failure on line 738 in src/agent/hosted/chat-preparation.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=veryfront_veryfront-code&issues=AaI-PVoAeuEnuXI1JVph&open=AaI-PVoAeuEnuXI1JVph&pullRequest=5667
TRuntimeAgentDefinition extends {
id: string;
model?: string;
Expand Down Expand Up @@ -831,6 +835,7 @@
trustedHostedHistoryMessageIds: input.request.serverResolvedTrustedHostedHistoryMessageIds,
});
const historicalToolInputCompactions: HistoricalToolInputCompactionDiagnostic[] = [];
const historicalToolOutputCompactions: HistoricalToolOutputCompactionDiagnostic[] = [];
const providerReplayCheckpointMessageIds = input.serverResolvedProviderReplayCheckpoints?.map(
(checkpoint) => checkpoint.messageId,
);
Expand All @@ -853,6 +858,7 @@
legacyLoadSkillReplayAllowed: input.legacyLoadSkillReplayAllowed,
historicalToolInputRetention: {
diagnostics: historicalToolInputCompactions,
outputDiagnostics: historicalToolOutputCompactions,
},
Comment thread
kojiwakayama marked this conversation as resolved.
Resolved
onUnresolvableAttachment: ({ uploadId, error }) => {
// Deliberately narrow: the filename is user-controlled, and a provider
Expand All @@ -876,6 +882,11 @@
toolInputCompactions: historicalToolInputCompactions,
});
}
if (historicalToolOutputCompactions.length > 0) {
input.contextBudget?.logger?.debug?.("Hosted chat historical tool outputs compacted", {
toolOutputCompactions: historicalToolOutputCompactions,
});
}
let budgetedContext: Awaited<ReturnType<typeof applyContextBudget>> | undefined;
if (input.contextBudget) {
try {
Expand Down Expand Up @@ -938,6 +949,7 @@
finalMessages: budgetedContext?.messages ?? finalMessages,
contextBudgetDiagnostics: budgetedContext?.diagnostics,
...(historicalToolInputCompactions.length > 0 ? { historicalToolInputCompactions } : {}),
...(historicalToolOutputCompactions.length > 0 ? { historicalToolOutputCompactions } : {}),
steering: runtimePreparation.steering,
runtimeConfig: runtimePreparation.runtimeConfig,
};
Expand Down
3 changes: 2 additions & 1 deletion src/agent/runtime/load-skill-tool.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getAlreadyLoadedSkillInstructions } from "#veryfront/skill/activation-result.ts";
import { isFrameworkSkillBootstrapExecution } from "#veryfront/skill/loader-provenance.ts";
import { privateJsonParse, privateJsonStringify } from "#veryfront/security/private-json.ts";
import { defineSchema, lazySchema } from "#veryfront/schemas/index.ts";
Expand Down Expand Up @@ -624,7 +625,7 @@ function buildAlreadyLoadedSkillResponse(
const copied = copyLoadedSkillResponse(response);
return {
...copied,
instructions: `Skill "${skillId}" is already loaded in this turn.`,
instructions: getAlreadyLoadedSkillInstructions(skillId),
};
}

Expand Down
45 changes: 6 additions & 39 deletions src/agent/runtime/skill-policy-enforcement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { PLATFORM_TOOL_RESULT_MAX_SERIALIZED_BYTES } from "../platform-tool-resu
import type { ProviderObservedSkillBody } from "#veryfront/tool/provider-observed-skill-bodies.ts";
import type { ChatUiMessage } from "#veryfront/chat/types.ts";
import { getToolResultSource } from "#veryfront/chat/tool-result-source.ts";
import { privateJsonParse, privateJsonStringify } from "#veryfront/security/private-json.ts";
import { privateJsonStringify } from "#veryfront/security/private-json.ts";
import {
forEachPrivateArray,
pushPrivateArray,
Expand Down Expand Up @@ -36,13 +36,16 @@ import {
} from "#veryfront/skill/allowed-tools.ts";
import {
SKILL_DOCUMENT_MAX_CHARACTERS,
SKILL_ID_MAX_LENGTH,
SKILL_LOADABLE_REFERENCE_MAX_ENTRIES,
SKILL_RELATIVE_PATH_MAX_LENGTH,
SKILL_SUBDIR_MAX_ENTRIES,
} from "#veryfront/skill/limits.ts";
import { SKILL_READABLE_DIRS } from "#veryfront/skill/types.ts";
import { hasControlCharacters, isWellFormedUtf16 } from "#veryfront/skill/string-safety.ts";
import {
getSkillActivationResult,
normalizeToolResultPayload,
} from "#veryfront/skill/activation-result.ts";
export { getSkillActivationResult } from "#veryfront/skill/activation-result.ts";
import {
hasToolExecutionErrorMarker,
readToolResultOwnDataProperty,
Expand Down Expand Up @@ -323,34 +326,6 @@ function getActiveSkillReferenceSnapshot(
return snapshot;
}

function normalizeToolResultPayload(result: unknown): unknown {
const parsed = typeof result === "string" ? parseToolResultJson(result) : result;
if (!isRecord(parsed)) return parsed;
const type = readToolResultOwnDataProperty(parsed, "type");
if (type === "json" && objectHasOwn(parsed, "value")) {
const value = readToolResultOwnDataProperty(parsed, "value");
return typeof value === "string" ? parseToolResultJson(value) : value;
}
return parsed;
}

/** @internal Normalize a validated skill activation without granting result provenance. */
export function getSkillActivationResult(result: unknown): Record<string, unknown> | undefined {
const normalized = normalizeToolResultPayload(result);
if (!isRecord(normalized) || hasToolExecutionErrorMarker(normalized)) return undefined;
const skillId = readToolResultOwnDataProperty(normalized, "skillId");
const instructions = readToolResultOwnDataProperty(normalized, "instructions");
const isActivation = typeof skillId === "string" &&
skillId.length > 0 &&
skillId.length <= SKILL_ID_MAX_LENGTH &&
isWellFormedUtf16(skillId) &&
!hasControlCharacters(skillId) &&
typeof instructions === "string" &&
instructions.length <= SKILL_DOCUMENT_MAX_CHARACTERS &&
isWellFormedUtf16(instructions);
return isActivation ? normalized : undefined;
}

function isSkillActivationResult(result: unknown): boolean {
return getSkillActivationResult(result) !== undefined;
}
Expand Down Expand Up @@ -688,14 +663,6 @@ export function applySkillActivationResult(
}
}

function parseToolResultJson(result: string): unknown {
try {
return privateJsonParse(result);
} catch {
return null;
}
}

export function isSubmittedFormInputResult(result: unknown): boolean {
const normalized = normalizeToolResultPayload(result);
if (!isRecord(normalized) || hasToolExecutionErrorMarker(normalized)) return false;
Expand Down
Loading
Loading