π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β‘οΈ perf(agent): store a run's tool set once on the state (#19707)
Arvin Xudb3aa5f31725
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.tsindex 94320433d07..a3bf95277cd 100644--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts@@ -1,10 +1,32 @@-import type { AgentState } from '@lobechat/agent-runtime';+import { type AgentState, normalizeAgentState } from '@lobechat/agent-runtime';import { describe, expect, it } from 'vitest';import { resolveServerCallLlmTooling } from '../serverCallLlmTooling';-const buildState = (state: Pick<AgentState, 'binding' | 'plan' | 'principal'> = {}): AgentState =>- state as AgentState;+const buildState = (+ state: Pick<+ AgentState,+ | 'binding'+ | 'operationToolSet'+ | 'plan'+ | 'principal'+ | 'toolExecutorMap'+ | 'toolManifestMap'+ | 'toolSourceMap'+ | 'tools'+ > = {},+): AgentState => state as AgentState;++const webBrowsing = {+ api: [{ description: 'Search the web', name: 'search', parameters: {} }],+ identifier: 'lobe-web-browsing',+ meta: { title: 'Web Browsing' },+ type: 'builtin',+} as unknown as NonNullable<AgentState['toolManifestMap']>[string];+const searchTool = {+ function: { name: 'lobe-web-browsing____search' },+ type: 'function',+} as unknown as NonNullable<AgentState['tools']>[number];describe('resolveServerCallLlmTooling', () => {// Regression: `serverCallLlmContextBuilder` needs this to compute@@ -34,6 +56,47 @@ describe('resolveServerCallLlmTooling', () => {expect(result.activeDeviceId).toBeUndefined();});+ // The state stores the tool set once, on the operation slot. This is the exit:+ // if the payload stops finding its tools here, the model loses them entirely.+ it('resolves the tools from the operation slot alone', () => {+ const result = resolveServerCallLlmTooling(+ { operationId: 'op-1', stepIndex: 0 },+ buildState({+ operationToolSet: {+ enabledToolIds: ['lobe-web-browsing'],+ executorMap: {},+ manifestMap: { 'lobe-web-browsing': webBrowsing },+ sourceMap: { 'lobe-web-browsing': 'builtin' },+ tools: [searchTool],+ },+ }),+ );++ expect(result.tools).toEqual([searchTool]);+ expect(result.resolved.enabledToolIds).toEqual(['lobe-web-browsing']);+ });++ // An operation that started before the slot existed keeps its tool set in the+ // legacy top-level mirrors; the load path lifts them and the payload is the same.+ it('still resolves the tools of a pre-slot operation', () => {+ const legacy = buildState({+ toolExecutorMap: {},+ toolManifestMap: { 'lobe-web-browsing': webBrowsing },+ toolSourceMap: { 'lobe-web-browsing': 'builtin' },+ tools: [searchTool],+ });++ expect(+ resolveServerCallLlmTooling({ operationId: 'op-1', stepIndex: 0 }, legacy).tools,+ ).toEqual([searchTool]);+ expect(+ resolveServerCallLlmTooling(+ { operationId: 'op-1', stepIndex: 0 },+ normalizeAgentState(legacy),+ ).tools,+ ).toEqual([searchTool]);+ });+it('leaves the active device id undefined with no binding at all', () => {const result = resolveServerCallLlmTooling({ operationId: 'op-1', stepIndex: 0 }, buildState());diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.tsindex 5b2fa7e1181..ebaa931fdd0 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts@@ -1,4 +1,4 @@-import type { AgentState } from '@lobechat/agent-runtime';+import { type AgentState, selectOperationToolSet } from '@lobechat/agent-runtime';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import {buildStepSkillDelta,@@ -59,13 +59,7 @@ export const resolveServerCallLlmTooling = (// forbids devices β the same filter the tool executors apply.const activeDeviceId = resolveRunActiveDeviceId(state);const executionTarget = (state.plan?.execution as ExecutionPlan | undefined)?.target;- const operationToolSet: OperationToolSet = state.operationToolSet ?? {- enabledToolIds: [],- executorMap: state.toolExecutorMap ?? {},- manifestMap: state.toolManifestMap ?? {},- sourceMap: state.toolSourceMap ?? {},- tools: state.tools ?? [],- };+ const operationToolSet: OperationToolSet = selectOperationToolSet(state);const stepDelta = buildStepToolDelta({activeDeviceId,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex 3a1b3113c6d..320b30e3aad 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -1,4 +1,4 @@-import type { AgentState } from '@lobechat/agent-runtime';+import { type AgentState, selectToolSourceMap } from '@lobechat/agent-runtime';import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboarding/utils';import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';@@ -191,7 +191,7 @@ export const createServerContextFactProviders = ({// providers, so presence in the tool set is the connection).listConnectedConnectorIds: async (agentId) => {const connected = await loadConnectedComposioIds(db, userId, ctx.workspaceId, agentId);- const sourceMap = state.operationToolSet?.sourceMap ?? state.toolSourceMap ?? {};+ const sourceMap = selectToolSourceMap(state);for (const [identifier, source] of Object.entries(sourceMap)) {if (source === 'lobehubSkill') connected.add(identifier);}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex bb6b097ae19..f121a4ec837 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -470,8 +470,8 @@ describe('AgentRuntimeService', () => {stepCount: 0,messages: [],modelRuntimeConfig: mockParams.modelRuntimeConfig,+ operationToolSet: expect.objectContaining({ manifestMap: {} }),origin: expect.objectContaining({ userId: mockParams.userId }),- toolManifestMap: {},world: expect.objectContaining({ agent: mockParams.agentConfig }),}),);@@ -492,6 +492,29 @@ describe('AgentRuntimeService', () => {});});+ it('stores the run tool set once, on the operation slot', async () => {+ const manifestMap = { 'lobe-web-browsing': { identifier: 'lobe-web-browsing' } };++ await service.createOperation({+ ...mockParams,+ toolSet: {+ enabledToolIds: ['lobe-web-browsing'],+ executorMap: {},+ manifestMap,+ sourceMap: { 'lobe-web-browsing': 'builtin' },+ tools: [{ function: { name: 'search' }, type: 'function' }],+ } as unknown as OperationCreationParams['toolSet'],+ });++ const [, state] = mockCoordinator.saveAgentState.mock.calls[0];+ expect(state.operationToolSet.manifestMap).toEqual(manifestMap);+ // Manifests are the heaviest thing on the state and it is re-serialized at+ // every step, so the legacy top-level mirrors are not written any more.+ for (const mirror of ['toolExecutorMap', 'toolManifestMap', 'toolSourceMap', 'tools']) {+ expect(mirror in state).toBe(false);+ }+ });+it('keeps the frozen model facts on the run state but out of durable storage', async () => {const recordStart = vi.spyOn(AgentOperationModel.prototype, 'recordStart')diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 96dfd881edc..aa68787405c 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -1115,13 +1115,14 @@ export class AgentRuntimeService {// modelRuntimeConfig at state level for executor fallbackmodelRuntimeConfig,operationId,+ // The run's only copy of its tool set. The manifest map is the heaviest+ // thing on the state and the state is re-serialized at every step, so the+ // former top-level mirrors (`tools`, `toolManifestMap`, `toolSourceMap`,+ // `toolExecutorMap`) are no longer written; readers go through+ // `selectToolManifestMap` and friends.operationToolSet,status: 'idle',stepCount: initialStepCount,- // Backward-compat: resolved tool fields read by RuntimeExecutors- toolExecutorMap: operationToolSet.executorMap,- toolManifestMap: operationToolSet.manifestMap,- toolSourceMap: operationToolSet.sourceMap,// How the run executes β frozen from here on.plan: {eval: evalRuntime,@@ -1157,7 +1158,6 @@ export class AgentRuntimeService {userMemory,userTimezone,},- tools: operationToolSet.tools,// User intervention config for headless mode in async tasksuserInterventionConfig,} as Partial<AgentState>;diff --git a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts b/apps/server/src/services/agentRuntime/agentInterventionNotification.tsindex c69c73676de..3f020b004b7 100644--- a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts+++ b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts@@ -1,4 +1,8 @@-import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '@lobechat/agent-runtime';+import {+ DEFAULT_SECURITY_BLACKLIST,+ InterventionChecker,+ selectToolManifestMap,+} from '@lobechat/agent-runtime';import {type ChatToolPayload,classifyToolInterventionPresentation,@@ -168,7 +172,7 @@ const actionsFor = (* Unknown tools and incomplete discovery placeholders remain Review-only.*/const hasAuthoritativeApiDefinition = (state: any, tool: ChatToolPayload): boolean => {- const baseManifestMap = state?.operationToolSet?.manifestMap ?? state?.toolManifestMap ?? {};+ const baseManifestMap = selectToolManifestMap(state ?? {});const activatedManifestMap = Object.fromEntries((Array.isArray(state?.activatedStepTools) ? state.activatedStepTools : []).filter(diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 10da57df05d..cbce339590b 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -25,6 +25,7 @@ import {type SubAgentResultPayload,type SubAgentsBatchResultPayload,} from '../types';+import { selectRunTools, selectToolManifestMap } from '../utils/operationToolSet';import { shouldCompress } from '../utils/tokenCounter';const TOOL_NOT_ALLOWED_CONTENT =@@ -72,7 +73,7 @@ export class GeneralChatAgent implements Agent {}private getTools(state: AgentState, fallbackTools?: any[]): any[] | undefined {- return this.config.tools ?? state.tools ?? state.operationToolSet?.tools ?? fallbackTools;+ return this.config.tools ?? selectRunTools(state) ?? fallbackTools;}private getAllowedToolNamesPayload() {@@ -108,7 +109,7 @@ export class GeneralChatAgent implements Agent {state: AgentState,): ExtendedHumanInterventionConfig | undefined {const { identifier, apiName } = toolCalling;- const manifest = state.toolManifestMap[identifier];+ const manifest = selectToolManifestMap(state)[identifier];if (!manifest) return undefined;@@ -217,7 +218,7 @@ export class GeneralChatAgent implements Agent {}// Phase 2.5: Get manifest for later use- const manifest = state.toolManifestMap?.[identifier];+ const manifest = selectToolManifestMap(state)[identifier];// Phase 3: Per-tool dynamic resolverconst config = this.getToolInterventionConfig(toolCalling, state);@@ -272,7 +273,7 @@ export class GeneralChatAgent implements Agent {// Only applies to manual/allow-list modes; auto-run users accept the riskif (!manifest) {console.warn(- `[InterventionGuard] Unknown tool "${identifier}/${apiName}" not found in toolManifestMap (keys: ${Object.keys(state.toolManifestMap ?? {}).join(', ')}), requiring intervention`,+ `[InterventionGuard] Unknown tool "${identifier}/${apiName}" not found in toolManifestMap (keys: ${Object.keys(selectToolManifestMap(state)).join(', ')}), requiring intervention`,);toolsNeedingIntervention.push(toolCalling);continue;diff --git a/packages/agent-runtime/src/agents/graph/GraphAgent.ts b/packages/agent-runtime/src/agents/graph/GraphAgent.tsindex 8b24f43fed4..9f99e42f1db 100644--- a/packages/agent-runtime/src/agents/graph/GraphAgent.ts+++ b/packages/agent-runtime/src/agents/graph/GraphAgent.ts@@ -15,6 +15,7 @@ import type {GeneralAgentCallLLMInstructionPayload,GeneralAgentConfig,} from '../../types';+import { selectRunTools, selectToolManifestMap } from '../../utils/operationToolSet';import { GeneralChatAgent } from '../GeneralChatAgent';import {evaluateGraphPromptTrigger,@@ -767,12 +768,11 @@ export class GraphAgent implements Agent {private getNodeTools(node: Readonly<AgentGraphNode>, state: AgentState): any[] {if (node.type !== 'agent') return [];- const rootTools =- this.generalConfig.tools ?? state.tools ?? state.operationToolSet?.tools ?? [];+ const rootTools = this.generalConfig.tools ?? selectRunTools(state) ?? [];if (!node.allowedToolApiNames) return rootTools;const allowedApiNames = new Set(node.allowedToolApiNames);- const manifestMap = state.operationToolSet?.manifestMap ?? state.toolManifestMap;+ const manifestMap = selectToolManifestMap(state);const toolNameResolver = new ToolNameResolver();const allowedToolNames = new Set<string>();diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.tsindex 02256a6b359..702d9dcb742 100644--- a/packages/agent-runtime/src/core/runtime.ts+++ b/packages/agent-runtime/src/core/runtime.ts@@ -468,7 +468,6 @@ export class AgentRuntime {messages: [],status: 'idle',stepCount: 0,- toolManifestMap: {},usage: AgentRuntime.createDefaultUsage(),// User provided values override defaults...(partialState || { operationId: '' }),diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 10dea5ca552..6953cb1c1fa 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -15,6 +15,7 @@ import type {InstructionExecutor,} from '../types';import { extractActivatedSkillsFromMessages, extractTodosFromMessages } from '../utils';+import { selectToolManifestMap, selectToolSourceMap } from '../utils/operationToolSet';import { settleAbortedToolRows } from './abortedToolRows';const TOOL_EXECUTION_PHASE = 'tool_execution';@@ -100,7 +101,7 @@ const requireToolTransport = (host: AgentRuntimeHost) => {const toolNameOf = (tool: ChatToolPayload) => `${tool.identifier}/${tool.apiName}`;const resolveToolSource = (state: AgentState, tool: ChatToolPayload): string | undefined =>- state.operationToolSet?.sourceMap?.[tool.identifier] ?? state.toolSourceMap?.[tool.identifier];+ selectToolSourceMap(state)[tool.identifier];const parseToolArgs = (tool: ChatToolPayload): Record<string, unknown> => {try {@@ -121,7 +122,7 @@ const parseToolArgs = (tool: ChatToolPayload): Record<string, unknown> => {};const buildEffectiveManifestMap = (state: AgentState): Record<string, any> => ({- ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),+ ...selectToolManifestMap(state),...Object.fromEntries((state.activatedStepTools ?? []).filter((activation) => activation.manifest)diff --git a/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.ts b/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.tsindex 95b6f8d4e02..d73c2f01c91 100644--- a/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.ts+++ b/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.ts@@ -169,7 +169,6 @@ export class GroupOrchestrationRuntime {messages: [],status: 'idle',stepCount: 0,- toolManifestMap: {},usage: {humanInteraction: {approvalRequests: 0,diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex 4e724722ef4..d799245eabf 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -463,14 +463,25 @@ export interface AgentState {counts: Record<string, number>;};- /** Tool executor map for routing tool execution between server and client */+ /**+ * Legacy mirrors of {@link OperationToolSet}, kept only so operations that+ * started before `operationToolSet` existed still resolve their tools. Nothing+ * writes them: the maps are the heaviest thing on the state and it is+ * re-serialized at every step boundary. Read through `selectToolManifestMap`+ * and friends, which prefer the slot; `normalizeAgentState` lifts these into it+ * on load.+ *+ * @deprecated Use `operationToolSet`.+ */toolExecutorMap?: Record<string, ToolExecutor>;- toolManifestMap: Record<string, any>;+ /** @deprecated Use `operationToolSet.manifestMap`. */+ toolManifestMap?: Record<string, any>;+ /** @deprecated Use `operationToolSet.tools`. */tools?: any[];- /** Tool source map for routing tool execution to correct handler */+ /** @deprecated Use `operationToolSet.sourceMap`. */toolSourceMap?: Record<string, ToolSource>;/**diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.tsindex 6998b900fcb..ca5539fb5ff 100644--- a/packages/agent-runtime/src/utils/index.ts+++ b/packages/agent-runtime/src/utils/index.ts@@ -1,6 +1,7 @@export * from './llmErrorClassifier';export * from './messageSelectors';export * from './normalizeAgentState';+export * from './operationToolSet';export * from './replay';export * from './runtimeRetry';export * from './status';diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts b/packages/agent-runtime/src/utils/normalizeAgentState.test.tsindex 1c07f27c8b9..243d23996bd 100644--- a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts+++ b/packages/agent-runtime/src/utils/normalizeAgentState.test.ts@@ -209,6 +209,56 @@ describe('normalizeAgentState', () => {expect(normalized.metadata).toEqual({});});+ it('lifts the legacy top-level tool mirrors into the operation slot', () => {+ const manifestMap = { 'lobe-web-browsing': { identifier: 'lobe-web-browsing' } };+ const state = {+ ...baseState(),+ toolExecutorMap: { 'lobe-web-browsing': 'server' },+ toolManifestMap: manifestMap,+ toolSourceMap: { 'lobe-web-browsing': 'builtin' },+ tools: [{ function: { name: 'search' }, type: 'function' }],+ } as unknown as AgentState;++ const normalized = normalizeAgentState(state);++ expect(normalized.operationToolSet).toEqual({+ enabledToolIds: [],+ executorMap: { 'lobe-web-browsing': 'server' },+ manifestMap,+ sourceMap: { 'lobe-web-browsing': 'builtin' },+ tools: [{ function: { name: 'search' }, type: 'function' }],+ });+ // The blob no longer carries the tool set twice.+ expect('toolManifestMap' in normalized).toBe(false);+ expect('toolSourceMap' in normalized).toBe(false);+ expect('toolExecutorMap' in normalized).toBe(false);+ expect('tools' in normalized).toBe(false);+ // Input is not mutated.+ expect(state.toolManifestMap).toBe(manifestMap);+ });++ it('keeps the operation slot over the legacy tool mirrors', () => {+ const state = {+ ...baseState(),+ operationToolSet: {+ enabledToolIds: ['lobe-web-browsing'],+ executorMap: {},+ manifestMap: { 'lobe-web-browsing': { identifier: 'lobe-web-browsing' } },+ sourceMap: {},+ tools: [],+ },+ toolManifestMap: { stale: { identifier: 'stale' } },+ } as unknown as AgentState;++ const normalized = normalizeAgentState(state);++ expect(normalized.operationToolSet?.manifestMap).toEqual({+ 'lobe-web-browsing': { identifier: 'lobe-web-browsing' },+ });+ expect(normalized.operationToolSet?.enabledToolIds).toEqual(['lobe-web-browsing']);+ expect('toolManifestMap' in normalized).toBe(false);+ });+it('lifts a partial device binding without inventing an id', () => {const state = {...baseState(),diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.ts b/packages/agent-runtime/src/utils/normalizeAgentState.tsindex b882e9d8866..16a53f02ecb 100644--- a/packages/agent-runtime/src/utils/normalizeAgentState.ts+++ b/packages/agent-runtime/src/utils/normalizeAgentState.ts@@ -62,6 +62,30 @@ const LEGACY_KEY_PATHS: Record<string, readonly string[]> = {deviceSystemInfo: ['binding', 'device', 'systemInfo'],};+/**+ * Top-level keys that mirrored a slot instead of hiding in `metadata`. The tool+ * set used to be written twice β once as `operationToolSet`, once as these four+ * β which doubled the heaviest part of the blob on every step. They are lifted+ * into the slot and dropped.+ */+const LEGACY_MIRROR_PATHS: Record<string, readonly string[]> = {+ toolExecutorMap: ['operationToolSet', 'executorMap'],+ toolManifestMap: ['operationToolSet', 'manifestMap'],+ toolSourceMap: ['operationToolSet', 'sourceMap'],+ tools: ['operationToolSet', 'tools'],+};++const LEGACY_MIRROR_KEYS = Object.keys(LEGACY_MIRROR_PATHS);++/**+ * An empty mirror carries no tool set, so lifting it would only rewrite the blob+ * for nothing (and would hide a populated slot behind an empty default).+ */+const isPopulatedMirror = (value: unknown) =>+ Array.isArray(value)+ ? value.length > 0+ : !!value && typeof value === 'object' && Object.keys(value).length > 0;+const LEGACY_KEYS = Object.keys(LEGACY_KEY_PATHS);const isPresent = (record: Record<string, unknown>, key: string) =>@@ -96,22 +120,51 @@ const setIfAbsent = (root: Record<string, unknown>, path: readonly string[], val* (the in-flight state blob has a hard 10MB ceiling). `null` legacy values* are treated as absent: the slots use `undefined` only. Returns the same* object when nothing needed lifting.+ *+ * The run's tool set is lifted the same way, from the four top-level mirrors it+ * used to be written to alongside `operationToolSet` β see+ * {@link LEGACY_MIRROR_PATHS}.*/export const normalizeAgentState = <T extends AgentState>(state: T): T => {const metadata = state.metadata;- if (!metadata || !LEGACY_KEYS.some((key) => Object.prototype.hasOwnProperty.call(metadata, key)))- return state;+ const hasLegacyMetadata =+ !!metadata && LEGACY_KEYS.some((key) => Object.prototype.hasOwnProperty.call(metadata, key));+ const mirrorKeys = LEGACY_MIRROR_KEYS.filter(+ (key) =>+ isPresent(state as unknown as Record<string, unknown>, key) &&+ isPopulatedMirror((state as unknown as Record<string, unknown>)[key]),+ );+ if (!hasLegacyMetadata && mirrorKeys.length === 0) return state;const next = { ...state } as Record<string, unknown>;- for (const [legacyKey, path] of Object.entries(LEGACY_KEY_PATHS)) {- if (isPresent(metadata, legacyKey)) setIfAbsent(next, path, metadata[legacyKey]);++ if (metadata && hasLegacyMetadata) {+ for (const [legacyKey, path] of Object.entries(LEGACY_KEY_PATHS)) {+ if (isPresent(metadata, legacyKey)) setIfAbsent(next, path, metadata[legacyKey]);+ }++ const strippedMetadata: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(metadata)) {+ if (!LEGACY_KEYS.includes(key)) strippedMetadata[key] = value;+ }+ next.metadata = strippedMetadata;}- const strippedMetadata: Record<string, unknown> = {};- for (const [key, value] of Object.entries(metadata)) {- if (!LEGACY_KEYS.includes(key)) strippedMetadata[key] = value;+ if (mirrorKeys.length > 0) {+ for (const key of mirrorKeys) {+ setIfAbsent(+ next,+ LEGACY_MIRROR_PATHS[key],+ (state as unknown as Record<string, unknown>)[key],+ );+ delete next[key];+ }+ // `setIfAbsent` cloned the slot on the way in, so this default cannot reach+ // the caller's state. A pre-slot blob never had the enabled ids, and the step+ // delta then starts from nothing β how those operations already behaved.+ const toolSet = next.operationToolSet as Record<string, unknown>;+ if (toolSet.enabledToolIds === undefined) toolSet.enabledToolIds = [];}- next.metadata = strippedMetadata;return next as T;};diff --git a/packages/agent-runtime/src/utils/operationToolSet.ts b/packages/agent-runtime/src/utils/operationToolSet.tsnew file mode 100644index 00000000000..993c6dfa458--- /dev/null+++ b/packages/agent-runtime/src/utils/operationToolSet.ts@@ -0,0 +1,52 @@+import type { OperationToolSet } from '@lobechat/context-engine';++import type { AgentState } from '../types';++/** Every place a run's tool set can be found on the state. */+type ToolSetCarrier = Pick<+ AgentState,+ 'operationToolSet' | 'toolExecutorMap' | 'toolManifestMap' | 'toolSourceMap' | 'tools'+>;++/**+ * Read the run's tool set from the operation slot.+ *+ * The slot is the only copy a host writes: manifest maps are the heaviest thing+ * on the state (a full manifest carries every API schema and system role), and+ * the state is re-serialized into Redis at every step boundary, so keeping a+ * second copy doubled that cost for nothing.+ *+ * Operations that started before the slot existed carry the four maps at the top+ * level instead. `normalizeAgentState` lifts those into the slot when the blob is+ * loaded; these readers accept them directly too, so an in-memory state that+ * never passed the load path still resolves its tools.+ */+export const selectRunTools = (state: Partial<ToolSetCarrier>): any[] | undefined =>+ state.operationToolSet?.tools ?? state.tools;++export const selectToolManifestMap = (state: Partial<ToolSetCarrier>): Record<string, any> =>+ state.operationToolSet?.manifestMap ?? state.toolManifestMap ?? {};++export const selectToolSourceMap = (+ state: Partial<ToolSetCarrier>,+): NonNullable<AgentState['toolSourceMap']> =>+ state.operationToolSet?.sourceMap ?? state.toolSourceMap ?? {};++export const selectToolExecutorMap = (+ state: Partial<ToolSetCarrier>,+): NonNullable<AgentState['toolExecutorMap']> =>+ state.operationToolSet?.executorMap ?? state.toolExecutorMap ?? {};++/**+ * The whole set as one struct, for callers that hand it to the resolvers.+ * A legacy state has no `enabledToolIds` anywhere β it predates the slot β so+ * the step delta starts from nothing, exactly as the old inline fallback did.+ */+export const selectOperationToolSet = (state: Partial<ToolSetCarrier>): OperationToolSet =>+ state.operationToolSet ?? {+ enabledToolIds: [],+ executorMap: selectToolExecutorMap(state),+ manifestMap: selectToolManifestMap(state),+ sourceMap: selectToolSourceMap(state),+ tools: selectRunTools(state) ?? [],+ };diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.tsindex a9a026118ed..6e1453704fb 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts@@ -1322,14 +1322,11 @@ describe('StreamingExecutor actions', () => {undefined,expect.objectContaining({ executionEnv: 'local' }),);- const readFile = state.toolManifestMap['lobe-local-system']?.api.find(- (api: LobeChatPluginApi) => api.name === 'readFile',- );+ const localSystem = state.operationToolSet?.manifestMap['lobe-local-system'];+ const readFile = localSystem?.api.find((api: LobeChatPluginApi) => api.name === 'readFile');expect(readFile?.description).toContain('base64');- expect(state.toolManifestMap['lobe-local-system']?.systemRole).toContain(- 'Image files are uploaded as visual tool results',- );+ expect(localSystem?.systemRole).toContain('Image files are uploaded as visual tool results');});it('should not inject page editor context outside page scope', () => {@@ -1844,8 +1841,9 @@ describe('StreamingExecutor actions', () => {disableTools: true,});- // toolManifestMap should be empty when disableTools is true- expect(state.toolManifestMap).toEqual({});+ // The run's tool set lives on the operation slot, and it holds nothing.+ expect(state.operationToolSet?.manifestMap).toEqual({});+ expect(state.operationToolSet?.tools).toEqual([]);});it('should return empty tools in agentConfig when disableTools is true', async () => {diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 9950292c893..564ca4094ec 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -361,13 +361,13 @@ export class StreamingExecutorActionImpl {},modelRuntimeConfig,operationId: operationId ?? agentId,+ // Single copy of the run's tool set, like the server's state.operationToolSet: {enabledToolIds,manifestMap: toolManifestMap,sourceMap: {},tools: toolsDetailed.tools ?? [],},- toolManifestMap,userInterventionConfig,});const state: AgentState = {