Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
feat: Fingerprint Agent Context for Zero-Read Warm Continuation (#15299)
Danny Avila6fba51a35ae2
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.jsindex a947d3682c..3c4db501cb 100644--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js@@ -86,8 +86,6 @@ const mockResolveAgentTurnExecutionPlan = jest.fn((input) => {input.event?.expectedAction != null &&input.checkpointerType !== 'memory' &&!input.canPause &&- !input.hasSkillPrimes &&- !input.hasMemoryContext &&!input.expectedActionMayDetach;let strategy = 'history';if (input.isNewConversation) {@@ -4477,27 +4475,6 @@ describe('ResumableAgentController resume metadata', () => {undefined,undefined,],- [- 'always-apply skill prime',- { toolDefinitions: [], alwaysApplySkillPrimes: [{ name: 'playbook', body: '# playbook' }] },- {},- undefined,- undefined,- ],- [- 'manual skill prime',- { toolDefinitions: [], manualSkillPrimes: [{ name: 'playbook', body: '# playbook' }] },- {},- undefined,- undefined,- ],- [- 'skills-capable (history-derived re-priming)',- { toolDefinitions: [] },- {},- undefined,- { primeInvokedSkills: async () => undefined },- ],['background-capable expected action',{ toolDefinitions: [], backgroundToolNames: ['submit_move_mcp_chess'] },@@ -4614,7 +4591,7 @@ describe('ResumableAgentController resume metadata', () => {options: {agent: {toolDefinitions: [],- manualSkillPrimes: [{ name: 'playbook', body: '# playbook' }],+ backgroundToolNames: ['submit_move'],},},sendMessage: jest.fn(),@@ -4689,7 +4666,7 @@ describe('ResumableAgentController resume metadata', () => {options: {agent: {toolDefinitions: [],- manualSkillPrimes: [{ name: 'playbook', body: '# playbook' }],+ backgroundToolNames: ['submit_move'],},},sendMessage: jest.fn(async () => ({ messageId: 'must-not-run' })),@@ -4758,7 +4735,7 @@ describe('ResumableAgentController resume metadata', () => {options: {agent: {toolDefinitions: [],- manualSkillPrimes: [{ name: 'playbook', body: '# playbook' }],+ backgroundToolNames: ['submit_move'],},},sendMessage: jest.fn(async () => {@@ -4840,7 +4817,7 @@ describe('ResumableAgentController resume metadata', () => {options: {agent: {toolDefinitions: [],- manualSkillPrimes: [{ name: 'playbook', body: '# playbook' }],+ backgroundToolNames: ['submit_move'],},},sendMessage: jest.fn(async () => {diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 5fe5d1a3eb..d5c442e169 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -1,5 +1,9 @@require('events').EventEmitter.defaultMaxListeners = 100;-const { logger } = require('@librechat/data-schemas');+const {+ logger,+ MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH,+ MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH,+} = require('@librechat/data-schemas');const { getBufferString, HumanMessage } = require('@librechat/agents/langchain/messages');const {createRun,@@ -98,6 +102,7 @@ const {applyAttachmentOnlyText,hydrateMissingIndexTokenCounts,injectSkillPrimes,+ buildAgentEventActorSkillMessages,collectFreshSkillPrimeNames,isSkillPrimeMessage,collectFileIds,@@ -121,6 +126,10 @@ const {collectReachableAgents,getDynamicToolContexts,getSafeErrorMetadata,+ createInitializedAgentContextFingerprint,+ createSkillContentDigest,+ normalizeAgentEventActorDiscoveredTools,+ MAX_AGENT_CONTEXT_SKILLS,} = require('@librechat/api');const {Run,@@ -162,6 +171,65 @@ const loadAgent = (params) => loadAgentFn(params, { getAgent: db.getAgent, getMCconst MEMORY_INPUT_CHARS_PER_TOKEN = 8;+function normalizeEventActorSummary(summary) {+ if (summary == null) {+ return undefined;+ }+ if (+ typeof summary.text !== 'string' ||+ summary.text.length === 0 ||+ summary.text.length > MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH ||+ !Number.isFinite(summary.tokenCount) ||+ summary.tokenCount < 0+ ) {+ throw new RangeError('Event actor summary state is invalid');+ }+ return { text: summary.text, tokenCount: summary.tokenCount };+}++function normalizeEventActorContextMeta(contextMeta) {+ if (contextMeta == null) {+ return undefined;+ }+ const { calibrationRatio, encoding } = contextMeta;+ if (+ !Number.isFinite(calibrationRatio) ||+ calibrationRatio < 0.5 ||+ calibrationRatio > 5 ||+ (encoding != null &&+ (typeof encoding !== 'string' ||+ encoding.length === 0 ||+ encoding.length > MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH))+ ) {+ throw new RangeError('Event actor context calibration is invalid');+ }+ return { calibrationRatio, ...(encoding == null ? {} : { encoding }) };+}++function getLatestEventActorSummary(contentParts) {+ if (!Array.isArray(contentParts)) {+ return undefined;+ }+ for (let index = contentParts.length - 1; index >= 0; index -= 1) {+ const part = contentParts[index];+ if (part?.type !== ContentTypes.SUMMARY || !Array.isArray(part.content)) {+ continue;+ }+ const text = part.content+ .map((block) => (typeof block?.text === 'string' ? block.text : ''))+ .join('')+ .trim();+ if (text.length === 0) {+ continue;+ }+ return normalizeEventActorSummary({+ text,+ tokenCount: Number.isFinite(part.tokenCount) && part.tokenCount >= 0 ? part.tokenCount : 0,+ });+ }+ return undefined;+}+function getUserFacingRequestError(baseMessage, error, appConfig) {const protectionEnabled = hasModelBoundContentProtection(appConfig?.filters,@@ -216,6 +284,9 @@ class AgentClient extends BaseClient {this.eventActorCheckpointId = undefined;this.eventActorInvocationId = undefined;this.eventActorContinuation = undefined;+ this.eventActorSkillPrimeResult = undefined;+ this.eventActorDiscoveredToolNames = undefined;+ this.eventActorSummary = undefined;/** @type {AgentRun} */this.run;@@ -293,6 +364,53 @@ class AgentClient extends BaseClient {usageEmitSink?.filter((event) => event?.usage_type === 'subagent').length ?? 0;/** @type {AgentClientOptions} */this.options = Object.assign({ endpoint: options.endpoint }, clientOptions);+ if (+ this.options.req?._isAgentTrigger === true &&+ this.options.req?._agentEventBindingParentConversationId != null+ ) {+ /** Preserve initialization-time semantic inputs before buildMessages+ * decorates live agent instructions with request memory/MCP context. */+ this.eventActorAgentContextSources = this.getEventActorAgents().map((agent) => ({+ id: agent.id,+ version: agent.version,+ provider: agent.provider,+ model: agent.model ?? agent.model_parameters?.model,+ instructions: agent.instructions,+ additional_instructions: agent.additional_instructions,+ model_parameters: JSON.parse(JSON.stringify(agent.model_parameters ?? {})),+ toolDefinitions: JSON.parse(JSON.stringify(agent.toolDefinitions ?? [])),+ toolRegistryDefinitions: JSON.parse(+ JSON.stringify(+ [...(agent.toolRegistry?.values() ?? [])].sort((left, right) =>+ left.name.localeCompare(right.name),+ ),+ ),+ ),+ tool_options: JSON.parse(JSON.stringify(agent.tool_options ?? {})),+ execution: JSON.parse(+ JSON.stringify({+ endpoint: agent.endpoint,+ configId: agent.configId,+ tool_kwargs: agent.tool_kwargs,+ edges: agent.edges,+ end_after_tools: agent.end_after_tools,+ hide_sequential_outputs: agent.hide_sequential_outputs,+ stateful_code_sessions: agent.stateful_code_sessions,+ stateful_code_environment: agent.stateful_code_environment,+ artifacts: agent.artifacts,+ recursion_limit: agent.recursion_limit,+ subagents: agent.subagents,+ memory_scope: agent.memory_scope,+ skills_enabled: agent.skills_enabled,+ skills: agent.skills,+ backgroundToolNames: agent.backgroundToolNames,+ intentToolNames: agent.intentToolNames,+ }),+ ),+ manualSkillPrimes: agent.manualSkillPrimes,+ alwaysApplySkillPrimes: agent.alwaysApplySkillPrimes,+ }));+ }/** @type {string} */this.model = this.options.agent.model_parameters.model;/** The key for the usage object's input tokens@@ -1551,7 +1669,152 @@ class AgentClient extends BaseClient {return files;}+ getEventActorAgents() {+ return collectReachableAgents([this.options.agent, ...(this.agentConfigs?.values() ?? [])]);+ }++ /**+ * Resolves the committed Skill manifest and request-cached memory before the+ * actor chooses warm versus rebuilt continuation. No message history is read.+ *+ * @param {import('@librechat/data-schemas').IAgentEventActorState | null} state+ */+ async prepareEventActorContext(state) {+ if (state?.contextFingerprint == null) {+ return undefined;+ }+ if (isMemoryAgentEnabled(this.options.req.config?.memory)) {+ return undefined;+ }+ const storedManifest = Array.isArray(state.skillManifest) ? state.skillManifest : [];+ if (storedManifest.length > MAX_AGENT_CONTEXT_SKILLS) {+ return undefined;+ }+ let discoveredToolNames;+ let summary;+ let contextMeta;+ try {+ discoveredToolNames = normalizeAgentEventActorDiscoveredTools(state.discoveredToolNames);+ summary = normalizeEventActorSummary(state.summary);+ contextMeta = normalizeEventActorContextMeta(state.contextMeta);+ } catch {+ return undefined;+ }++ let skillPrimeResult = {};+ if (storedManifest.length > 0) {+ if (typeof this.options.primeInvokedSkills !== 'function') {+ return undefined;+ }+ skillPrimeResult = await this.options.primeInvokedSkills(+ [],+ storedManifest.map((skill) => skill.name),+ );+ const resolvedManifest = [...(skillPrimeResult?.skillManifest ?? [])].sort((left, right) =>+ left.id.localeCompare(right.id),+ );+ const expectedManifest = [...storedManifest].sort((left, right) =>+ left.id.localeCompare(right.id),+ );+ if (JSON.stringify(resolvedManifest) !== JSON.stringify(expectedManifest)) {+ return undefined;+ }+ }+ this.eventActorSkillPrimeResult = skillPrimeResult;+ this.eventActorDiscoveredToolNames = discoveredToolNames;+ this.eventActorSummary = summary;+ this.contextMeta = contextMeta;+ const context = await this.getEventActorContext(storedManifest, discoveredToolNames);+ const skillBodies = new Map(skillPrimeResult?.skills ?? []);+ const rootAgentContext = this.eventActorAgentContextSources?.[0];+ for (const skill of [+ ...(rootAgentContext?.manualSkillPrimes ?? []),+ ...(rootAgentContext?.alwaysApplySkillPrimes ?? []),+ ]) {+ if (typeof skill.name === 'string' && typeof skill.body === 'string') {+ skillBodies.set(skill.name, skill.body);+ }+ }+ return {+ ...context,+ checkpointMessageOverlay: {+ source: 'skill',+ messages: buildAgentEventActorSkillMessages(skillBodies),+ },+ };+ }++ /**+ * @param {Array<{id: string, name: string, version: number}>} [baseManifest]+ */+ async getEventActorContext(baseManifest = [], baseDiscoveredToolNames) {+ const manifest = new Map(baseManifest.map((skill) => [skill.id, skill]));+ for (const skill of this.eventActorAgentContextSources?.[0]?.manualSkillPrimes ?? []) {+ if (!Number.isInteger(skill.version) || skill.version < 1 || typeof skill.body !== 'string') {+ throw new Error('Manual Skill is missing semantic identity');+ }+ manifest.set(skill._id.toString(), {+ id: skill._id.toString(),+ name: skill.name,+ version: skill.version,+ contentDigest: createSkillContentDigest(skill.body),+ });+ }+ for (const skill of this.eventActorSkillPrimeResult?.skillManifest ?? []) {+ manifest.set(skill.id, skill);+ }+ for (const skill of this.options.invokedSkillIdentities?.values?.() ?? []) {+ manifest.set(skill.id, skill);+ }+ if (manifest.size > MAX_AGENT_CONTEXT_SKILLS) {+ throw new RangeError(`Event actor exceeds ${MAX_AGENT_CONTEXT_SKILLS} durable Skills`);+ }+ const skillManifest = [...manifest.values()].sort((left, right) =>+ left.id.localeCompare(right.id),+ );+ const agents = this.getEventActorAgents();+ const memory = await this.getEventActorMemorySnapshots(agents);+ const agentsConfig = this.options.req.config?.endpoints?.[EModelEndpoint.agents];+ const discoveredToolNames = normalizeAgentEventActorDiscoveredTools([+ ...(baseDiscoveredToolNames ??+ (this.eventActorContinuation === 'warm' ? (this.eventActorDiscoveredToolNames ?? []) : [])),+ ...(this.run == null ? [] : getRunDiscoveredTools(this.run)),+ ]);+ const summary = getLatestEventActorSummary(this.contentParts) ?? this.eventActorSummary;+ this.eventActorSummary = summary;+ return {+ fingerprint: createInitializedAgentContextFingerprint({+ agents: this.eventActorAgentContextSources ?? agents,+ invokedSkills: skillManifest,+ approvalPolicy: agentsConfig?.toolApproval,+ memory,+ discoveredToolNames,+ checkpointerType: agentsConfig?.checkpointer?.type,+ }),+ skillManifest,+ discoveredToolNames,+ ...(summary == null ? {} : { summary }),+ ...(this.contextMeta == null ? {} : { contextMeta: this.contextMeta }),+ };+ }++ async loadHistory(conversationId, parentMessageId = null) {+ if (this.eventActorContinuation === 'warm') {+ logger.debug('[AgentClient] Skipping durable history for compatible event actor', {+ conversationId,+ });+ return [];+ }+ return super.loadHistory(conversationId, parentMessageId);+ }+async buildMessages(messages, parentMessageId, _buildOptions, opts) {+ if (this.eventActorContinuation === 'cold') {+ /** Compatibility was rejected after warm state preparation. Rebuild all+ * non-checkpointed state from durable history, never from that stale head. */+ this.eventActorSummary = undefined;+ this.contextMeta = undefined;+ }/** Always pass mapMethod; getMessagesForConversation applies it only to messages with addedConvo flag */const orderedMessages = this.constructor.getMessagesForConversation({messages,@@ -1616,7 +1879,7 @@ class AgentClient extends BaseClient {* original promise later still propagates either error.*/const earlySharedContextPromise = Promise.all([- this.useMemory(),+ this.getSharedMemoryContext(),resolveConfigServers(this.options.req),]);void earlySharedContextPromise.catch(() => {});@@ -2486,6 +2749,55 @@ class AgentClient extends BaseClient {return { withKeys, withoutKeys };}+ /** Reuses the exact memory authorization/load promise for planning and prompt construction. */+ getSharedMemoryContext() {+ this.memoryContextPromise ??= this.useMemory();+ return this.memoryContextPromise;+ }++ /**+ * Returns the model-bound memory snapshots needed for event-actor compatibility.+ * The request-scoped memory cache makes this the same read used by buildMessages.+ *+ * @param {Array<import('@librechat/api').InitializedAgent>} agents+ * @returns {Promise<Array<{scope: string, withKeys?: string, withoutKeys?: string}>>}+ */+ async getEventActorMemorySnapshots(agents) {+ const primary = await this.getSharedMemoryContext();+ if (!primary) {+ return [];+ }+ const userId = this.options.req.user.id + '';+ const primaryScope = getMemoryAgentId(this.options.agent);+ const scopes = new Map([[primaryScope ?? '', primary]]);+ await Promise.all(+ agents.map(async (agent) => {+ if (agent !== this.options.agent && !agentHasInlineMemoryTools(agent)) {+ return;+ }+ const agentId = getMemoryAgentId(agent);+ const scope = agentId ?? '';+ if (scopes.has(scope)) {+ return;+ }+ const snapshot = await getRequestMemories({+ req: this.options.req,+ userId,+ agentId,+ getFormattedMemories: db.getFormattedMemories,+ });+ scopes.set(scope, snapshot);+ }),+ );+ return [...scopes]+ .map(([scope, snapshot]) => ({+ scope: scope || 'shared',+ ...(snapshot.withKeys ? { withKeys: snapshot.withKeys } : {}),+ ...(snapshot.withoutKeys ? { withoutKeys: snapshot.withoutKeys } : {}),+ }))+ .sort((left, right) => left.scope.localeCompare(right.scope));+ }+/*** Filters out image URLs from message content* @param {BaseMessage} message - The message to filter@@ -3414,9 +3726,17 @@ class AgentClient extends BaseClient {const tokenCounter = await createCachedTokenCounter(this.getEncoding());/** Pre-resolve invoked skill bodies + re-prime files before formatting messages */- const skillPrimeResult = this.options.primeInvokedSkills- ? await this.options.primeInvokedSkills(payload)- : undefined;+ if (this.eventActorContinuation === 'cold') {+ this.eventActorSkillPrimeResult = undefined;+ this.eventActorDiscoveredToolNames = undefined;+ }+ let skillPrimeResult = this.eventActorSkillPrimeResult;+ if (skillPrimeResult == null) {+ skillPrimeResult = this.options.primeInvokedSkills+ ? await this.options.primeInvokedSkills(payload)+ : undefined;+ }+ this.eventActorSkillPrimeResult = skillPrimeResult;/** Seed each reachable agent's trusted code-session partition. */const initialSessions = buildInitialToolSessions({@@ -3473,6 +3793,11 @@ class AgentClient extends BaseClient {skillPrimeResult?.skills,formatOptions,);+ if (this.eventActorContinuation !== 'warm') {+ this.eventActorSummary = initialSummary;+ }+ const continuationSummary =+ this.eventActorContinuation === 'warm' ? this.eventActorSummary : initialSummary;if (boundaryTokenAdjustment) {logger.debug(`[AgentClient] Boundary token adjustment: ${boundaryTokenAdjustment.original} → ${boundaryTokenAdjustment.adjusted} (${boundaryTokenAdjustment.remainingChars}/${boundaryTokenAdjustment.totalChars} chars)`,@@ -3698,6 +4023,8 @@ class AgentClient extends BaseClient {// carries no messages, so history cannot identify the conversation.conversationId: this.conversationId,messages,+ discoveredToolNames:+ this.eventActorContinuation === 'warm' ? this.eventActorDiscoveredToolNames : undefined,modelCallbacks: [modelBoundCallback],// This controller implements the full HITL pause/resume lifecycle (handleRunInterrupt// persists the pending action; the /resume route rebuilds + continues the run), so it@@ -3718,11 +4045,11 @@ class AgentClient extends BaseClient {// plus the one new event), so those indices address different// messages and the pruner would never recount them. Hand it an empty// map so every count is derived from the messages actually in state.- // `initialSummary` deliberately stays: it rides the system tail, and- // the pre-boundary turns it summarizes were excluded from the very- // history the committed checkpoint was built from.+ // The active summary lives in AgentContext rather than checkpointed+ // graph messages, so warm turns restore the actor-head copy while+ // rebuilt turns use the summary reconstructed from durable history.indexTokenCountMap: this.eventActorContinuation === 'warm' ? {} : indexTokenCountMap,- initialSummary,+ initialSummary: continuationSummary,initialSessions,calibrationRatio,runId: this.responseMessageId,@@ -3867,6 +4194,10 @@ class AgentClient extends BaseClient {this.contentParts.unshift(...manualParts);}+ /** Summaries are run state, even when sequential-output reshaping hides+ * their display block from the persisted response content. */+ this.eventActorSummary =+ getLatestEventActorSummary(this.contentParts) ?? this.eventActorSummary;this.applyHideSequentialOutputsFilter();this.rebaseActivityPhaseBounds(contentBeforeReshape);} catch (err) {@@ -3917,6 +4248,10 @@ class AgentClient extends BaseClient {});}} finally {+ /** An aborted/erroring run can still have completed compaction before+ * the failure; retain that model-visible state for actor reconciliation. */+ this.eventActorSummary =+ getLatestEventActorSummary(this.contentParts) ?? this.eventActorSummary;/** Capture calibration state from the run for persistence on the response message.* Runs in finally so values are captured even on abort. */const ratio = this.run?.getCalibrationRatio() ?? 0;@@ -4305,6 +4640,8 @@ class AgentClient extends BaseClient {// before resume finalize/re-pause persistence reads `this.contentParts`, so a// resumed sequential chain doesn't persist/emit outputs hide_sequential_outputs// is meant to hide.+ this.eventActorSummary =+ getLatestEventActorSummary(this.contentParts) ?? this.eventActorSummary;const contentBeforeReshape = [...this.contentParts];this.applyHideSequentialOutputsFilter();this.rebaseActivityPhaseBounds(contentBeforeReshape);@@ -4343,6 +4680,8 @@ class AgentClient extends BaseClient {});}} finally {+ this.eventActorSummary =+ getLatestEventActorSummary(this.contentParts) ?? this.eventActorSummary;const ratio = this.run?.getCalibrationRatio() ?? 0;if (ratio > 0 && ratio !== 1) {this.contextMeta = {diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.jsindex 4cc105219b..e2b920a06b 100644--- a/api/server/controllers/agents/client.test.js+++ b/api/server/controllers/agents/client.test.js@@ -56,6 +56,13 @@ jest.mock('@librechat/api', () => ({countFormattedMessageTokens: jest.fn(() => 42),countTokens: jest.fn((text) => Math.ceil(String(text ?? '').length / 4)),createCachedTokenCounter: jest.fn(async () => jest.fn(() => 0)),+ createInitializedAgentContextFingerprint: jest.fn(() => ({+ algorithm: 'sha256',+ version: 1,+ digest: 'context',+ })),+ createSkillContentDigest: jest.fn((body) => `digest:${body}`),+ MAX_AGENT_CONTEXT_SKILLS: 64,createDetachedSubagentUsageRecorder: (...args) =>mockCreateDetachedSubagentUsageRecorder(...args),captureAgentCheckpointGeneration: (...args) => mockCaptureAgentCheckpointGeneration(...args),@@ -77,6 +84,271 @@ jest.mock('@librechat/api', () => ({hasDurableAgentInterruptCheckpoint: (...args) => mockHasDurableAgentInterruptCheckpoint(...args),}));+describe('AgentClient - event actor history adapter', () => {+ const fingerprint = { algorithm: 'sha256', version: 1, digest: 'context' };++ it('loads no durable history after compatibility selected a warm continuation', async () => {+ const loadHistory = jest.spyOn(BaseClient.prototype, 'loadHistory');+ const client = Object.create(AgentClient.prototype);+ client.eventActorContinuation = 'warm';++ await expect(client.loadHistory('conversation-1', 'message-1')).resolves.toEqual([]);+ expect(loadHistory).not.toHaveBeenCalled();+ loadHistory.mockRestore();+ });++ it('delegates rebuilt continuation to the existing durable history loader', async () => {+ const loadHistory = jest+ .spyOn(BaseClient.prototype, 'loadHistory')+ .mockResolvedValue([{ messageId: 'message-1' }]);+ const client = Object.create(AgentClient.prototype);+ client.eventActorContinuation = 'cold';++ await expect(client.loadHistory('conversation-1', 'message-1')).resolves.toEqual([+ { messageId: 'message-1' },+ ]);+ expect(loadHistory).toHaveBeenCalledWith('conversation-1', 'message-1');+ loadHistory.mockRestore();+ });++ it('resolves and caches the exact durable Skill manifest before warming', async () => {+ const skillManifest = [{ id: 'skill-1', name: 'analysis', version: 3 }];+ const skillPrimeResult = {+ skillManifest,+ skills: new Map([['analysis', 'Analyze carefully.']]),+ };+ const primeInvokedSkills = jest.fn().mockResolvedValue(skillPrimeResult);+ const client = Object.create(AgentClient.prototype);+ client.options = {+ req: { config: {} },+ primeInvokedSkills,+ };+ client.getEventActorContext = jest.fn().mockResolvedValue({+ fingerprint,+ skillManifest,+ discoveredToolNames: ['deferred_tool'],+ summary: { text: 'Earlier compacted context.', tokenCount: 12 },+ contextMeta: { calibrationRatio: 1.25, encoding: 'o200k_base' },+ });++ await expect(+ client.prepareEventActorContext({+ contextFingerprint: fingerprint,+ skillManifest,+ discoveredToolNames: ['deferred_tool'],+ summary: { text: 'Earlier compacted context.', tokenCount: 12 },+ contextMeta: { calibrationRatio: 1.25, encoding: 'o200k_base' },+ }),+ ).resolves.toMatchObject({+ fingerprint,+ skillManifest,+ discoveredToolNames: ['deferred_tool'],+ summary: { text: 'Earlier compacted context.', tokenCount: 12 },+ contextMeta: { calibrationRatio: 1.25, encoding: 'o200k_base' },+ checkpointMessageOverlay: {+ source: 'skill',+ messages: [+ expect.objectContaining({+ content: 'Analyze carefully.',+ additional_kwargs: expect.objectContaining({+ source: 'skill',+ skillName: 'analysis',+ }),+ }),+ ],+ },+ });+ expect(primeInvokedSkills).toHaveBeenCalledWith([], ['analysis']);+ expect(client.getEventActorContext).toHaveBeenCalledWith(skillManifest, ['deferred_tool']);+ expect(client.eventActorSkillPrimeResult).toEqual(skillPrimeResult);+ expect(client.eventActorDiscoveredToolNames).toEqual(['deferred_tool']);+ expect(client.eventActorSummary).toEqual({+ text: 'Earlier compacted context.',+ tokenCount: 12,+ });+ expect(client.contextMeta).toEqual({ calibrationRatio: 1.25, encoding: 'o200k_base' });+ });++ it('falls back when a durable Skill resolves to a different revision', async () => {+ const client = Object.create(AgentClient.prototype);+ client.options = {+ req: { config: {} },+ primeInvokedSkills: jest.fn().mockResolvedValue({+ skillManifest: [{ id: 'skill-1', name: 'analysis', version: 4 }],+ }),+ };+ client.getEventActorContext = jest.fn();++ await expect(+ client.prepareEventActorContext({+ contextFingerprint: fingerprint,+ skillManifest: [{ id: 'skill-1', name: 'analysis', version: 3 }],+ }),+ ).resolves.toBeUndefined();+ expect(client.getEventActorContext).not.toHaveBeenCalled();+ });++ it('carries a freshly manual-primed Skill into the durable manifest', async () => {+ const client = Object.create(AgentClient.prototype);+ client.options = { req: { config: { endpoints: { agents: {} } } } };+ client.eventActorAgentContextSources = [+ {+ id: 'agent-1',+ manualSkillPrimes: [+ { _id: 'skill-1', name: 'analysis', version: 3, body: 'Analyze carefully.' },+ ],+ },+ ];+ client.getEventActorAgents = jest.fn(() => []);+ client.getEventActorMemorySnapshots = jest.fn().mockResolvedValue([]);++ await expect(client.getEventActorContext()).resolves.toMatchObject({+ skillManifest: [+ {+ id: 'skill-1',+ name: 'analysis',+ version: 3,+ contentDigest: 'digest:Analyze carefully.',+ },+ ],+ });+ });++ it('replays only root Skill primes into the global checkpoint overlay', async () => {+ const client = Object.create(AgentClient.prototype);+ client.options = { req: { config: {} } };+ client.eventActorAgentContextSources = [+ {+ id: 'root-agent',+ alwaysApplySkillPrimes: [+ { _id: 'root-skill', name: 'root-skill', version: 1, body: 'Root instructions.' },+ ],+ },+ {+ id: 'child-agent',+ alwaysApplySkillPrimes: [+ { _id: 'child-skill', name: 'child-skill', version: 1, body: 'Child instructions.' },+ ],+ },+ ];+ client.getEventActorContext = jest.fn().mockResolvedValue({ fingerprint });++ const context = await client.prepareEventActorContext({ contextFingerprint: fingerprint });++ expect(context.checkpointMessageOverlay.messages).toEqual([+ expect.objectContaining({+ content: 'Root instructions.',+ additional_kwargs: expect.objectContaining({ skillName: 'root-skill' }),+ }),+ ]);+ expect(context.checkpointMessageOverlay.messages).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ additional_kwargs: expect.objectContaining({ skillName: 'child-skill' }),+ }),+ ]),+ );+ });++ it('keeps child manual Skills out of the root durable manifest', async () => {+ const client = Object.create(AgentClient.prototype);+ client.options = { req: { config: { endpoints: { agents: {} } } } };+ client.eventActorAgentContextSources = [+ { id: 'root-agent', manualSkillPrimes: [] },+ {+ id: 'child-agent',+ manualSkillPrimes: [+ { _id: 'child-skill', name: 'child-skill', version: 1, body: 'Child instructions.' },+ ],+ },+ ];+ client.getEventActorAgents = jest.fn(() => []);+ client.getEventActorMemorySnapshots = jest.fn().mockResolvedValue([]);++ await expect(client.getEventActorContext()).resolves.toMatchObject({ skillManifest: [] });+ });++ it('captures the latest run summary and pruning calibration in continuation state', async () => {+ const client = Object.create(AgentClient.prototype);+ client.options = { req: { config: { endpoints: { agents: {} } } } };+ client.eventActorAgentContextSources = [];+ client.contentParts = [+ {+ type: ContentTypes.SUMMARY,+ content: [{ type: ContentTypes.TEXT, text: 'Fresh compacted context.' }],+ tokenCount: 18,+ },+ ];+ client.contextMeta = { calibrationRatio: 1.3, encoding: 'o200k_base' };+ client.getEventActorAgents = jest.fn(() => []);+ client.getEventActorMemorySnapshots = jest.fn().mockResolvedValue([]);++ await expect(client.getEventActorContext()).resolves.toMatchObject({+ summary: { text: 'Fresh compacted context.', tokenCount: 18 },+ contextMeta: { calibrationRatio: 1.3, encoding: 'o200k_base' },+ });+ });++ it('fingerprints agents reachable only through nested subagent graphs', () => {+ const graphMember = { id: 'graph-member' };+ const graphMetadata = { id: 'graph-metadata', configId: 'graph-metadata-v2' };+ const lazy = {+ id: 'lazy',+ configId: 'lazy-config-v2',+ subagentGraphMemberMetadata: [graphMetadata],+ };+ const nested = {+ id: 'nested',+ lazySubagentConfigs: [lazy],+ subagentGraphConfigs: [{ memberConfigs: [graphMember] }],+ };+ const client = Object.create(AgentClient.prototype);+ client.options = { agent: { id: 'primary', subagentAgentConfigs: [nested] } };+ client.agentConfigs = new Map([['parallel', { id: 'parallel' }]]);++ expect(client.getEventActorAgents().map((agent) => agent.id)).toEqual([+ 'primary',+ 'parallel',+ 'nested',+ 'lazy',+ 'graph-member',+ 'graph-metadata',+ ]);+ });++ it('snapshots only memory partitions that can reach model context', async () => {+ const getFormattedMemories = require('~/models').getFormattedMemories;+ getFormattedMemories.mockClear();+ getFormattedMemories.mockResolvedValue({ withKeys: 'private memory' });+ const primary = { id: 'primary' };+ const inertChild = {+ id: 'inert-child',+ memory_scope: 'agent',+ memoryToolsRegistered: false,+ };+ const memoryChild = {+ id: 'memory-child',+ memory_scope: 'agent',+ memoryToolsRegistered: true,+ };+ const client = Object.create(AgentClient.prototype);+ client.options = { agent: primary, req: { user: { id: 'user-1' } } };+ client.getSharedMemoryContext = jest.fn().mockResolvedValue({ withoutKeys: 'shared memory' });++ await expect(+ client.getEventActorMemorySnapshots([primary, inertChild, memoryChild]),+ ).resolves.toEqual([+ { scope: 'memory-child', withKeys: 'private memory' },+ { scope: 'shared', withoutKeys: 'shared memory' },+ ]);+ expect(getFormattedMemories).toHaveBeenCalledTimes(1);+ expect(getFormattedMemories).toHaveBeenCalledWith({+ userId: 'user-1',+ agentId: 'memory-child',+ });+ });+});+describe('AgentClient - final model-bound content protection', () => {const filters = {messages: {@@ -1434,16 +1706,26 @@ describe('AgentClient - startup telemetry', () => {mockFormatAgentMessages.mockReturnValueOnce({messages: [history, currentEvent],indexTokenCountMap: { 0: 11, 1: 22 },- summary: { text: 'summary of earlier turns', tokenCount: 40 },+ summary: undefined,boundaryTokenAdjustment: undefined,});- const processStream = jest.fn().mockResolvedValue();+ let client;+ const processStream = jest.fn(async () => {+ client.contentParts.push(+ {+ type: ContentTypes.SUMMARY,+ content: [{ type: ContentTypes.TEXT, text: 'Fresh compacted context.' }],+ tokenCount: 18,+ },+ { type: ContentTypes.TEXT, text: 'Done.' },+ );+ });mockCreateRun.mockResolvedValue({Graph: null,processStream,getCalibrationRatio: jest.fn(() => 0),});- const client = new AgentClient({+ client = new AgentClient({req: {user: { id: 'user-123' },body: {},@@ -1456,7 +1738,7 @@ describe('AgentClient - startup telemetry', () => {endpoint: EModelEndpoint.openAI,provider: EModelEndpoint.openAI,model_parameters: { model: 'gpt-4' },- hide_sequential_outputs: false,+ hide_sequential_outputs: true,},endpointTokenConfig: {},eventHandlers: {},@@ -1471,6 +1753,9 @@ describe('AgentClient - startup telemetry', () => {client.eventActorCheckpointId = 'checkpoint-base';client.eventActorInvocationId = 'event-2';client.eventActorContinuation = 'warm';+ client.eventActorDiscoveredToolNames = ['deferred_tool'];+ client.eventActorSummary = { text: 'summary of earlier turns', tokenCount: 40 };+ client.contextMeta = { calibrationRatio: 1.25, encoding: client.getEncoding() };client.recordCollectedUsage = jest.fn().mockResolvedValue();await client.chatCompletion({ payload: [] });@@ -1478,6 +1763,7 @@ describe('AgentClient - startup telemetry', () => {expect(mockCreateRun).toHaveBeenCalledWith(expect.objectContaining({messages: [history, currentEvent],+ discoveredToolNames: ['deferred_tool'],eventActorCheckpointing: true,/** The DB-derived token map is positional over full history, which a* checkpoint-restored graph state no longer matches. It must be blank@@ -1486,6 +1772,7 @@ describe('AgentClient - startup telemetry', () => {* excluded from the history the committed checkpoint was built from. */indexTokenCountMap: {},initialSummary: { text: 'summary of earlier turns', tokenCount: 40 },+ calibrationRatio: 1.25,}),);expect(processStream).toHaveBeenCalledWith(@@ -1503,6 +1790,13 @@ describe('AgentClient - startup telemetry', () => {expect.anything(),);expect(mockDeleteAgentCheckpoint).not.toHaveBeenCalled();+ expect(client.eventActorSummary).toEqual({+ text: 'Fresh compacted context.',+ tokenCount: 18,+ });+ expect(client.contentParts).not.toEqual(+ expect.arrayContaining([expect.objectContaining({ type: ContentTypes.SUMMARY })]),+ );});it('does not expose or process a fresh graph when strict checkpoint pruning fails', async () => {diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.jsindex 2cf4807189..06a2c446a7 100644--- a/api/server/controllers/agents/request.js+++ b/api/server/controllers/agents/request.js@@ -1690,10 +1690,6 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTitconst eventActorMayPause =isHITLEnabled(agentsConfig?.toolApproval) ||eventActorAgents.some(agentRequestsAskUserQuestion);- const eventActorHasSkillPrimes =- client?.options?.primeInvokedSkills != null ||- (client?.options?.agent?.alwaysApplySkillPrimes?.length ?? 0) > 0 ||- (client?.options?.agent?.manualSkillPrimes?.length ?? 0) > 0;const expectedActionToolName = agentEventDelivery?.expectedAction?.toolName;const eventActorActionMayDetach =typeof expectedActionToolName === 'string' &&@@ -1730,8 +1726,6 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit: undefined,canPause: eventActorMayPause,checkpointerType: agentsConfig?.checkpointer?.type,- hasSkillPrimes: eventActorHasSkillPrimes,- hasMemoryContext: req.config?.memory != null && req.config.memory.disabled !== true,expectedActionMayDetach: eventActorActionMayDetach,});@@ -2077,6 +2071,8 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTitexpectedAction: turnExecutionPlan.expectedAction,signal: job.abortController.signal,checkpointer: req.config?.endpoints?.[EModelEndpoint.agents]?.checkpointer,+ resolveContext: (state) => client.prepareEventActorContext(state),+ readResultContext: () => client.getEventActorContext(),invoke: async (actorContext) => {client.checkpointNamespace = actorContext.checkpointNamespace;client.eventActorCheckpointId = actorContext.checkpointId;diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex a6ef6bb581..41f18cabc3 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -14,6 +14,7 @@ const {discoverConnectedAgents,resolveAgentTokenConfig,resolveAgentScopedSkillIds,+ resolveAlwaysApplySkills,resolveModelSpecSkillIds,getAgentStartupTelemetry,isContentFilterError,@@ -345,6 +346,7 @@ const initializeClient = async ({/** @type {Map<string, import('@librechat/api').EndpointTokenConfig | undefined>} */const endpointTokenConfigByAgentId = new Map();+ const invokedSkillIdentities = new Map();const toolExecuteOptions = {loadTools: async (toolNames, agentId, _configurable, callerCapabilityProjection) => {const ctx = agentToolContexts.get(agentId) ?? {};@@ -392,6 +394,11 @@ const initializeClient = async ({}),emitAttachment: createAttachmentEmitter({ res, streamId, jobCreatedAt }),emitPtcProgress: createPtcProgressEmitter({ res, streamId, jobCreatedAt }),+ onSkillResolved: (skill, { agentId }) => {+ if (agentId === primaryConfig.id) {+ invokedSkillIdentities.set(skill.id, skill);+ }+ },...getSkillToolDeps(),};@@ -726,6 +733,12 @@ const initializeClient = async ({const skippedAgentIds = new Set(discoveredSkippedIds ?? []);const lazyMetadataByAgentId = new Map();+ const eventActorContextRequested =+ req._isAgentTrigger === true && req._agentEventBindingParentConversationId != null;+ /** Request-scoped cache: lazy descriptors sharing the same Skill ACL scope+ * reuse one metadata-only always-apply lookup without initializing tools,+ * files, model clients, or MCP connections. */+ const lazyAlwaysApplySkillsByScope = new Map();const subagentGraphIds = new Set();const expandedSubagentDescriptorState = { configCount: 0, rootAgentIds: [] };@@ -836,7 +849,38 @@ const initializeClient = async ({),);- const toLazySubagentMetadata = (agent) => {+ const resolveLazyAlwaysApplySkillPrimes = (agent) => {+ if (!eventActorContextRequested) {+ return Promise.resolve([]);+ }+ const scopedSkillIds = resolveAgentScopedSkillIds({+ agent,+ accessibleSkillIds,+ skillsCapabilityEnabled,+ ephemeralSkillsToggle,+ });+ if (scopedSkillIds.length === 0 || typeof skillDbMethods.listAlwaysApplySkills !== 'function') {+ return Promise.resolve([]);+ }+ const scopeKey = scopedSkillIds+ .map((skillId) => skillId.toString())+ .sort()+ .join(':');+ let resolution = lazyAlwaysApplySkillsByScope.get(scopeKey);+ if (resolution == null) {+ resolution = resolveAlwaysApplySkills({+ listAlwaysApplySkills: skillDbMethods.listAlwaysApplySkills,+ accessibleSkillIds: scopedSkillIds,+ userId,+ skillStates,+ defaultActiveOnShare,+ });+ lazyAlwaysApplySkillsByScope.set(scopeKey, resolution);+ }+ return resolution;+ };++ const toLazySubagentMetadata = async (agent) => {const statefulCodeSessions =statefulSessionsAvailable === true &&codeEnvAvailable === true &&@@ -857,6 +901,9 @@ const initializeClient = async ({model: agent.model,model_parameters: { model: agent.model_parameters?.model },recursion_limit: agent.recursion_limit,+ memory_scope: agent.memory_scope,+ memoryToolsRegistered:+ memoryAvailable === true && agent.tools?.includes(Tools.memory) === true,subagents: agent.subagents,configId: getLazySubagentConfigId(agent),codeEnvAvailable:@@ -864,6 +911,7 @@ const initializeClient = async ({statefulCodeSessions,statefulCodeEnvironment,includeReasoningHistory: getIncludeReasoningHistory(agent),+ alwaysApplySkillPrimes: await resolveLazyAlwaysApplySkillPrimes(agent),};};@@ -877,7 +925,7 @@ const initializeClient = async ({skippedAgentIds.add(agentId);return null;}- const metadata = toLazySubagentMetadata(agent);+ const metadata = await toLazySubagentMetadata(agent);lazyMetadataByAgentId.set(agentId, metadata);return metadata;} catch (error) {@@ -1087,12 +1135,15 @@ const initializeClient = async ({model: metadata.model,model_parameters: metadata.model_parameters,recursion_limit: metadata.recursion_limit,+ memory_scope: metadata.memory_scope,+ memoryToolsRegistered: metadata.memoryToolsRegistered,subagents: metadata.subagents,configId: metadata.configId,codeEnvAvailable: metadata.codeEnvAvailable,statefulCodeSessions: metadata.statefulCodeSessions,statefulCodeEnvironment: metadata.statefulCodeEnvironment,includeReasoningHistory: metadata.includeReasoningHistory,+ alwaysApplySkillPrimes: metadata.alwaysApplySkillPrimes,lazySubagentConfigs: lazyChildren,subagentAgentConfigs: eagerChildren,subagentGraphMemberMetadata,@@ -1355,10 +1406,11 @@ const initializeClient = async ({},);const handlePrimeInvokedSkills = skillsCapabilityEnabled- ? (payload) =>+ ? (payload, skillNames) =>primeInvokedSkillsForProfiles({req,payload,+ skillNames,accessibleSkillIds,executionProfiles: codeExecutionProfiles,...getSkillToolDeps(),@@ -1438,6 +1490,7 @@ const initializeClient = async ({aggregateContent,artifactPromises,primeInvokedSkills: handlePrimeInvokedSkills,+ invokedSkillIdentities,agent: primaryConfig,spec: endpointOption.spec,iconURL: endpointOption.iconURL,diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex 391c138421..48fc331389 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -816,6 +816,33 @@ describe('initializeClient — subagent loading', () => {);});+ it('retains only root-attributed model-invoked Skills for durable replay', async () => {+ mockInitializeAgent.mockResolvedValue(makePrimaryConfig({}));+ await initializeClient({+ req: makeSubagentReq(),+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });+ const rootSkill = {+ id: 'root-skill',+ name: 'root-skill',+ version: 1,+ contentDigest: 'root-digest',+ };+ const childSkill = {+ id: 'child-skill',+ name: 'child-skill',+ version: 1,+ contentDigest: 'child-digest',+ };++ capturedToolExecuteOptions.onSkillResolved(childSkill, { agentId: SUBAGENT_ID });+ capturedToolExecuteOptions.onSkillResolved(rootSkill, { agentId: PRIMARY_ID });++ expect([...agentClientArgs.invokedSkillIdentities.values()]).toEqual([rootSkill]);+ });+it('keeps an existing detached task controllable after subagent config is disabled', async () => {mockInitializeAgent.mockResolvedValue(makePrimaryConfig({@@ -986,6 +1013,7 @@ describe('initializeClient — subagent loading', () => {author: new mongoose.Types.ObjectId(),tools: ['web'],stateful_code_environment: 'agent-user',+ memory_scope: 'agent',});await grantView(subAgent);@@ -1019,6 +1047,8 @@ describe('initializeClient — subagent loading', () => {id: SUBAGENT_ID,configId: expect.any(String),statefulCodeEnvironment: 'agent-user',+ memory_scope: 'agent',+ memoryToolsRegistered: false,}),);expect(agentClientArgs.agent.lazySubagentConfigs[0]).not.toHaveProperty('tools');@@ -1041,6 +1071,103 @@ describe('initializeClient — subagent loading', () => {expect(agentClientArgs.agentConfigs.has(SUBAGENT_ID)).toBe(false);});+ it('includes current always-apply Skill revisions in lazy descriptor metadata', async () => {+ const secondSubagentId = 'agent_subagent_skill_2';+ const { skill } = await createSkill({+ name: 'lazy-specialist',+ description: 'Prime a lazy specialist.',+ body: '# Lazy specialist v1\n',+ alwaysApply: true,+ author: testUser._id,+ authorName: testUser.name,+ });+ await AclEntry.create({+ principalType: PrincipalType.USER,+ principalId: testUser._id,+ principalModel: PrincipalModel.USER,+ resourceType: ResourceType.SKILL,+ resourceId: skill._id,+ permBits: PermissionBits.VIEW,+ grantedBy: testUser._id,+ });+ const subAgent = await createAgent({+ id: SUBAGENT_ID,+ name: 'Skill Subagent',+ provider: 'openai',+ model: 'gpt-4',+ author: testUser._id,+ tools: [],+ skills_enabled: true,+ skills: [skill._id.toString()],+ });+ await grantView(subAgent);+ const secondSubAgent = await createAgent({+ id: secondSubagentId,+ name: 'Second Skill Subagent',+ provider: 'openai',+ model: 'gpt-4',+ author: testUser._id,+ tools: [],+ skills_enabled: true,+ skills: [skill._id.toString()],+ });+ await grantView(secondSubAgent);+ mockInitializeAgent.mockResolvedValue(+ makePrimaryConfig({+ subagents: {+ enabled: true,+ allowSelf: true,+ agent_ids: [SUBAGENT_ID, secondSubagentId],+ },+ }),+ );+ const req = makeSubagentReq();+ req.config.endpoints.agents.capabilities.push('skills');+ const listAlwaysApplySkillsSpy = jest.spyOn(getSkillDbMethods(), 'listAlwaysApplySkills');++ try {+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });++ expect(mockInitializeAgent).toHaveBeenCalledTimes(1);+ expect(listAlwaysApplySkillsSpy).not.toHaveBeenCalled();+ for (const descriptor of agentClientArgs.agent.lazySubagentConfigs) {+ expect(descriptor.alwaysApplySkillPrimes).toEqual([]);+ }++ const eventReq = makeSubagentReq();+ eventReq.config.endpoints.agents.capabilities.push('skills');+ eventReq._isAgentTrigger = true;+ eventReq._agentEventBindingParentConversationId = 'parent-conversation';+ await initializeClient({+ req: eventReq,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });++ expect(mockInitializeAgent).toHaveBeenCalledTimes(2);+ expect(listAlwaysApplySkillsSpy).toHaveBeenCalledTimes(1);+ expect(agentClientArgs.agent.lazySubagentConfigs).toHaveLength(2);+ for (const descriptor of agentClientArgs.agent.lazySubagentConfigs) {+ expect(descriptor.alwaysApplySkillPrimes).toEqual([+ expect.objectContaining({+ _id: skill._id,+ name: 'lazy-specialist',+ version: 1,+ body: '# Lazy specialist v1\n',+ }),+ ]);+ }+ } finally {+ listAlwaysApplySkillsSpy.mockRestore();+ }+ });+it('rejects a disallowed lazy subagent scope before exposing it for prewarm', async () => {const subAgent = await createAgent({id: SUBAGENT_ID,diff --git a/packages/api/src/agents/checkpointer.integration.spec.ts b/packages/api/src/agents/checkpointer.integration.spec.tsindex c7ea1fecd4..a992822485 100644--- a/packages/api/src/agents/checkpointer.integration.spec.ts+++ b/packages/api/src/agents/checkpointer.integration.spec.ts@@ -1,6 +1,7 @@import mongoose from 'mongoose';import { logger } from '@librechat/data-schemas';import { MongoMemoryServer } from 'mongodb-memory-server';+import { HumanMessage } from '@librechat/agents/langchain/messages';import { MongoDBSaver } from '@langchain/langgraph-checkpoint-mongodb';import { emptyCheckpoint, ERROR, INTERRUPT } from '@langchain/langgraph-checkpoint';import {@@ -216,6 +217,70 @@ describe('checkpointer (mongodb-memory-server integration)', () => {).toBe(2);});+ it('replaces checkpoint-carried Skill context while preserving the committed base', async () => {+ const saver = await getAgentCheckpointer(MONGO_CFG);+ const threadId = `actor-${new mongoose.Types.ObjectId().toString()}`;+ const checkpoint = emptyCheckpoint();+ checkpoint.channel_values.messages = [+ new HumanMessage({ content: 'ordinary history' }),+ new HumanMessage({+ content: 'old skill body',+ additional_kwargs: { isMeta: true, source: 'skill', skillName: 'analysis' },+ }),+ ];+ checkpoint.channel_versions.messages = 1;+ const sourceConfig = {+ configurable: {+ thread_id: threadId,+ checkpoint_ns: '',+ [LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: 'event-actor/base',+ [LIBRECHAT_EVENT_ACTOR_INVOCATION_KEY]: 'event-1',+ },+ };+ await saver!.put(sourceConfig, checkpoint, {+ source: 'input',+ step: -1,+ parents: {},+ });++ await forkAgentEventCheckpoint(+ { threadId, checkpointId: checkpoint.id, checkpointNs: 'event-actor/base' },+ 'event-actor/fork',+ 'event-2',+ MONGO_CFG,+ {+ source: 'skill',+ messages: [+ new HumanMessage({+ content: 'current skill body',+ additional_kwargs: { isMeta: true, source: 'skill', skillName: 'analysis' },+ }),+ ],+ },+ );++ const source = await saver!.getTuple(sourceConfig);+ const fork = await saver!.getTuple({+ configurable: {+ thread_id: threadId,+ checkpoint_ns: '',+ checkpoint_id: checkpoint.id,+ [LIBRECHAT_CHECKPOINT_NAMESPACE_KEY]: 'event-actor/fork',+ [LIBRECHAT_EVENT_ACTOR_INVOCATION_KEY]: 'event-2',+ },+ });+ expect(+ (source?.checkpoint.channel_values.messages as HumanMessage[]).map(+ (message) => message.content,+ ),+ ).toEqual(['ordinary history', 'old skill body']);+ expect(+ (fork?.checkpoint.channel_values.messages as HumanMessage[]).map(+ (message) => message.content,+ ),+ ).toEqual(['ordinary history', 'current skill body']);+ });+it('warm-continues from a copied actor head without mutating the committed base', async () => {const { StateGraph, START, END, Annotation } = await import('@langchain/langgraph');const saver = await getAgentCheckpointer(MONGO_CFG);diff --git a/packages/api/src/agents/checkpointer.ts b/packages/api/src/agents/checkpointer.tsindex 277056a64e..63005be922 100644--- a/packages/api/src/agents/checkpointer.ts+++ b/packages/api/src/agents/checkpointer.ts@@ -9,6 +9,7 @@ import type {CheckpointTuple,PendingWrite,} from '@langchain/langgraph-checkpoint';+import type { BaseMessage } from '@librechat/agents/langchain/messages';import type { TCheckpointerConfig } from 'librechat-data-provider';import type { RunnableConfig } from '@langchain/core/runnables';@@ -696,6 +697,47 @@ export interface AgentEventCheckpointReference {checkpointNs: string;}+export interface AgentEventCheckpointMessageOverlay {+ source: string;+ messages: readonly BaseMessage[];+}++function applyAgentEventCheckpointMessageOverlay(+ checkpoint: Checkpoint,+ overlay: AgentEventCheckpointMessageOverlay | undefined,+): Checkpoint {+ if (overlay == null) {+ return checkpoint;+ }+ const channelValues = checkpoint.channel_values;+ const messages = Array.isArray(channelValues.messages) ? channelValues.messages : [];+ const retainedMessages = messages.filter((message) => {+ if (message == null || typeof message !== 'object') {+ return true;+ }+ const kwargs = (message as { additional_kwargs?: { source?: unknown } }).additional_kwargs;+ return kwargs?.source !== overlay.source;+ });+ const agentMessages = channelValues.agentMessages;+ const retainedAgentMessages = Array.isArray(agentMessages)+ ? agentMessages.filter((message) => {+ if (message == null || typeof message !== 'object') {+ return true;+ }+ const kwargs = (message as { additional_kwargs?: { source?: unknown } }).additional_kwargs;+ return kwargs?.source !== overlay.source;+ })+ : agentMessages;+ return {+ ...checkpoint,+ channel_values: {+ ...channelValues,+ messages: [...retainedMessages, ...overlay.messages],+ ...(retainedAgentMessages === undefined ? {} : { agentMessages: retainedAgentMessages }),+ },+ };+}+function eventActorRunnableConfig(reference: Pick<AgentEventCheckpointReference, 'threadId' | 'checkpointNs'>,invocationId: string,@@ -718,6 +760,7 @@ export async function forkAgentEventCheckpoint(checkpointNs: string,invocationId: string,cfg?: TCheckpointerConfig,+ messageOverlay?: AgentEventCheckpointMessageOverlay,): Promise<AgentEventCheckpointReference | null> {const saver = await getAgentCheckpointer(cfg);if (!saver || checkpointNs.length === 0 || invocationId.length === 0) {@@ -732,7 +775,7 @@ export async function forkAgentEventCheckpoint(const target = { threadId: source.threadId, checkpointNs };const persisted = await saver.put(eventActorRunnableConfig(target, invocationId),- tuple.checkpoint,+ applyAgentEventCheckpointMessageOverlay(tuple.checkpoint, messageOverlay),tuple.metadata,);const checkpointId = persisted.configurable?.checkpoint_id;diff --git a/packages/api/src/agents/compatibility.spec.ts b/packages/api/src/agents/compatibility.spec.tsnew file mode 100644index 0000000000..0eafc633a2--- /dev/null+++ b/packages/api/src/agents/compatibility.spec.ts@@ -0,0 +1,205 @@+import {+ agentContextFingerprintsMatch,+ createAgentContextFingerprint,+ createInitializedAgentContextFingerprint,+ normalizeAgentEventActorDiscoveredTools,+ type AgentTurnSemanticContext,+} from './compatibility';++const context = (): AgentTurnSemanticContext => ({+ checkpointerType: 'mongodb',+ approvalPolicy: { enabled: false },+ agents: [+ {+ id: 'agent-1',+ version: 3,+ provider: 'openai',+ model: 'gpt-5',+ instructions: 'Help carefully.',+ modelParameters: { temperature: 0.2 },+ toolDefinitions: [{ name: 'search', schema: { type: 'object' } }],+ execution: { edges: [{ from: 'agent-1', to: 'agent-2' }], recursionLimit: 25 },+ skills: [+ { id: 'skill-b', name: 'beta', version: 2 },+ { id: 'skill-a', name: 'alpha', version: 1 },+ ],+ },+ ],+ memory: [{ scope: 'shared', withoutKeys: 'Prefers concise answers.' }],+});++describe('agent context compatibility', () => {+ it('is deterministic across object-key and set-like Skill ordering', () => {+ const left = context();+ const right = context();+ right.approvalPolicy = { enabled: false };+ right.agents[0].modelParameters = { temperature: 0.2 };+ right.agents[0].skills = [...(right.agents[0].skills ?? [])].reverse();++ expect(createAgentContextFingerprint(left)).toEqual(createAgentContextFingerprint(right));+ });++ it.each([+ ['agent revision', (value: AgentTurnSemanticContext) => (value.agents[0].version = 4)],+ ['instructions', (value: AgentTurnSemanticContext) => (value.agents[0].instructions = 'New')],+ ['model', (value: AgentTurnSemanticContext) => (value.agents[0].model = 'gpt-6')],+ [+ 'tool definition',+ (value: AgentTurnSemanticContext) =>+ (value.agents[0].toolDefinitions = [{ name: 'submit', schema: { type: 'object' } }]),+ ],+ [+ 'graph topology',+ (value: AgentTurnSemanticContext) =>+ (value.agents[0].execution = {+ edges: [{ from: 'agent-1', to: 'agent-3' }],+ recursionLimit: 25,+ }),+ ],+ [+ 'Skill version',+ (value: AgentTurnSemanticContext) =>+ (value.agents[0].skills = [{ id: 'skill-a', name: 'alpha', version: 2 }]),+ ],+ [+ 'memory snapshot',+ (value: AgentTurnSemanticContext) =>+ (value.memory = [{ scope: 'shared', withoutKeys: 'Prefers detailed answers.' }]),+ ],+ ])('changes when %s changes', (_label, mutate) => {+ const original = context();+ const changed = context();+ mutate(changed);++ expect(createAgentContextFingerprint(changed).digest).not.toBe(+ createAgentContextFingerprint(original).digest,+ );+ });++ it('excludes credential values from compatibility', () => {+ const left = context();+ const right = context();+ left.agents[0].modelParameters = {+ temperature: 0.2,+ apiKey: 'first',+ headers: { 'x-api-key': 'first-header-secret' },+ };+ right.agents[0].modelParameters = {+ apiKey: 'second',+ temperature: 0.2,+ headers: { 'x-api-key': 'second-header-secret' },+ };++ expect(createAgentContextFingerprint(left)).toEqual(createAgentContextFingerprint(right));+ });++ it('preserves credential-named JSON Schema fields in semantic tool definitions', () => {+ const left = context();+ const right = context();+ left.agents[0].toolDefinitions = [+ {+ name: 'login',+ schema: { type: 'object', properties: { password: { type: 'string' } } },+ },+ ];+ right.agents[0].toolDefinitions = [+ {+ name: 'login',+ schema: { type: 'object', properties: { password: { type: 'number' } } },+ },+ ];++ expect(createAgentContextFingerprint(left).digest).not.toBe(+ createAgentContextFingerprint(right).digest,+ );+ });++ it('fails compatibility closed for a missing or unknown stored version', () => {+ const current = createAgentContextFingerprint(context());++ expect(agentContextFingerprintsMatch(undefined, current)).toBe(false);+ expect(+ agentContextFingerprintsMatch({ ...current, version: current.version + 1 }, current),+ ).toBe(false);+ expect(agentContextFingerprintsMatch(current, current)).toBe(true);+ });++ it('projects initialized Skill identities without duplicate reads', () => {+ const fingerprint = createInitializedAgentContextFingerprint({+ agents: [+ {+ id: 'agent-1',+ manualSkillPrimes: [+ { _id: 'skill-1', name: 'analysis', version: 4 },+ { _id: 'skill-1', name: 'analysis', version: 4 },+ ],+ },+ ],+ });+ const changed = createInitializedAgentContextFingerprint({+ agents: [+ {+ id: 'agent-1',+ manualSkillPrimes: [{ _id: 'skill-1', name: 'analysis', version: 5 }],+ },+ ],+ });++ expect(changed.digest).not.toBe(fingerprint.digest);+ });++ it('invalidates a constant-version deployment Skill when its body changes', () => {+ const fingerprint = (body: string) =>+ createInitializedAgentContextFingerprint({+ agents: [+ {+ id: 'agent-1',+ alwaysApplySkillPrimes: [+ { _id: 'deployment:analysis', name: 'analysis', version: 1, body },+ ],+ },+ ],+ });++ expect(fingerprint('First instructions').digest).not.toBe(+ fingerprint('Updated instructions').digest,+ );+ });++ it('normalizes bounded tool discoveries and fingerprints the active set', () => {+ expect(normalizeAgentEventActorDiscoveredTools(['zeta', 'alpha', 'zeta'])).toEqual([+ 'alpha',+ 'zeta',+ ]);+ const left = context();+ const reordered = context();+ const changed = context();+ left.discoveredToolNames = ['zeta', 'alpha'];+ reordered.discoveredToolNames = ['alpha', 'zeta', 'alpha'];+ changed.discoveredToolNames = ['alpha', 'gamma'];++ expect(createAgentContextFingerprint(left)).toEqual(createAgentContextFingerprint(reordered));+ expect(createAgentContextFingerprint(left).digest).not.toBe(+ createAgentContextFingerprint(changed).digest,+ );+ expect(() =>+ normalizeAgentEventActorDiscoveredTools(+ Array.from({ length: 129 }, (_, index) => `tool-${index}`),+ ),+ ).toThrow('exceeds 128');+ });++ it('invalidates a deferred tool when its registry definition changes', () => {+ const fingerprint = (description: string) =>+ createInitializedAgentContextFingerprint({+ agents: [+ {+ id: 'agent-1',+ toolRegistryDefinitions: [{ name: 'deferred_tool', description, defer_loading: true }],+ },+ ],+ });++ expect(fingerprint('First schema').digest).not.toBe(fingerprint('Updated schema').digest);+ });+});diff --git a/packages/api/src/agents/compatibility.ts b/packages/api/src/agents/compatibility.tsnew file mode 100644index 0000000000..dfdb2154c6--- /dev/null+++ b/packages/api/src/agents/compatibility.ts@@ -0,0 +1,278 @@+import { createHash } from 'node:crypto';+import {+ MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS,+ MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH,+} from '@librechat/data-schemas';++export const AGENT_CONTEXT_FINGERPRINT_VERSION = 1;+export const AGENT_GRAPH_SCHEMA_VERSION = 1;+export const AGENT_CHECKPOINT_FORMAT_VERSION = 1;++export interface AgentContextFingerprint {+ algorithm: 'sha256';+ version: number;+ digest: string;+}++export interface AgentContextSkillIdentity {+ id: string;+ name: string;+ version: number;+ contentDigest?: string;+}++export interface AgentContextMemorySnapshot {+ scope: string;+ withKeys?: string;+ withoutKeys?: string;+}++export interface AgentContextDefinition {+ id: string;+ version?: number | string;+ provider?: string;+ model?: string;+ instructions?: string;+ additionalInstructions?: string;+ modelParameters?: object;+ toolDefinitions?: readonly object[];+ toolRegistryDefinitions?: readonly object[];+ toolOptions?: object;+ execution?: object;+ skills?: readonly AgentContextSkillIdentity[];+}++export interface AgentTurnSemanticContext {+ agents: readonly AgentContextDefinition[];+ approvalPolicy?: object;+ memory?: readonly AgentContextMemorySnapshot[];+ checkpointerType?: string;+ discoveredToolNames?: readonly string[];+ checkpointFormatVersion?: number;+ graphSchemaVersion?: number;+}++export interface InitializedAgentContextSource {+ id: string;+ version?: number | string;+ provider?: string;+ model?: string;+ instructions?: string;+ additional_instructions?: string;+ model_parameters?: object;+ toolDefinitions?: readonly object[];+ toolRegistryDefinitions?: readonly object[];+ tool_options?: object;+ execution?: object;+ manualSkillPrimes?: readonly {+ _id: { toString(): string } | string;+ name: string;+ version?: number;+ body?: string;+ }[];+ alwaysApplySkillPrimes?: readonly {+ _id: { toString(): string } | string;+ name: string;+ version?: number;+ body?: string;+ }[];+}++export const MAX_AGENT_CONTEXT_SKILLS = 64;++export function normalizeAgentEventActorDiscoveredTools(+ names: readonly string[] | undefined,+): string[] {+ if (names == null) {+ return [];+ }+ const normalized = new Set<string>();+ for (const name of names) {+ if (+ typeof name !== 'string' ||+ name.length === 0 ||+ name.length > MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH+ ) {+ throw new RangeError('Event actor discovered-tool state is invalid');+ }+ normalized.add(name);+ }+ if (normalized.size > MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS) {+ throw new RangeError(+ `Event actor discovered-tool state exceeds ${MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS}`,+ );+ }+ return [...normalized].sort((left, right) => left.localeCompare(right));+}++export function createSkillContentDigest(body: string): string {+ return createHash('sha256').update(body).digest('base64url');+}++const CREDENTIAL_KEY_PATTERN =+ /^(?:authorization|password|secret)$|(?:^|[-_])(?:api[-_]?key|access[-_]?token|refresh[-_]?token|client[-_]?secret)$/i;++const REDACTED_CREDENTIAL = '[credential]';++function redactModelParameterCredentials(value: object | undefined): object | undefined {+ if (value == null) {+ return undefined;+ }+ const redacted: Record<string, unknown> = {};+ for (const [key, item] of Object.entries(value)) {+ if (CREDENTIAL_KEY_PATTERN.test(key)) {+ redacted[key] = REDACTED_CREDENTIAL;+ continue;+ }+ if (key.toLowerCase() === 'headers' && item != null && typeof item === 'object') {+ redacted[key] = Object.fromEntries(+ Object.entries(item).map(([header, headerValue]) => [+ header,+ CREDENTIAL_KEY_PATTERN.test(header) ? REDACTED_CREDENTIAL : headerValue,+ ]),+ );+ continue;+ }+ redacted[key] = item;+ }+ return redacted;+}++function canonicalize(value: unknown, seen: WeakSet<object>): unknown {+ if (value == null || typeof value === 'string' || typeof value === 'boolean') {+ return value;+ }+ if (typeof value === 'number') {+ return Number.isFinite(value) ? value : String(value);+ }+ if (Array.isArray(value)) {+ return value.map((item) => canonicalize(item, seen)).filter((item) => item !== undefined);+ }+ if (typeof value !== 'object') {+ return undefined;+ }+ if (seen.has(value)) {+ throw new TypeError('Agent semantic context cannot contain circular references');+ }+ seen.add(value);+ const record = value as Record<string, unknown>;+ const normalized: Record<string, unknown> = {};+ for (const key of Object.keys(record).sort()) {+ const item = canonicalize(record[key], seen);+ if (item !== undefined) {+ normalized[key] = item;+ }+ }+ seen.delete(value);+ return normalized;+}++function sortSkillIdentities(+ skills: readonly AgentContextSkillIdentity[] | undefined,+): AgentContextSkillIdentity[] | undefined {+ if (skills == null) {+ return undefined;+ }+ const unique = new Map<string, AgentContextSkillIdentity>();+ for (const skill of skills) {+ unique.set(skill.id, skill);+ }+ if (unique.size > MAX_AGENT_CONTEXT_SKILLS) {+ throw new RangeError(`Agent context exceeds ${MAX_AGENT_CONTEXT_SKILLS} Skills`);+ }+ return [...unique.values()].sort(+ (left, right) =>+ left.id.localeCompare(right.id) ||+ left.name.localeCompare(right.name) ||+ left.version - right.version,+ );+}++/** Hashes only semantic, model-bound context; request and delivery metadata never enter this module. */+export function createAgentContextFingerprint(+ input: AgentTurnSemanticContext,+): AgentContextFingerprint {+ const semanticContext = {+ version: AGENT_CONTEXT_FINGERPRINT_VERSION,+ graphSchemaVersion: input.graphSchemaVersion ?? AGENT_GRAPH_SCHEMA_VERSION,+ checkpointFormatVersion: input.checkpointFormatVersion ?? AGENT_CHECKPOINT_FORMAT_VERSION,+ checkpointerType: input.checkpointerType,+ discoveredToolNames: normalizeAgentEventActorDiscoveredTools(input.discoveredToolNames),+ approvalPolicy: input.approvalPolicy,+ agents: input.agents.map((agent) => ({+ ...agent,+ modelParameters: redactModelParameterCredentials(agent.modelParameters),+ skills: sortSkillIdentities(agent.skills),+ })),+ memory:+ input.memory == null+ ? undefined+ : [...input.memory].sort((left, right) => left.scope.localeCompare(right.scope)),+ };+ const canonical = JSON.stringify(canonicalize(semanticContext, new WeakSet()));+ return Object.freeze({+ algorithm: 'sha256' as const,+ version: AGENT_CONTEXT_FINGERPRINT_VERSION,+ digest: createHash('sha256').update(canonical).digest('base64url'),+ });+}++export function agentContextFingerprintsMatch(+ stored: AgentContextFingerprint | undefined,+ current: AgentContextFingerprint,+): boolean {+ return (+ stored?.algorithm === current.algorithm &&+ stored.version === current.version &&+ stored.digest === current.digest+ );+}++function skillIdentities(agent: InitializedAgentContextSource): AgentContextSkillIdentity[] {+ const skills = [...(agent.manualSkillPrimes ?? []), ...(agent.alwaysApplySkillPrimes ?? [])];+ const unique = new Map<string, AgentContextSkillIdentity>();+ for (const skill of skills) {+ const id = skill._id.toString();+ unique.set(id, {+ id,+ name: skill.name,+ version: skill.version ?? 0,+ ...(skill.body == null ? {} : { contentDigest: createSkillContentDigest(skill.body) }),+ });+ }+ return [...unique.values()];+}++/** Projects initialized runtime facts into the single semantic compatibility module. */+export function createInitializedAgentContextFingerprint(input: {+ agents: readonly InitializedAgentContextSource[];+ invokedSkills?: readonly AgentContextSkillIdentity[];+ approvalPolicy?: object;+ memory?: readonly AgentContextMemorySnapshot[];+ checkpointerType?: string;+ discoveredToolNames?: readonly string[];+}): AgentContextFingerprint {+ return createAgentContextFingerprint({+ checkpointerType: input.checkpointerType,+ approvalPolicy: input.approvalPolicy,+ memory: input.memory,+ discoveredToolNames: input.discoveredToolNames,+ agents: input.agents.map((agent, index) => ({+ id: agent.id,+ version: agent.version,+ provider: agent.provider,+ model: agent.model,+ instructions: agent.instructions,+ additionalInstructions: agent.additional_instructions,+ modelParameters: agent.model_parameters,+ toolDefinitions: agent.toolDefinitions,+ toolRegistryDefinitions: agent.toolRegistryDefinitions,+ toolOptions: agent.tool_options,+ execution: agent.execution,+ skills:+ index === 0+ ? [...skillIdentities(agent), ...(input.invokedSkills ?? [])]+ : skillIdentities(agent),+ })),+ });+}diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex 247000f1c3..6fdc5124be 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -56,10 +56,12 @@ function invokeHandler(directOnlyToolNames: string[];codeExecutionOnlyToolNames: string[];},+ agentId?: string,): Promise<ToolExecuteResult[]> {return new Promise((resolve, reject) => {const request = {toolCalls,+ agentId,callerCapabilityProjection,resolve,reject,@@ -1427,6 +1429,7 @@ describe('createToolExecuteHandler', () => {function createSkillHandler(getSkillByName: ToolExecuteOptions['getSkillByName'],filters?: Record<string, unknown>,+ onSkillResolved?: ToolExecuteOptions['onSkillResolved'],) {const loadTools: ToolExecuteOptions['loadTools'] = jest.fn(async () => ({loadedTools: [],@@ -1435,7 +1438,7 @@ describe('createToolExecuteHandler', () => {...(filters != null ? { req: { config: { filters } } } : {}),},}));- return createToolExecuteHandler({ loadTools, getSkillByName });+ return createToolExecuteHandler({ loadTools, getSkillByName, onSkillResolved });}/** Skill with one bundled file plus every dep the priming gate requires,@@ -1504,6 +1507,42 @@ describe('createToolExecuteHandler', () => {expect(result.errorMessage).toContain('pii-redactor');});+ it('captures the exact identity of a successfully model-invoked Skill', async () => {+ const onSkillResolved = jest.fn();+ const getSkillByName = jest.fn(async () => ({+ _id: { toString: () => 'skill-id' } as never,+ name: 'analysis',+ body: 'Analyze the position.',+ fileCount: 0,+ version: 4,+ }));+ const handler = createSkillHandler(getSkillByName, undefined, onSkillResolved);++ const [result] = await invokeHandler(+ handler,+ [+ {+ id: 'call_skill_identity',+ name: Constants.SKILL_TOOL,+ args: { skillName: 'analysis' },+ },+ ],+ undefined,+ 'agent-child',+ );++ expect(result.status).toBe('success');+ expect(onSkillResolved).toHaveBeenCalledWith(+ {+ id: 'skill-id',+ name: 'analysis',+ version: 4,+ contentDigest: expect.any(String),+ },+ { agentId: 'agent-child' },+ );+ });+it('blocks stored skill instructions before injecting them into model context', async () => {const protectedValue = 'PRIVATE-SKILL-BODY';const getSkillByName = jest.fn(async () => ({diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex c6d424c1f5..a87f7b2bb1 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -69,6 +69,7 @@ import {import { getSafeErrorMetadata, logAxiosError, runOutsideTracing, truncateMiddle } from '~/utils';import { resolveCallerCapabilityProjectionSnapshot } from './callerCapabilities';import { buildSkillPrimeMessage, SKILL_FILE_PREFIX } from './skills';+import { createSkillContentDigest } from './compatibility';import { parseFrontmatter } from '../skills/import';import { cleanCodeToolOutput } from './cleanup';import { primeSkillFiles } from './skillFiles';@@ -199,6 +200,16 @@ export interface ToolExecuteOptions {*/disableModelInvocation?: boolean;} | null>;+ /** Captures a successfully resolved model-invoked Skill for durable continuation context. */+ onSkillResolved?: (+ skill: {+ id: string;+ name: string;+ version: number;+ contentDigest: string;+ },+ context: { agentId?: string },+ ) => void;/*** Loads a skill by name when the current user is the author. This is a* narrow recovery path for freshly-authored skills whose runtime catalog@@ -3885,6 +3896,7 @@ async function handleSkillToolCall(tc: ToolCallRequest,mergedConfigurable: Record<string, unknown>,options: ToolExecuteOptions,+ agentId?: string,req?: ServerRequest,): Promise<ToolExecuteResult> {const {@@ -4057,6 +4069,16 @@ async function handleSkillToolCall(}}+ options.onSkillResolved?.(+ {+ id: skill._id.toString(),+ name: skill.name,+ version: skill.version,+ contentDigest: createSkillContentDigest(skill.body),+ },+ { agentId },+ );+return {toolCallId: tc.id,content: contentText,@@ -4846,6 +4868,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandtc,mergedConfigurable,options,+ agentId,req,);} else if (tc.name === Constants.READ_FILE) {diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex d7d2d21360..941434b204 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -5,6 +5,7 @@ export * from './callerCapabilities';export * from './client';export * from './config';export * from './checkpointer';+export * from './compatibility';export * from './contact';export * from './context';export * from './control';diff --git a/packages/api/src/agents/plan.spec.ts b/packages/api/src/agents/plan.spec.tsindex 4ad4ef2f67..cab33760a0 100644--- a/packages/api/src/agents/plan.spec.ts+++ b/packages/api/src/agents/plan.spec.ts@@ -6,8 +6,6 @@ const baseInput = (): ResolveAgentTurnExecutionPlanInput => ({parentMessageId: 'message-1',isNewConversation: false,canPause: false,- hasSkillPrimes: false,- hasMemoryContext: false,expectedActionMayDetach: false,});@@ -58,8 +56,6 @@ describe('resolveAgentTurnExecutionPlan', () => {['no expected action', { event: { ...boundEvent(), expectedAction: undefined } }],['memory checkpointer', { event: boundEvent(), checkpointerType: 'memory' }],['pause-capable run', { event: boundEvent(), canPause: true }],- ['Skill primes', { event: boundEvent(), hasSkillPrimes: true }],- ['memory context', { event: boundEvent(), hasMemoryContext: true }],['detachable action', { event: boundEvent(), expectedActionMayDetach: true }],] as const)('falls back to history for %s', (_label, overrides) => {expect(resolveAgentTurnExecutionPlan({ ...baseInput(), ...overrides }).strategy).toBe(diff --git a/packages/api/src/agents/plan.ts b/packages/api/src/agents/plan.tsindex 802e2ea623..61d38733de 100644--- a/packages/api/src/agents/plan.ts+++ b/packages/api/src/agents/plan.ts@@ -35,8 +35,6 @@ export interface ResolveAgentTurnExecutionPlanInput {};canPause: boolean;checkpointerType?: TCheckpointerType;- hasSkillPrimes: boolean;- hasMemoryContext: boolean;expectedActionMayDetach: boolean;}@@ -73,8 +71,6 @@ export function resolveAgentTurnExecutionPlan(expectedAction != null &&input.checkpointerType !== 'memory' &&!input.canPause &&- !input.hasSkillPrimes &&- !input.hasMemoryContext &&!input.expectedActionMayDetach;let strategy: AgentTurnContinuationStrategy = 'history';if (input.isNewConversation) {diff --git a/packages/api/src/agents/skillFiles.spec.ts b/packages/api/src/agents/skillFiles.spec.tsindex c6ed855e13..73e7238252 100644--- a/packages/api/src/agents/skillFiles.spec.ts+++ b/packages/api/src/agents/skillFiles.spec.ts@@ -65,6 +65,23 @@ describe('primeInvokedSkills — execute_code capability gate', () => {expect(deps.batchUploadCodeEnvFiles).not.toHaveBeenCalled();});+ it('resolves explicit actor-head names without scanning message history', async () => {+ mockExtract.mockReturnValue(new Set());+ const deps = makeDeps({ payload: undefined, skillNames: ['brand-guidelines'] });++ const result = await primeInvokedSkills(deps);++ expect(deps.getSkillByName).toHaveBeenCalledWith('brand-guidelines', [SKILL_ID]);+ expect(result.skillManifest).toEqual([+ {+ id: SKILL_ID.toString(),+ name: 'brand-guidelines',+ version: SKILL_VERSION,+ contentDigest: expect.any(String),+ },+ ]);+ });+it('enters the batch-upload path when codeEnvAvailable is true', async () => {const deps = makeDeps({ codeEnvAvailable: true });@@ -614,6 +631,60 @@ describe('primeInvokedSkillsForProfiles', () => {.sort(),).toEqual(['default', 'stateful']);});++ it('keeps a successful profile Skill body and identity after another profile lookup fails', async () => {+ const {+ codeEnvAvailable: _codeEnvAvailable,+ codeExecutionContext: _codeExecutionContext,+ ...baseDeps+ } = makeDeps({+ getSkillByName: jest+ .fn()+ .mockRejectedValueOnce(new Error('transient lookup failure'))+ .mockResolvedValueOnce({+ _id: SKILL_ID,+ name: 'brand-guidelines',+ body: 'skill body',+ version: SKILL_VERSION,+ fileCount: 0,+ }),+ });+ const deps: PrimeInvokedSkillsForProfilesDeps = {+ ...baseDeps,+ executionProfiles: [+ {+ codeExecutionContext: {+ baseUrl: 'https://code.example.com/v1',+ codeSessionKey: 'execute_code',+ executionProfile: 'default',+ statefulSessions: false,+ },+ codeSessionKeys: ['execute_code'],+ },+ {+ codeExecutionContext: {+ baseUrl: 'https://stateful.example.com/v1',+ codeSessionKey: 'execute_code:stateful:v2:user:abc',+ executionProfile: 'stateful',+ statefulSessions: true,+ },+ codeSessionKeys: ['execute_code:stateful:v2:user:abc'],+ },+ ],+ };++ const result = await primeInvokedSkillsForProfiles(deps);++ expect(result.skills).toEqual(new Map([['brand-guidelines', 'skill body']]));+ expect(result.skillManifest).toEqual([+ {+ id: SKILL_ID.toString(),+ name: 'brand-guidelines',+ version: SKILL_VERSION,+ contentDigest: expect.any(String),+ },+ ]);+ });});/* The tool-invoked skill loader (`handle_skill` -> `primeSkillFiles`)diff --git a/packages/api/src/agents/skillFiles.ts b/packages/api/src/agents/skillFiles.tsindex 504f830a66..e4e155794e 100644--- a/packages/api/src/agents/skillFiles.ts+++ b/packages/api/src/agents/skillFiles.ts@@ -24,6 +24,7 @@ import { seedCodeFilesIntoSessions, type CodeExecutionProfileRoute } from './codimport { ContentFilterError, isContentFilterError } from '~/middleware/contentFilter';import { createConcurrencyLimiter, getSafeErrorMetadata } from '~/utils';import { assertSkillFileContentAllowed } from '~/skills/protection';+import { createSkillContentDigest } from './compatibility';import { extractInvokedSkillsFromPayload } from './run';import { SKILL_FILE_PREFIX } from './skills';@@ -604,7 +605,9 @@ async function executePrimeSkillFiles(export interface PrimeInvokedSkillsDeps {req: ServerRequest;/** Raw message payload (before formatAgentMessages). Used to extract invoked skill names. */- payload: Array<Partial<{ role: string; content: unknown }>>;+ payload?: Array<Partial<{ role: string; content: unknown }>>;+ /** Explicit durable names used by a validated event-actor preflight. */+ skillNames?: readonly string[];accessibleSkillIds: Types.ObjectId[];/** `execute_code` capability flag for the run. When false, the batch-upload* path is skipped entirely — skill bodies still reconstruct for history@@ -635,6 +638,13 @@ export interface PrimeInvokedSkillsResult {/** Pre-resolved skill bodies keyed by skill name. Passed to formatAgentMessages* so it can reconstruct HumanMessages at the right position in the message sequence. */skills?: Map<string, string>;+ /** Exact records resolved under the current request's ACL. */+ skillManifest?: Array<{+ id: string;+ name: string;+ version: number;+ contentDigest: string;+ }>;}export interface PrimeInvokedSkillsForProfilesDeps@@ -653,11 +663,14 @@ export interface PrimeInvokedSkillsForProfilesDepsexport async function primeInvokedSkills(deps: PrimeInvokedSkillsDeps,): Promise<PrimeInvokedSkillsResult> {- if (!deps.payload?.length || !deps.accessibleSkillIds?.length) {+ if ((!deps.payload?.length && !deps.skillNames?.length) || !deps.accessibleSkillIds?.length) {return {};}- const invokedSkills = extractInvokedSkillsFromPayload(deps.payload);+ const invokedSkills = new Set(deps.skillNames ?? []);+ for (const name of extractInvokedSkillsFromPayload(deps.payload ?? [])) {+ invokedSkills.add(name);+ }if (invokedSkills.size === 0) {return {};}@@ -689,6 +702,12 @@ export async function primeInvokedSkills(logger.warn('[primeInvokedSkills] Skill resolution failed:', getSafeErrorMetadata(r.reason));}}+ const skillManifest = resolvedSkills.map((skill) => ({+ id: skill._id.toString(),+ name: skill.name,+ version: skill.version,+ contentDigest: createSkillContentDigest(skill.body),+ }));// Phase 2: Single batch upload for ALL skills' files (shared session)let sessions: ToolSessionMap | undefined;@@ -784,7 +803,11 @@ export async function primeInvokedSkills(files: cachedFiles,lastUpdated: Date.now(),} satisfies CodeSessionContext);- return { initialSessions: sessions, skills: skills.size > 0 ? skills : undefined };+ return {+ initialSessions: sessions,+ skills: skills.size > 0 ? skills : undefined,+ skillManifest,+ };}}}@@ -867,6 +890,7 @@ export async function primeInvokedSkills(return {initialSessions: sessions,skills: skills.size > 0 ? skills : undefined,+ skillManifest,};}@@ -893,9 +917,30 @@ export async function primeInvokedSkillsForProfiles(let initialSessions: ToolSessionMap | undefined;const skills = new Map<string, string>();+ const skillManifestByName = new Map<+ string,+ NonNullable<PrimeInvokedSkillsResult['skillManifest']>[number]+ >();for (const { profile, result } of profileResults) {+ const resultManifestByName = new Map(+ (result.skillManifest ?? []).map((skill) => [skill.name, skill]),+ );for (const [name, body] of result.skills ?? []) {+ const identity = resultManifestByName.get(name);+ if (identity == null) {+ throw new Error(`Skill "${name}" resolved without a semantic identity`);+ }+ const existingIdentity = skillManifestByName.get(name);+ const existingBody = skills.get(name);+ if (+ (existingIdentity != null &&+ JSON.stringify(existingIdentity) !== JSON.stringify(identity)) ||+ (existingBody != null && existingBody !== body)+ ) {+ throw new Error(`Skill "${name}" changed while execution profiles were initialized`);+ }skills.set(name, body);+ skillManifestByName.set(name, identity);}const skillFiles = result.initialSessions?.get(Constants.EXECUTE_CODE)?.files;if (!skillFiles?.length) {@@ -913,5 +958,9 @@ export async function primeInvokedSkillsForProfiles(return {initialSessions,skills: skills.size > 0 ? skills : undefined,+ skillManifest:+ skillManifestByName.size > 0+ ? [...skillManifestByName.values()].sort((left, right) => left.id.localeCompare(right.id))+ : undefined,};}diff --git a/packages/api/src/agents/skills.ts b/packages/api/src/agents/skills.tsindex 42bc3ebe94..3cc4f7fea0 100644--- a/packages/api/src/agents/skills.ts+++ b/packages/api/src/agents/skills.ts@@ -6,6 +6,7 @@ import type { LCToolRegistry, LCTool, InjectedMessage } from '@librechat/agents'import type { BaseMessage } from '@librechat/agents/langchain/messages';import type { Agent } from 'librechat-data-provider';import type { Types } from 'mongoose';+import { createSkillContentDigest } from './compatibility';import { registerCodeExecutionTools } from './tools';import { logAxiosError } from '~/utils';@@ -30,6 +31,8 @@ export type TGetSkillByName = (_id: Types.ObjectId;name: string;body: string;+ /** Monotonic Skill document version used by checkpoint context compatibility. */+ version?: number;author: Types.ObjectId;/** Structured SKILL.md metadata retained for model-bound policy checks. */frontmatter?: Record<string, unknown>;@@ -780,6 +783,27 @@ export function buildSkillPrimeMessage(skill: { name: string; body: string }): I};}+/** Builds the exact live Skill overlay placed at the tail of an event actor checkpoint fork. */+export function buildAgentEventActorSkillMessages(+ skills: ReadonlyMap<string, string>,+): HumanMessage[] {+ return [...skills.entries()]+ .sort(([left], [right]) => left.localeCompare(right))+ .map(+ ([name, body]) =>+ new HumanMessage({+ id: `event-actor-skill:${createSkillContentDigest(`${name}\0${body}`)}`,+ content: body,+ additional_kwargs: {+ isMeta: true,+ source: SKILL_MESSAGE_SOURCE,+ trigger: SKILL_TRIGGER_MODEL,+ skillName: name,+ },+ }),+ );+}+export interface ResolveManualSkillsParams {/** Skill names the user invoked (via `$` popover or `always-apply`). */names: string[];@@ -798,6 +822,7 @@ export interface ResolveManualSkillsParams {_id: Types.ObjectId;name: string;body: string;+ version?: number;author: Types.ObjectId | string;deployment?: boolean;/** Structured SKILL.md metadata retained for model-bound policy checks. */@@ -846,6 +871,8 @@ export interface ResolvedSkillPrime {_id: Types.ObjectId;name: string;body: string;+ /** Monotonic Skill revision used by checkpoint compatibility. */+ version?: number;/** Structured SKILL.md metadata retained for model-bound policy checks. */frontmatter?: Record<string, unknown>;/**@@ -980,6 +1007,7 @@ export async function resolveManualSkills(_id: skill._id,name: skill.name,body: skill.body,+ version: skill.version,frontmatter: skill.frontmatter,};if (skill.allowedTools !== undefined) {@@ -1016,6 +1044,7 @@ export interface ResolveAlwaysApplySkillsParams {author: Types.ObjectId | string;frontmatter?: Record<string, unknown>;allowedTools?: string[];+ version?: number;deployment?: boolean;}>;has_more?: boolean;@@ -1140,6 +1169,7 @@ export async function resolveAlwaysApplySkills(_id: skill._id,name: skill.name,body: skill.body,+ version: skill.version,frontmatter: skill.frontmatter,};if (skill.allowedTools !== undefined) {diff --git a/packages/api/src/agents/traversal.spec.ts b/packages/api/src/agents/traversal.spec.tsindex 846fb276af..21e7188b2d 100644--- a/packages/api/src/agents/traversal.spec.ts+++ b/packages/api/src/agents/traversal.spec.ts@@ -3,6 +3,9 @@ import { collectReachableAgents } from './traversal';interface TestAgent {id: string;subagentAgentConfigs?: Array<TestAgent | null>;+ lazySubagentConfigs?: Array<TestAgent | null>;+ subagentGraphMemberMetadata?: Array<TestAgent | null>;+ subagentGraphConfigs?: Array<{ memberConfigs: Array<TestAgent | null> }>;}describe('collectReachableAgents', () => {@@ -23,4 +26,20 @@ describe('collectReachableAgents', () => {expect(collectReachableAgents([first])).toEqual([first, second]);});++ it('collects every effective topology route exactly once', () => {+ const eager: TestAgent = { id: 'eager' };+ const lazy: TestAgent = { id: 'lazy' };+ const graphMember: TestAgent = { id: 'graph-member' };+ const graphMetadata: TestAgent = { id: 'graph-metadata' };+ const root: TestAgent = {+ id: 'root',+ subagentAgentConfigs: [eager],+ lazySubagentConfigs: [lazy],+ subagentGraphMemberMetadata: [graphMetadata],+ subagentGraphConfigs: [{ memberConfigs: [graphMember, eager] }],+ };++ expect(collectReachableAgents([root])).toEqual([root, eager, lazy, graphMetadata, graphMember]);+ });});diff --git a/packages/api/src/agents/traversal.ts b/packages/api/src/agents/traversal.tsindex 707f2766e3..1685664066 100644--- a/packages/api/src/agents/traversal.ts+++ b/packages/api/src/agents/traversal.ts@@ -1,5 +1,10 @@export interface ReachableAgent<TAgent> {readonly subagentAgentConfigs?: readonly (TAgent | null | undefined)[];+ readonly lazySubagentConfigs?: readonly (TAgent | null | undefined)[];+ readonly subagentGraphMemberMetadata?: readonly (TAgent | null | undefined)[];+ readonly subagentGraphConfigs?: readonly {+ readonly memberConfigs?: readonly (TAgent | null | undefined)[];+ }[];}/**@@ -21,7 +26,14 @@ export function collectReachableAgents<T extends ReachableAgent<T>>(}visited.add(agent);agents.push(agent);- pending.push(...(agent.subagentAgentConfigs ?? []));+ pending.push(+ ...(agent.subagentAgentConfigs ?? []),+ ...(agent.lazySubagentConfigs ?? []),+ ...(agent.subagentGraphMemberMetadata ?? []),+ );+ for (const graph of agent.subagentGraphConfigs ?? []) {+ pending.push(...(graph.memberConfigs ?? []));+ }}return agents;diff --git a/packages/api/src/agents/triggers/actor.spec.ts b/packages/api/src/agents/triggers/actor.spec.tsindex f73c6a02e0..bf391fd350 100644--- a/packages/api/src/agents/triggers/actor.spec.ts+++ b/packages/api/src/agents/triggers/actor.spec.ts@@ -9,6 +9,7 @@ import {getAgentCheckpointer,} from '../checkpointer';import { createAgentEventActionRecorder, findAgentEventAppliedAction } from './outcome';+import { createAgentContextFingerprint } from '../compatibility';import { executeAgentEventActor } from './actor';jest.mock('../checkpointer', () => ({@@ -58,26 +59,47 @@ describe('event actor host adapter', () => {legacyTurn,epoch,})),- commitState: jest.fn(async ({ expected, expectedEpoch, checkpoint }) => {- if (- expectedEpoch !== epoch ||- (state == null && expected != null) ||- (state != null &&- (expected == null ||- expected.generation !== state.generation ||- expected.checkpoint.checkpointId !== state.checkpoint.checkpointId ||- (expected.requiresColdStart === true) !== (state.requiresColdStart === true)))- ) {- return { status: 'stale' as const, ...(state == null ? {} : { state }) };- }- const previous = state?.checkpoint;- state = {- generation: (state?.generation ?? 0) + 1,+ commitState: jest.fn(+ async ({+ expected,+ expectedEpoch,checkpoint,- ...(previous == null ? {} : { previousCheckpoint: previous }),- };- return { status: 'committed' as const, state };- }),+ contextFingerprint,+ skillManifest,+ discoveredToolNames,+ summary,+ contextMeta,+ }) => {+ if (+ expectedEpoch !== epoch ||+ (state == null && expected != null) ||+ (state != null &&+ (expected == null ||+ expected.generation !== state.generation ||+ expected.checkpoint.checkpointId !== state.checkpoint.checkpointId ||+ JSON.stringify(expected.skillManifest) !== JSON.stringify(state.skillManifest) ||+ JSON.stringify(expected.discoveredToolNames) !==+ JSON.stringify(state.discoveredToolNames) ||+ JSON.stringify(expected.summary) !== JSON.stringify(state.summary) ||+ JSON.stringify(expected.contextMeta) !== JSON.stringify(state.contextMeta) ||+ (expected.requiresColdStart === true) !== (state.requiresColdStart === true)))+ ) {+ return { status: 'stale' as const, ...(state == null ? {} : { state }) };+ }+ const previous = state?.checkpoint;+ state = {+ generation: (state?.generation ?? 0) + 1,+ checkpoint,+ ...(contextFingerprint == null ? {} : { contextFingerprint }),+ ...(skillManifest == null ? {} : { skillManifest }),+ ...(discoveredToolNames == null ? {} : { discoveredToolNames }),+ ...(summary == null ? {} : { summary }),+ ...(contextMeta == null ? {} : { contextMeta }),+ ...(previous == null ? {} : { previousCheckpoint: previous }),+ };+ return { status: 'committed' as const, state };+ },+ ),recordReconciliation: jest.fn(async () => true),resolveReconciliation: jest.fn(async () => true),admitAction: jest.fn(async () => true),@@ -123,10 +145,111 @@ describe('event actor host adapter', () => {expect.stringMatching(/^event-actor\//),'event-2',undefined,+ undefined,);expect(state).toMatchObject({ generation: 2, checkpoint: { checkpointId: 'checkpoint-2' } });});+ it('rebuilds on a missing or changed context fingerprint and stamps the new head', async () => {+ const current = createAgentContextFingerprint({ agents: [{ id: 'agent-1', version: 2 }] });+ state = {+ generation: 1,+ checkpoint: {+ threadId: conversationId,+ checkpointId: 'checkpoint-old-context',+ checkpointNs: 'event-actor/old-context',+ },+ };+ const dependencies = deps();+ let continuation: 'warm' | 'cold' | undefined;++ await executeAgentEventActor(+ {+ user: 'user-1',+ conversationId,+ invocationId: 'event-new-context',+ event: { id: 'event-new-context', type: 'turn' },+ signal: new AbortController().signal,+ contextFingerprint: current,+ invoke: async (context) => {+ continuation = context.continuation;+ return 'response';+ },+ readAppliedAction: () => ({ toolName: 'submit_move' }),+ },+ dependencies,+ );++ expect(continuation).toBe('cold');+ expect(mockedFork).not.toHaveBeenCalled();+ expect(state?.contextFingerprint).toEqual(current);+ });++ it('validates the stored Skill manifest before warm continuation and commits additions', async () => {+ const current = createAgentContextFingerprint({ agents: [{ id: 'agent-1', version: 2 }] });+ const storedSkill = { id: 'skill-1', name: 'analysis', version: 3 };+ const invokedSkill = { id: 'skill-2', name: 'reporting', version: 1 };+ state = {+ generation: 1,+ checkpoint: {+ threadId: conversationId,+ checkpointId: 'checkpoint-compatible',+ checkpointNs: 'event-actor/compatible',+ },+ contextFingerprint: current,+ skillManifest: [storedSkill],+ discoveredToolNames: ['deferred_lookup'],+ summary: { text: 'Earlier compacted context.', tokenCount: 12 },+ contextMeta: { calibrationRatio: 1.25, encoding: 'o200k_base' },+ };+ let continuation: 'warm' | 'cold' | undefined;+ const checkpointMessageOverlay = { source: 'skill', messages: [] };++ await executeAgentEventActor(+ {+ user: 'user-1',+ conversationId,+ invocationId: 'event-skill-context',+ event: { id: 'event-skill-context', type: 'turn' },+ signal: new AbortController().signal,+ resolveContext: async (observed) => ({+ fingerprint: current,+ skillManifest: observed.skillManifest ?? [],+ discoveredToolNames: observed.discoveredToolNames ?? [],+ summary: observed.summary,+ contextMeta: observed.contextMeta,+ checkpointMessageOverlay,+ }),+ readResultContext: async () => ({+ fingerprint: current,+ skillManifest: [storedSkill, invokedSkill],+ discoveredToolNames: ['deferred_lookup', 'deferred_write'],+ summary: { text: 'Updated compacted context.', tokenCount: 15 },+ contextMeta: { calibrationRatio: 1.3, encoding: 'o200k_base' },+ }),+ invoke: async (context) => {+ continuation = context.continuation;+ return 'response';+ },+ readAppliedAction: () => ({ toolName: 'submit_move' }),+ },+ deps(),+ );++ expect(continuation).toBe('warm');+ expect(state?.skillManifest).toEqual([storedSkill, invokedSkill]);+ expect(state?.discoveredToolNames).toEqual(['deferred_lookup', 'deferred_write']);+ expect(state?.summary).toEqual({ text: 'Updated compacted context.', tokenCount: 15 });+ expect(state?.contextMeta).toEqual({ calibrationRatio: 1.3, encoding: 'o200k_base' });+ expect(mockedFork).toHaveBeenCalledWith(+ expect.anything(),+ expect.any(String),+ 'event-skill-context',+ undefined,+ checkpointMessageOverlay,+ );+ });+it('commits from the execution-time receipt when run steps lag sendMessage', async () => {const dependencies = deps();const expectedAction = { toolName: 'submit_move', argumentSubset: { gameId: 'game-1' } };@@ -461,6 +584,41 @@ describe('event actor host adapter', () => {expect(mockedDelete).not.toHaveBeenCalled();});+ it('retains applied-action evidence when result context capture fails', async () => {+ const dependencies = deps();+ let toolExecutions = 0;+ await expect(+ executeAgentEventActor(+ {+ user: 'user-1',+ conversationId,+ invocationId: 'event-context-indeterminate',+ event: { id: 'event-context-indeterminate' },+ signal: new AbortController().signal,+ invoke: async () => {+ toolExecutions += 1;+ return 'response';+ },+ readAppliedAction: () => ({ toolName: 'submit_move' }),+ readResultContext: async () => {+ throw new Error('memory partition unavailable');+ },+ },+ dependencies,+ ),+ ).rejects.toThrow('requires commit_indeterminate reconciliation');++ expect(toolExecutions).toBe(1);+ expect(dependencies.commitState).not.toHaveBeenCalled();+ expect(dependencies.recordReconciliation).toHaveBeenCalledWith(+ expect.objectContaining({+ reconciliation: expect.objectContaining({ status: 'commit_indeterminate' }),+ }),+ );+ expect(mockedCapture).not.toHaveBeenCalled();+ expect(mockedDelete).not.toHaveBeenCalled();+ });+it('recovers an indeterminate cleanup after the actor head was committed', async () => {state = {generation: 2,diff --git a/packages/api/src/agents/triggers/actor.ts b/packages/api/src/agents/triggers/actor.tsindex 25444f4f4f..9dd6e28b76 100644--- a/packages/api/src/agents/triggers/actor.ts+++ b/packages/api/src/agents/triggers/actor.ts@@ -11,8 +11,11 @@ import type {AgentTriggerDeliveryMethods,ConversationMethods,IAgentEventActorState,+ IAgentEventActorSkillIdentity,} from '@librechat/data-schemas';import type { TCheckpointerConfig } from 'librechat-data-provider';+import type { AgentEventCheckpointMessageOverlay } from '../checkpointer';+import type { AgentContextFingerprint } from '../compatibility';import type { AgentTriggerExpectedAction } from './envelope';import type { AgentEventAppliedAction } from './outcome';import {@@ -22,6 +25,7 @@ import {getAgentCheckpointer,getApprovalTtlMs,} from '../checkpointer';+import { agentContextFingerprintsMatch } from '../compatibility';interface EventActorResult extends Record<string, EventActorEvent> {action: AgentEventAppliedAction;@@ -47,12 +51,24 @@ export interface ExecuteAgentEventActorInput<T> {expectedAction?: AgentTriggerExpectedAction;signal: AbortSignal;checkpointer?: TCheckpointerConfig;+ contextFingerprint?: AgentContextFingerprint;+ resolveContext?(state: IAgentEventActorState): Promise<AgentEventActorContext | undefined>;+ readResultContext?(): Promise<AgentEventActorContext | undefined>;/** Deprecated compatibility input. Elapsed time never proves replay safety. */legacyTurnStaleMs?: number;invoke(context: AgentEventActorInvocationContext): Promise<T>;readAppliedAction(): AgentEventAppliedAction | undefined;}+export interface AgentEventActorContext {+ fingerprint: AgentContextFingerprint;+ skillManifest: IAgentEventActorSkillIdentity[];+ discoveredToolNames?: string[];+ summary?: IAgentEventActorState['summary'];+ contextMeta?: IAgentEventActorState['contextMeta'];+ checkpointMessageOverlay?: AgentEventCheckpointMessageOverlay;+}+export interface ExecuteAgentEventActorResult<T> {value: T;execution: EventActorExecutionResult<EventActorResult>;@@ -121,6 +137,8 @@ export async function executeAgentEventActor<T>(let ownedActionAdmissionId: string | undefined;let observedState: IAgentEventActorState | null | undefined;let observedEpoch: number | undefined;+ let preparedContext: AgentEventActorContext | undefined;+ let resultContext: AgentEventActorContext | undefined;const adapter: EventActorHostAdapter<EventActorEvent, EventActorResult> = {async prepare(request, context) {if (context.signal.aborted) {@@ -245,11 +263,24 @@ export async function executeAgentEventActor<T>(if (state == null || state.requiresColdStart === true) {return { status: 'checkpoint_unavailable', head };}+ const validatesContext = input.resolveContext != null || input.contextFingerprint != null;+ if (validatesContext) {+ preparedContext = input.resolveContext+ ? await input.resolveContext(state)+ : { fingerprint: input.contextFingerprint!, skillManifest: [], discoveredToolNames: [] };+ if (+ preparedContext == null ||+ !agentContextFingerprintsMatch(state.contextFingerprint, preparedContext.fingerprint)+ ) {+ return { status: 'checkpoint_unavailable', head };+ }+ }const fork = await forkAgentEventCheckpoint(state.checkpoint,request.checkpointNs,request.invocationId,input.checkpointer,+ preparedContext?.checkpointMessageOverlay,);if (fork == null) {return { status: 'checkpoint_unavailable', head };@@ -397,6 +428,18 @@ export async function executeAgentEventActor<T>(}return { status: 'completed_no_action' };}+ try {+ resultContext = input.readResultContext ? await input.readResultContext() : preparedContext;+ } catch (error) {+ return {+ status: 'applied',+ result: {+ action,+ checkpointCaptureError: `Applied turn context could not be captured: ${asError(error).message}`,+ },+ checkpoint: invocation.fork,+ };+ }let checkpoint: Awaited<ReturnType<typeof captureAgentEventCheckpoint>>;try {checkpoint = await captureAgentEventCheckpoint(@@ -464,6 +507,19 @@ export async function executeAgentEventActor<T>(checkpointNs: expectedHeadCheckpoint!.checkpointNs,},...(observedState.requiresColdStart === true ? { requiresColdStart: true } : {}),+ ...(observedState.contextFingerprint == null+ ? {}+ : { contextFingerprint: observedState.contextFingerprint }),+ ...(observedState.skillManifest == null+ ? {}+ : { skillManifest: observedState.skillManifest }),+ ...(observedState.discoveredToolNames == null+ ? {}+ : { discoveredToolNames: observedState.discoveredToolNames }),+ ...(observedState.summary == null ? {} : { summary: observedState.summary }),+ ...(observedState.contextMeta == null+ ? {}+ : { contextMeta: observedState.contextMeta }),};const committed = await deps.commitState({user: input.user,@@ -481,6 +537,17 @@ export async function executeAgentEventActor<T>(checkpointId: appliedCheckpointId,checkpointNs: request.checkpoint.checkpointNs,},+ ...(resultContext == null+ ? {}+ : {+ contextFingerprint: resultContext.fingerprint,+ skillManifest: resultContext.skillManifest,+ discoveredToolNames: resultContext.discoveredToolNames ?? [],+ ...(resultContext.summary == null ? {} : { summary: resultContext.summary }),+ ...(resultContext.contextMeta == null+ ? {}+ : { contextMeta: resultContext.contextMeta }),+ }),});if (committed.status === 'stale') {/** A host-private cold marker can invalidate the CAS without advancingdiff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.tsindex 4cd74f5f45..edcd562925 100644--- a/packages/data-schemas/src/index.ts+++ b/packages/data-schemas/src/index.ts@@ -46,6 +46,13 @@ export {digestMCPAuthorityValue,} from './methods';export { FAVORITE_ITEM_TYPES } from './types/favorite';+export {+ MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS,+ MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH,+ MAX_AGENT_EVENT_ACTOR_SKILLS,+ MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH,+ MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH,+} from './types/convo';export type * from './types';export type * from './methods';export {diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.tsindex 5e9e12e914..bf753d9494 100644--- a/packages/data-schemas/src/methods/conversation.spec.ts+++ b/packages/data-schemas/src/methods/conversation.spec.ts@@ -4234,6 +4234,146 @@ describe('Conversation Operations', () => {);});+ it('persists complete warm-continuation state with the actor head', async () => {+ const conversationId = uuidv4();+ const fingerprint = {+ algorithm: 'sha256' as const,+ version: 1,+ digest: 'context-one',+ };+ const actorCheckpoint = {+ threadId: conversationId,+ checkpointId: 'checkpoint-context',+ checkpointNs: 'event-actor/context',+ };+ const skillManifest = [{ id: 'skill-1', name: 'analysis', version: 3 }];+ const discoveredToolNames = ['deferred_lookup', 'deferred_write'];+ const summary = { text: 'Earlier compacted context.', tokenCount: 12 };+ const contextMeta = { calibrationRatio: 1.25, encoding: 'o200k_base' };+ await Conversation.create({+ conversationId,+ user: 'actor-context-user',+ endpoint: EModelEndpoint.agents,+ agent_id: 'agent-player',+ agentEventBinding: {+ bindingId: `evtbind_${'f'.repeat(48)}`,+ sourceKeyId: 'key-a',+ actorId: 'player-a',+ },+ subagentThread: {+ rootConversationId: 'parent',+ parentConversationId: 'parent',+ parentMessageId: 'parent-message',+ parentToolCallId: 'event-binding',+ parentAgentId: 'agent-director',+ subagentType: 'agent-player',+ subagentKind: 'agent',+ depth: 1,+ },+ });+ await methods.recordAgentEventActorReconciliation({+ user: 'actor-context-user',+ conversationId,+ reconciliation: {+ invocationId: 'context-one',+ status: 'invocation_pending',+ checkpoint: actorCheckpoint,+ action: { toolName: 'submit_move' },+ observedAt: new Date(),+ },+ });++ const committed = await methods.commitAgentEventActorState({+ user: 'actor-context-user',+ conversationId,+ invocationId: 'context-one',+ expectedEpoch: 0,+ action: { toolName: 'submit_move' },+ checkpoint: actorCheckpoint,+ contextFingerprint: fingerprint,+ skillManifest,+ discoveredToolNames,+ summary,+ contextMeta,+ });++ expect(committed).toMatchObject({+ status: 'committed',+ state: {+ generation: 1,+ checkpoint: actorCheckpoint,+ contextFingerprint: fingerprint,+ skillManifest,+ discoveredToolNames,+ summary,+ contextMeta,+ },+ });+ await expect(+ methods.getAgentEventActorSnapshot({ user: 'actor-context-user', conversationId }),+ ).resolves.toMatchObject({+ state: {+ contextFingerprint: fingerprint,+ skillManifest,+ discoveredToolNames,+ summary,+ contextMeta,+ },+ });++ await expect(+ methods.commitAgentEventActorState({+ user: 'actor-context-user',+ conversationId,+ invocationId: 'too-many-skills',+ expectedEpoch: 0,+ action: { toolName: 'submit_move' },+ checkpoint: actorCheckpoint,+ skillManifest: Array.from({ length: 65 }, (_, index) => ({+ id: `skill-${index}`,+ name: `skill-${index}`,+ version: 1,+ })),+ }),+ ).rejects.toThrow('Event actor Skill manifest exceeds 64');++ await expect(+ methods.commitAgentEventActorState({+ user: 'actor-context-user',+ conversationId,+ invocationId: 'too-many-tools',+ expectedEpoch: 0,+ action: { toolName: 'submit_move' },+ checkpoint: actorCheckpoint,+ discoveredToolNames: Array.from({ length: 129 }, (_, index) => `tool-${index}`),+ }),+ ).rejects.toThrow('Event actor discovered-tool state is invalid');++ await expect(+ methods.commitAgentEventActorState({+ user: 'actor-context-user',+ conversationId,+ invocationId: 'invalid-summary',+ expectedEpoch: 0,+ action: { toolName: 'submit_move' },+ checkpoint: actorCheckpoint,+ summary: { text: '', tokenCount: 1 },+ }),+ ).rejects.toThrow('Event actor summary state is invalid');++ await expect(+ methods.commitAgentEventActorState({+ user: 'actor-context-user',+ conversationId,+ invocationId: 'invalid-calibration',+ expectedEpoch: 0,+ action: { toolName: 'submit_move' },+ checkpoint: actorCheckpoint,+ contextMeta: { calibrationRatio: 9, encoding: 'o200k_base' },+ }),+ ).rejects.toThrow('Event actor context calibration is invalid');+ });+it('retains exact legacy settled receipts until delivery-ledger migration', async () => {const conversationId = uuidv4();await Conversation.create({diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.tsindex 973f005e3c..f23a722aa6 100644--- a/packages/data-schemas/src/methods/conversation.ts+++ b/packages/data-schemas/src/methods/conversation.ts@@ -16,6 +16,13 @@ import type {ISubagentThreadReservation,} from '~/types';import type { MessageMethods } from './message';+import {+ MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS,+ MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH,+ MAX_AGENT_EVENT_ACTOR_SKILLS,+ MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH,+ MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH,+} from '~/types/convo';import {activeExpirationFilter,buildRetentionVisibilityFilter,@@ -245,6 +252,11 @@ export interface ConversationMethods {expected?: IAgentEventActorState;expectedEpoch: number;checkpoint: IAgentEventActorCheckpoint;+ contextFingerprint?: IAgentEventActorState['contextFingerprint'];+ skillManifest?: IAgentEventActorState['skillManifest'];+ discoveredToolNames?: IAgentEventActorState['discoveredToolNames'];+ summary?: IAgentEventActorState['summary'];+ contextMeta?: IAgentEventActorState['contextMeta'];}): Promise<AgentEventActorCommitResult>;beginAgentEventActorLegacyTurn(input: {user: string;@@ -533,10 +545,46 @@ export function createConversationMethods(expected?: IAgentEventActorState;expectedEpoch: number;checkpoint: IAgentEventActorCheckpoint;+ contextFingerprint?: IAgentEventActorState['contextFingerprint'];+ skillManifest?: IAgentEventActorState['skillManifest'];+ discoveredToolNames?: IAgentEventActorState['discoveredToolNames'];+ summary?: IAgentEventActorState['summary'];+ contextMeta?: IAgentEventActorState['contextMeta'];}): Promise<AgentEventActorCommitResult> {if (input.checkpoint.threadId !== input.conversationId) {throw new Error('Event actor checkpoint changed its logical thread');}+ if ((input.skillManifest?.length ?? 0) > MAX_AGENT_EVENT_ACTOR_SKILLS) {+ throw new RangeError(`Event actor Skill manifest exceeds ${MAX_AGENT_EVENT_ACTOR_SKILLS}`);+ }+ if (+ (input.discoveredToolNames?.length ?? 0) > MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS ||+ input.discoveredToolNames?.some(+ (name) => name.length === 0 || name.length > MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH,+ )+ ) {+ throw new RangeError('Event actor discovered-tool state is invalid');+ }+ if (+ input.summary != null &&+ (input.summary.text.length === 0 ||+ input.summary.text.length > MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH ||+ !Number.isFinite(input.summary.tokenCount) ||+ input.summary.tokenCount < 0)+ ) {+ throw new RangeError('Event actor summary state is invalid');+ }+ if (+ input.contextMeta != null &&+ (!Number.isFinite(input.contextMeta.calibrationRatio) ||+ input.contextMeta.calibrationRatio < 0.5 ||+ input.contextMeta.calibrationRatio > 5 ||+ (input.contextMeta.encoding != null &&+ (input.contextMeta.encoding.length === 0 ||+ input.contextMeta.encoding.length > MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH)))+ ) {+ throw new RangeError('Event actor context calibration is invalid');+ }const Conversation = mongoose.models.Conversation as Model<IConversation>;/** A legacy turn against a headless or already cold-marked actor leaves* the head fields unchanged, so the CAS must also require the invalidation@@ -555,6 +603,28 @@ export function createConversationMethods('agentEventActor.checkpoint.threadId': input.expected.checkpoint.threadId,'agentEventActor.checkpoint.checkpointId': input.expected.checkpoint.checkpointId,'agentEventActor.checkpoint.checkpointNs': input.expected.checkpoint.checkpointNs,+ ...(input.expected.contextFingerprint == null+ ? { 'agentEventActor.contextFingerprint': { $exists: false } }+ : {+ 'agentEventActor.contextFingerprint.algorithm':+ input.expected.contextFingerprint.algorithm,+ 'agentEventActor.contextFingerprint.version':+ input.expected.contextFingerprint.version,+ 'agentEventActor.contextFingerprint.digest':+ input.expected.contextFingerprint.digest,+ }),+ ...(input.expected.skillManifest == null+ ? { 'agentEventActor.skillManifest': { $exists: false } }+ : { 'agentEventActor.skillManifest': input.expected.skillManifest }),+ ...(input.expected.discoveredToolNames == null+ ? { 'agentEventActor.discoveredToolNames': { $exists: false } }+ : { 'agentEventActor.discoveredToolNames': input.expected.discoveredToolNames }),+ ...(input.expected.summary == null+ ? { 'agentEventActor.summary': { $exists: false } }+ : { 'agentEventActor.summary': input.expected.summary }),+ ...(input.expected.contextMeta == null+ ? { 'agentEventActor.contextMeta': { $exists: false } }+ : { 'agentEventActor.contextMeta': input.expected.contextMeta }),'agentEventActor.requiresColdStart':input.expected.requiresColdStart === true ? true : { $ne: true },}),@@ -562,6 +632,13 @@ export function createConversationMethods(const nextState: IAgentEventActorState = {generation: (input.expected?.generation ?? 0) + 1,checkpoint: input.checkpoint,+ ...(input.contextFingerprint == null ? {} : { contextFingerprint: input.contextFingerprint }),+ ...(input.skillManifest == null ? {} : { skillManifest: input.skillManifest }),+ ...(input.discoveredToolNames == null+ ? {}+ : { discoveredToolNames: input.discoveredToolNames }),+ ...(input.summary == null ? {} : { summary: input.summary }),+ ...(input.contextMeta == null ? {} : { contextMeta: input.contextMeta }),...(input.expected == null ? {} : { previousCheckpoint: input.expected.checkpoint }),};const previous = await Conversation.findOneAndUpdate(diff --git a/packages/data-schemas/src/methods/skill.spec.ts b/packages/data-schemas/src/methods/skill.spec.tsindex aaefd5795b..c952cff11c 100644--- a/packages/data-schemas/src/methods/skill.spec.ts+++ b/packages/data-schemas/src/methods/skill.spec.ts@@ -1337,6 +1337,7 @@ describe('Skill CRUD methods', () => {});const names = result.skills.map((s) => s.name).sort();expect(names).toEqual(['always-a', 'always-b']);+ expect(result.skills.map((skill) => skill.version)).toEqual([1, 1]);});it('listAlwaysApplySkills excludes rows outside accessibleIds', async () => {diff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.tsindex c0b2d692e2..3fcc67a6fa 100644--- a/packages/data-schemas/src/methods/skill.ts+++ b/packages/data-schemas/src/methods/skill.ts@@ -789,6 +789,7 @@ export type ListAlwaysApplySkillsResult = {author: Types.ObjectId;frontmatter?: Record<string, unknown>;allowedTools?: string[];+ version: number;}>;/** `true` when another page exists beyond this one. */has_more: boolean;@@ -1419,7 +1420,7 @@ export function createSkillMethods(const rows = await Skill.find(filter).sort({ updatedAt: -1, _id: 1 }).limit(limit + 1)- .select('name body author frontmatter updatedAt allowedTools')+ .select('name body author frontmatter updatedAt allowedTools version').lean();const has_more = rows.length > limit;@@ -1448,6 +1449,7 @@ export function createSkillMethods(name: row.name,body: row.body ?? '',author: row.author as Types.ObjectId,+ version: row.version,frontmatter: row.frontmatter,};if (row.allowedTools !== undefined) {diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.tsindex ac91a2d4e3..c08fcf8d46 100644--- a/packages/data-schemas/src/schema/convo.ts+++ b/packages/data-schemas/src/schema/convo.ts@@ -1,4 +1,11 @@import { Schema } from 'mongoose';+import {+ MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS,+ MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH,+ MAX_AGENT_EVENT_ACTOR_SKILLS,+ MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH,+ MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH,+} from '~/types/convo';import { conversationPreset } from './defaults';import { IConversation } from '~/types';@@ -80,6 +87,63 @@ const convoSchema: Schema<IConversation> = new Schema(_id: false,required: true,},+ contextFingerprint: {+ type: {+ algorithm: { type: String, enum: ['sha256'], required: true },+ version: { type: Number, min: 1, required: true },+ digest: { type: String, required: true },+ },+ _id: false,+ default: undefined,+ },+ skillManifest: {+ type: [+ {+ id: { type: String, required: true },+ name: { type: String, required: true },+ version: { type: Number, min: 1, required: true },+ contentDigest: { type: String, default: undefined },+ _id: false,+ },+ ],+ default: undefined,+ validate: {+ validator: (skills: unknown[]) => skills.length <= MAX_AGENT_EVENT_ACTOR_SKILLS,+ message: `Event actor Skill manifest exceeds ${MAX_AGENT_EVENT_ACTOR_SKILLS}`,+ },+ },+ discoveredToolNames: {+ type: [{ type: String, maxlength: MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH }],+ default: undefined,+ validate: {+ validator: (names: unknown[]) => names.length <= MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS,+ message: `Event actor discovered-tool state exceeds ${MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS}`,+ },+ },+ summary: {+ type: {+ text: {+ type: String,+ required: true,+ maxlength: MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH,+ },+ tokenCount: { type: Number, min: 0, required: true },+ },+ _id: false,+ default: undefined,+ },+ contextMeta: {+ type: {+ calibrationRatio: { type: Number, min: 0.5, max: 5, required: true },+ encoding: {+ type: String,+ maxlength: MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH,+ default: undefined,+ },+ },+ _id: false,+ default: undefined,+ },previousCheckpoint: {type: {threadId: { type: String, required: true },diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.tsindex 9e8cb3ca7a..45c86586c3 100644--- a/packages/data-schemas/src/types/convo.ts+++ b/packages/data-schemas/src/types/convo.ts@@ -1,6 +1,12 @@import type { TSubagentThreadLineage } from 'librechat-data-provider';import type { Document, Types } from 'mongoose';+export const MAX_AGENT_EVENT_ACTOR_SKILLS = 64;+export const MAX_AGENT_EVENT_ACTOR_DISCOVERED_TOOLS = 128;+export const MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH = 512;+export const MAX_AGENT_EVENT_ACTOR_SUMMARY_LENGTH = 1_000_000;+export const MAX_AGENT_EVENT_ACTOR_ENCODING_LENGTH = 128;+export interface ISubagentThreadLease {token: string;taskId: string;@@ -20,10 +26,42 @@ export interface IAgentEventActorCheckpoint {checkpointNs: string;}+export interface IAgentEventActorContextFingerprint {+ algorithm: 'sha256';+ version: number;+ digest: string;+}++export interface IAgentEventActorSkillIdentity {+ id: string;+ name: string;+ version: number;+ contentDigest?: string;+}++export interface IAgentEventActorSummary {+ text: string;+ tokenCount: number;+}++export interface IAgentEventActorContextMeta {+ calibrationRatio: number;+ encoding?: string;+}+/** Private committed checkpoint state for one event-bound child actor. */export interface IAgentEventActorState {generation: number;checkpoint: IAgentEventActorCheckpoint;+ contextFingerprint?: IAgentEventActorContextFingerprint;+ /** Bounded semantic Skill set needed to validate a warm continuation without history. */+ skillManifest?: IAgentEventActorSkillIdentity[];+ /** Bounded run-evolved tool-search state needed to rebuild the next model binding. */+ discoveredToolNames?: string[];+ /** Active compaction summary, which the SDK keeps outside checkpointed graph messages. */+ summary?: IAgentEventActorSummary;+ /** Pruner calibration carried by ordinary turns on the parent response message. */+ contextMeta?: IAgentEventActorContextMeta;previousCheckpoint?: IAgentEventActorCheckpoint;/** Forces the next qualifying event to rebuild from durable message history. */requiresColdStart?: boolean;