🤯 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-runtime): leave tool-set copies out of the per-step state blob (#23170)
Arvin Xu60cccaa69f2f
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.tsindex 3508be9b73d..8f9e1cc9116 100644--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts@@ -12,6 +12,7 @@ import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlaimport { hasNonPersistedMessage } from './messagePersistence';import { getAgentRuntimeRedisClient } from './redis';+import { restoreSlimState, slimStateForPersist } from './slimAgentState';const log = debug('lobe-server:agent-runtime:agent-state-manager');@@ -123,7 +124,28 @@ const STRIP_FLAG_CACHE_TTL_MS = 5000;const STRIP_FLAG_CACHE_MAX = 1024;/**- * Resolved values, keyed by owner ('' for the global value).+ * Whether a persisted blob may also leave out the copies `slimStateForPersist`+ * drops (see `slimAgentState.ts`): runtime flag `agent_runtime_slim_state`,+ * overridden by `AGENT_RUNTIME_SLIM_STATE` (`0` kill switch, `1` force on).+ * Same rollout contract as the tool set: the load path restores them+ * unconditionally, so this build must be everywhere before the flag is+ * published, and flipping it either way is safe for operations in flight.+ */+interface PersistOptions {+ slim: boolean;+ stripToolSet: boolean;+}++const envOverride = (name: string): boolean | undefined => {+ const value = process.env[name];+ if (value === '0') return false;+ if (value === '1') return true;+ return undefined;+};++/**+ * Resolved values, keyed by owner ('' for the global value). One provider read+ * resolves both flags.** `getMergedFeatureFlags` always reads the per-user override record when it is* given a user id, and that provider does not cache a missing record@@ -133,49 +155,62 @@ const STRIP_FLAG_CACHE_MAX = 1024;* back because stripping stays inline. This cache bounds the lookup to once per* owner per TTL.*/-const stripFlagCache = new Map<string, { expiresAt: number; value: boolean }>();+const persistFlagCache = new Map<string, { expiresAt: number; value: PersistOptions }>();-/** Clear the strip-flag resolution cache (for testing). */+/** Clear the persistence-flag resolution cache (for testing). */export const resetStripOperationToolsetCache = () => {- stripFlagCache.clear();+ persistFlagCache.clear();};-const resolveStripOperationToolset = async (userId?: string): Promise<boolean> => {- const override = process.env.AGENT_RUNTIME_STRIP_OPERATION_TOOLSET;- if (override === '0') return false;- if (override === '1') return true;-+const resolveFlags = async (userId?: string): Promise<PersistOptions> => {// Owners without a user id all resolve the global value, so they share a key.const cacheKey = userId ?? '';- const cached = stripFlagCache.get(cacheKey);+ const cached = persistFlagCache.get(cacheKey);if (cached) {if (cached.expiresAt > Date.now()) return cached.value;- stripFlagCache.delete(cacheKey);+ persistFlagCache.delete(cacheKey);}try {const flags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);- const enabled = flags.enableStripOperationToolset === true;+ const value: PersistOptions = {+ slim: flags.enableSlimAgentState === true,+ stripToolSet: flags.enableStripOperationToolset === true,+ };// Evict the oldest entry instead of growing with the number of owners.- if (stripFlagCache.size >= STRIP_FLAG_CACHE_MAX) {- const oldestKey = stripFlagCache.keys().next().value;- if (oldestKey !== undefined) stripFlagCache.delete(oldestKey);+ if (persistFlagCache.size >= STRIP_FLAG_CACHE_MAX) {+ const oldestKey = persistFlagCache.keys().next().value;+ if (oldestKey !== undefined) persistFlagCache.delete(oldestKey);}- stripFlagCache.set(cacheKey, {- expiresAt: Date.now() + STRIP_FLAG_CACHE_TTL_MS,- value: enabled,- });+ persistFlagCache.set(cacheKey, { expiresAt: Date.now() + STRIP_FLAG_CACHE_TTL_MS, value });- return enabled;+ return value;} catch (error) {- // Deliberately not cached: a transient read failure must not pin the flag+ // Deliberately not cached: a transient read failure must not pin the flags// off for a whole TTL.- log('Failed to resolve agent_runtime_strip_operation_toolset, keeping inline: %O', error);- return false;+ log('Failed to resolve agent state persistence flags, keeping inline: %O', error);+ return { slim: false, stripToolSet: false };}};+const resolvePersistOptions = async (userId?: string): Promise<PersistOptions> => {+ const stripOverride = envOverride('AGENT_RUNTIME_STRIP_OPERATION_TOOLSET');+ // The tool set kill switch restores the fully inline blob, so it turns+ // slimming off too unless that is forced on separately.+ const slimOverride =+ envOverride('AGENT_RUNTIME_SLIM_STATE') ?? (stripOverride === false ? false : undefined);+ // Both pinned by env: never touch the flag provider.+ if (stripOverride !== undefined && slimOverride !== undefined) {+ return { slim: slimOverride, stripToolSet: stripOverride };+ }+ const flags = await resolveFlags(userId);+ return {+ slim: slimOverride ?? flags.slim,+ stripToolSet: stripOverride ?? flags.stripToolSet,+ };+};+export interface StepResult {events?: AgentEvent[];executionTime: number;@@ -274,18 +309,23 @@ export class AgentStateManager {* (group-member supervisor turns); the size win is forgone to avoid losing* the prompt.*/- private serializeStateForPersist(state: AgentState, stripToolSet: boolean): string {+ private serializeStateForPersist(state: AgentState, options: PersistOptions): string {+ const { slim, stripToolSet } = options;+ // Copies of the tool set are dropped against the full state, before the tool+ // set itself leaves the blob; `restoreSlimState` rebuilds them after it is+ // re-attached on load.+ const source = slim ? slimStateForPersist(state) : state;// `operationToolSet` is externalized to its own key (see// `externalizeToolSet`) and re-attached on load, so it never travels in the// blob — once stripping is enabled. Until then the blob keeps its inline// copy so a previous-build worker can still execute the operation (see- // `resolveStripOperationToolset`). It is immutable after creation, so a single+ // `resolvePersistOptions`). It is immutable after creation, so a single// write per operation replaces re-serializing ~300–400 KB of tool schemas// at every step.- const { operationToolSet: _toolSet, ...withoutToolSet } = state as AgentState & {+ const { operationToolSet: _toolSet, ...withoutToolSet } = source as AgentState & {operationToolSet?: unknown;};- const persistable = (stripToolSet ? withoutToolSet : state) as AgentState & {+ const persistable = (stripToolSet ? withoutToolSet : source) as AgentState & {messages?: unknown;operationToolSet?: unknown;};@@ -350,9 +390,10 @@ export class AgentStateManager {const stateKey = `${this.STATE_PREFIX}:${operationId}`;try {- const stripToolSet = await resolveStripOperationToolset(state.origin?.userId);+ const persistOptions = await resolvePersistOptions(state.origin?.userId);+ const { stripToolSet } = persistOptions;if (stripToolSet) await this.externalizeToolSet(operationId, state);- const serializedState = this.serializeStateForPersist(state, stripToolSet);+ const serializedState = this.serializeStateForPersist(state, persistOptions);await this.redis.setex(stateKey, this.DEFAULT_TTL, serializedState);// Keep the externalized tool set alive in lockstep with the blob so a// long run never loads a stripped blob whose tool set has expired.@@ -392,6 +433,9 @@ export class AgentStateManager {// that context in `metadata`; lift it once here so readers see one shape.const state = normalizeAgentState(JSON.parse(serializedState) as AgentState);await this.rehydrateToolSet(operationId, state);+ // Unconditional, like the tool set: a blob saved with slimming on loads the+ // same whatever the flag says now.+ restoreSlimState(state);log('[%s] Loaded state (step %d)', operationId, state.stepCount);return state;@@ -442,7 +486,8 @@ export class AgentStateManager {try {// Write-once before opening the pipeline; the inline loop warms the cache// on its first step and every later step skips the tool-set write.- const stripToolSet = await resolveStripOperationToolset(stepResult.newState.origin?.userId);+ const persistOptions = await resolvePersistOptions(stepResult.newState.origin?.userId);+ const { stripToolSet } = persistOptions;if (stripToolSet) await this.externalizeToolSet(operationId, stepResult.newState);const pipeline = this.redis.multi();@@ -452,7 +497,7 @@ export class AgentStateManager {pipeline.setex(stateKey,this.DEFAULT_TTL,- this.serializeStateForPersist(stepResult.newState, stripToolSet),+ this.serializeStateForPersist(stepResult.newState, persistOptions),);// Refresh the externalized tool set's TTL alongside the blob.if (stripToolSet) pipeline.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.tsindex 19396a5190e..2474f47e1ad 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts@@ -402,11 +402,13 @@ describe('AgentStateManager', () => {beforeEach(() => {delete process.env[STRIP_FLAG];+ delete process.env.AGENT_RUNTIME_SLIM_STATE;});afterAll(() => {if (originalFlag === undefined) delete process.env[STRIP_FLAG];else process.env[STRIP_FLAG] = originalFlag;+ delete process.env.AGENT_RUNTIME_SLIM_STATE;});it('strips the saveAgentState blob when the flag is on, resolved for the owner', async () => {@@ -514,6 +516,7 @@ describe('AgentStateManager', () => {it("env '1' forces stripping without consulting the flag provider", async () => {process.env[STRIP_FLAG] = '1';+ process.env.AGENT_RUNTIME_SLIM_STATE = '0';const op = 'op-ff-force';await stateManager.saveAgentState(op, {@@ -629,6 +632,166 @@ describe('AgentStateManager', () => {});});+ describe('slim state (agent_runtime_slim_state)', () => {+ const manifest = { api: [{ name: 'x' }], identifier: 'x' };+ const toolSet = {+ enabledToolIds: ['x'],+ manifestMap: { x: manifest },+ sourceMap: {},+ tools: [{ function: { name: 'x' } }],+ };+ const expertise = { renderedContext: 'expert' };+ const origin = { userId: 'user-slim' };+ const buildState = () => ({+ activatedStepTools: [{ activatedAtStep: 1, id: 'x', manifest, source: 'discovery' }],+ expertise,+ initialContext: { payload: { tools: toolSet.tools }, phase: 'user_input' },+ operationToolSet: toolSet,+ origin,+ status: 'running',+ stepCount: 2,+ world: { expertise },+ });+ const ENVS = ['AGENT_RUNTIME_STRIP_OPERATION_TOOLSET', 'AGENT_RUNTIME_SLIM_STATE'];++ const mockFlags = (flags: { slim: boolean; strip: boolean }) =>+ vi.mocked(getServerFeatureFlagsStateFromRuntimeConfig).mockResolvedValue({+ enableSlimAgentState: flags.slim,+ enableStripOperationToolset: flags.strip,+ } as any);++ const stepBlob = (op: string) =>+ JSON.parse(+ pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`)![2],+ );++ beforeEach(() => {+ for (const name of ENVS) delete process.env[name];+ });++ afterAll(() => {+ for (const name of ENVS) delete process.env[name];+ });++ it('leaves the copies out of the step blob when the flag is on', async () => {+ mockFlags({ slim: true, strip: true });+ const op = 'op-slim-on';++ await stateManager.saveStepResult(op, {+ executionTime: 1,+ newState: buildState(),+ stepIndex: 2,+ } as any);++ const blob = stepBlob(op);+ expect(blob.initialContext.payload.tools).toBeUndefined();+ expect(blob.activatedStepTools[0].manifest).toBeUndefined();+ expect(blob.expertise).toBeUndefined();+ expect(blob.world.expertise).toEqual(expertise);+ expect(blob.__slim).toEqual({ activatedManifests: [0], expertise: true, payloadTools: true });+ });++ it('loads a slimmed blob back to the full state', async () => {+ mockFlags({ slim: true, strip: true });+ const op = 'op-slim-load';+ await stateManager.saveStepResult(op, {+ executionTime: 1,+ newState: buildState(),+ stepIndex: 2,+ } as any);+ const stored = pipelineMock.setex.mock.calls.find(+ (c) => c[0] === `agent_runtime_state:${op}`,+ )![2];+ redisMock.get.mockImplementation(async (key: string) =>+ key === `agent_runtime_toolset:${op}` ? JSON.stringify(toolSet) : stored,+ );++ const loaded = await stateManager.loadAgentState(op);++ expect(loaded).toMatchObject(JSON.parse(JSON.stringify(buildState())));+ expect((loaded as any).__slim).toBeUndefined();+ });++ it('slims with the tool set kept inline too', async () => {+ mockFlags({ slim: true, strip: false });+ const op = 'op-slim-inline-toolset';++ await stateManager.saveStepResult(op, {+ executionTime: 1,+ newState: buildState(),+ stepIndex: 2,+ } as any);++ const blob = stepBlob(op);+ expect(blob.operationToolSet).toEqual(toolSet);+ expect(blob.initialContext.payload.tools).toBeUndefined();+ redisMock.get.mockResolvedValueOnce(JSON.stringify(blob));+ const loaded = await stateManager.loadAgentState(op);+ expect((loaded as any).initialContext.payload.tools).toEqual(toolSet.tools);+ });++ it('keeps the blob unchanged when the flag is off', async () => {+ mockFlags({ slim: false, strip: true });+ const op = 'op-slim-off';+ const { operationToolSet: _toolSet, ...expected } = buildState();++ await stateManager.saveStepResult(op, {+ executionTime: 1,+ newState: buildState(),+ stepIndex: 2,+ } as any);++ expect(stepBlob(op)).toEqual(JSON.parse(JSON.stringify(expected)));+ });++ it('the tool set kill switch turns slimming off without consulting the provider', async () => {+ process.env.AGENT_RUNTIME_STRIP_OPERATION_TOOLSET = '0';+ mockFlags({ slim: true, strip: true });+ const op = 'op-slim-kill';++ await stateManager.saveStepResult(op, {+ executionTime: 1,+ newState: buildState(),+ stepIndex: 2,+ } as any);++ expect(getServerFeatureFlagsStateFromRuntimeConfig).not.toHaveBeenCalled();+ expect(stepBlob(op)).toEqual(JSON.parse(JSON.stringify(buildState())));+ });++ it("AGENT_RUNTIME_SLIM_STATE='0' overrides an enabled flag", async () => {+ process.env.AGENT_RUNTIME_SLIM_STATE = '0';+ mockFlags({ slim: true, strip: true });+ const op = 'op-slim-env-off';++ await stateManager.saveStepResult(op, {+ executionTime: 1,+ newState: buildState(),+ stepIndex: 2,+ } as any);++ const blob = stepBlob(op);+ expect(blob.__slim).toBeUndefined();+ expect(blob.initialContext.payload.tools).toEqual(toolSet.tools);+ expect(blob.operationToolSet).toBeUndefined();+ });++ it('resolves both flags with one provider read per owner', async () => {+ mockFlags({ slim: true, strip: true });+ const op = 'op-slim-one-read';++ for (const stepIndex of [2, 3]) {+ await stateManager.saveStepResult(op, {+ executionTime: 1,+ newState: buildState(),+ stepIndex,+ } as any);+ }++ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledTimes(1);+ });+ });+describe('step execution lock', () => {it('claims an operation-scoped lock with the provided owner token', async () => {redisMock.eval.mockResolvedValue(1);diff --git a/apps/server/src/modules/AgentRuntime/__tests__/slimAgentState.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/slimAgentState.test.tsnew file mode 100644index 00000000000..0fb609865e0--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/__tests__/slimAgentState.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from 'vitest';++import { restoreSlimState, SLIM_MARKER_KEY, slimStateForPersist } from '../slimAgentState';++const manifestA = { api: [{ name: 'a' }], identifier: 'a' };+const manifestB = { api: [{ name: 'b' }], identifier: 'b' };+const toolSet = {+ enabledToolIds: ['a', 'b'],+ manifestMap: { a: manifestA, b: manifestB },+ sourceMap: {},+ tools: [{ function: { name: 'a' } }, { function: { name: 'b' } }],+};+const expertise = { renderedContext: 'expert', version: 1 };++const buildState = () => ({+ activatedStepTools: [+ { activatedAtStep: 1, id: 'a', manifest: structuredClone(manifestA), source: 'discovery' },+ { activatedAtStep: 2, id: 'c', manifest: { api: [], identifier: 'c' }, source: 'discovery' },+ { activatedAtStep: 3, id: 'b', source: 'discovery' },+ ],+ expertise: structuredClone(expertise),+ initialContext: {+ payload: { message: [{ content: 'hi' }], tools: structuredClone(toolSet.tools) },+ phase: 'user_input',+ },+ operationToolSet: toolSet,+ status: 'running',+ world: { expertise: structuredClone(expertise) },+});++/** What the persistence layer does: JSON round-trip, then restore. */+const roundTrip = (state: object) => {+ const loaded = JSON.parse(JSON.stringify(slimStateForPersist(state)));+ restoreSlimState(loaded);+ return loaded;+};++describe('slimStateForPersist', () => {+ it('drops the copies equal to their source and records them', () => {+ const slim = slimStateForPersist(buildState()) as any;++ expect(slim.initialContext.payload.tools).toBeUndefined();+ expect(slim.initialContext.payload.message).toEqual([{ content: 'hi' }]);+ expect(slim.activatedStepTools[0]).toEqual({+ activatedAtStep: 1,+ id: 'a',+ source: 'discovery',+ });+ // Not in the manifest map: stays inline.+ expect(slim.activatedStepTools[1].manifest).toEqual({ api: [], identifier: 'c' });+ expect(slim.expertise).toBeUndefined();+ expect(slim[SLIM_MARKER_KEY]).toEqual({+ activatedManifests: [0],+ expertise: true,+ payloadTools: true,+ });+ });++ it('never mutates the live state', () => {+ const state = buildState();+ const before = JSON.stringify(state);++ slimStateForPersist(state);++ expect(JSON.stringify(state)).toBe(before);+ });++ it('keeps a copy that differs from its source', () => {+ const state = buildState();+ state.initialContext.payload.tools = [{ function: { name: 'other' } }];+ state.expertise = { renderedContext: 'stale', version: 0 };+ state.activatedStepTools[0].manifest = { api: [], identifier: 'a-old' } as any;++ const slim = slimStateForPersist(state) as any;++ expect(slim.initialContext.payload.tools).toEqual([{ function: { name: 'other' } }]);+ expect(slim.expertise).toEqual({ renderedContext: 'stale', version: 0 });+ expect(slim.activatedStepTools[0].manifest).toEqual({ api: [], identifier: 'a-old' });+ expect(slim[SLIM_MARKER_KEY]).toBeUndefined();+ });++ it('returns the state itself when there is nothing to drop', () => {+ const state = { status: 'running', stepCount: 1 };++ expect(slimStateForPersist(state)).toBe(state);+ });++ it('keeps everything without a tool set to restore from', () => {+ const { operationToolSet: _toolSet, ...state } = buildState();++ const slim = slimStateForPersist(state) as any;++ expect(slim.initialContext.payload.tools).toHaveLength(2);+ expect(slim.activatedStepTools[0].manifest).toEqual(manifestA);+ // Expertise has its own source (`world.expertise`).+ expect(slim[SLIM_MARKER_KEY]).toEqual({ expertise: true });+ });+});++describe('restoreSlimState', () => {+ it('restores the state a reader saw before the save', () => {+ const state = buildState();++ expect(roundTrip(state)).toEqual(JSON.parse(JSON.stringify(state)));+ });++ it('does not add a manifest an entry never had', () => {+ const loaded = roundTrip(buildState());++ expect(loaded.activatedStepTools[2]).toEqual({+ activatedAtStep: 3,+ id: 'b',+ source: 'discovery',+ });+ });++ it('restores fresh copies, not references to their source', () => {+ const loaded = roundTrip(buildState());++ expect(loaded.initialContext.payload.tools).not.toBe(loaded.operationToolSet.tools);+ expect(loaded.activatedStepTools[0].manifest).not.toBe(loaded.operationToolSet.manifestMap.a);+ expect(loaded.expertise).not.toBe(loaded.world.expertise);+ });++ it('leaves a field absent when its source is gone', () => {+ const loaded = JSON.parse(JSON.stringify(slimStateForPersist(buildState())));+ delete loaded.operationToolSet;++ restoreSlimState(loaded);++ expect(loaded.initialContext.payload.tools).toBeUndefined();+ expect(loaded.activatedStepTools[0].manifest).toBeUndefined();+ expect(loaded[SLIM_MARKER_KEY]).toBeUndefined();+ });++ it('is a no-op on a blob saved without slimming', () => {+ const state = JSON.parse(JSON.stringify(buildState()));+ const before = JSON.stringify(state);++ restoreSlimState(state);++ expect(JSON.stringify(state)).toBe(before);+ });+});diff --git a/apps/server/src/modules/AgentRuntime/slimAgentState.ts b/apps/server/src/modules/AgentRuntime/slimAgentState.tsnew file mode 100644index 00000000000..ab649203678--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/slimAgentState.ts@@ -0,0 +1,114 @@+/**+ * Leave copies out of the persisted agent state blob, and put them back on load.+ *+ * The blob is rewritten at every step, so every byte in it is paid for once per+ * step on the write and again on the next step's read. Three parts of it are+ * exact copies of data the operation already holds elsewhere:+ *+ * - `initialContext.payload.tools` is the same array as `operationToolSet.tools`+ * (`operationPrep` hands both the discovery result);+ * - each `activatedStepTools[i].manifest` is copied from+ * `operationToolSet.manifestMap[id]` when the tool is activated;+ * - the deprecated top-level `expertise` mirrors `world.expertise`.+ *+ * {@link slimStateForPersist} drops a copy only when it is equal to its source,+ * and records what it dropped under {@link SLIM_MARKER_KEY};+ * {@link restoreSlimState} reads that record and rebuilds exactly those fields,+ * so the state a reader sees after load is the same as before the save. A copy+ * that differs from its source stays inline. The source must already be on the+ * state: restore runs after the tool set is re-attached.+ */++/** Persist-only record of the copies left out. Never present on a live state. */+export const SLIM_MARKER_KEY = '__slim';++interface SlimMarker {+ /** Indices into `activatedStepTools` whose `manifest` was left out. */+ activatedManifests?: number[];+ /** The top-level `expertise` was left out. */+ expertise?: true;+ /** `initialContext.payload.tools` was left out. */+ payloadTools?: true;+}++type LooseState = Record<string, any>;++const sameJson = (a: unknown, b: unknown) =>+ a !== undefined && b !== undefined && JSON.stringify(a) === JSON.stringify(b);++/**+ * Return a shallow copy of `state` without the copies listed above, plus the+ * marker. Objects along a changed path are cloned; `state` is never mutated.+ * Returns `state` itself when nothing was left out.+ */+export const slimStateForPersist = <T extends object>(state: T): T => {+ const source = state as LooseState;+ const toolSet = source.operationToolSet;+ const marker: SlimMarker = {};+ const next: LooseState = { ...source };++ const payload = source.initialContext?.payload;+ if (payload && sameJson(payload.tools, toolSet?.tools)) {+ const { tools: _tools, ...payloadRest } = payload;+ next.initialContext = { ...source.initialContext, payload: payloadRest };+ marker.payloadTools = true;+ }++ const activated = source.activatedStepTools;+ if (Array.isArray(activated) && toolSet?.manifestMap) {+ const indices: number[] = [];+ const slimmed = activated.map((entry: LooseState, index: number) => {+ if (!entry?.manifest || !sameJson(entry.manifest, toolSet.manifestMap[entry.id])) {+ return entry;+ }+ indices.push(index);+ const { manifest: _manifest, ...rest } = entry;+ return rest;+ });+ if (indices.length > 0) {+ next.activatedStepTools = slimmed;+ marker.activatedManifests = indices;+ }+ }++ if (source.expertise !== undefined && sameJson(source.expertise, source.world?.expertise)) {+ delete next.expertise;+ marker.expertise = true;+ }++ if (Object.keys(marker).length === 0) return state;+ next[SLIM_MARKER_KEY] = marker;+ return next as T;+};++/**+ * Rebuild the fields {@link slimStateForPersist} left out, in place, and drop+ * the marker. Each restored value is a fresh copy, as a JSON parse of the full+ * blob would have produced, so mutating it never reaches its source. A field+ * whose source is gone (the tool set key expired) stays absent — the same+ * fallback a missing tool set already gets.+ */+export const restoreSlimState = (state: object): void => {+ const target = state as LooseState;+ const marker = target[SLIM_MARKER_KEY] as SlimMarker | undefined;+ if (!marker) return;+ delete target[SLIM_MARKER_KEY];++ const toolSet = target.operationToolSet;++ if (marker.payloadTools && target.initialContext?.payload && toolSet?.tools) {+ target.initialContext.payload.tools = structuredClone(toolSet.tools);+ }++ if (marker.activatedManifests && Array.isArray(target.activatedStepTools)) {+ for (const index of marker.activatedManifests) {+ const entry = target.activatedStepTools[index];+ const manifest = entry && toolSet?.manifestMap?.[entry.id];+ if (manifest) entry.manifest = structuredClone(manifest);+ }+ }++ if (marker.expertise && target.world?.expertise !== undefined) {+ target.expertise = structuredClone(target.world.expertise);+ }+};diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex fa57afaa11b..eb5bbb7f733 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -533,6 +533,25 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mappedState.enableDashboard).toBe(false);});+ describe('agent_runtime_slim_state', () => {+ it('is off by default', () => {+ expect(DEFAULT_FEATURE_FLAGS.agent_runtime_slim_state).toBe(false);+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableSlimAgentState).toBe(+ false,+ );+ });++ it('maps true and a user allowlist', () => {+ expect(+ mapFeatureFlagsEnvToState({ agent_runtime_slim_state: true }).enableSlimAgentState,+ ).toBe(true);++ const config = FeatureFlagsSchema.parse({ agent_runtime_slim_state: ['user-1'] });+ expect(mapFeatureFlagsEnvToState(config, 'user-1').enableSlimAgentState).toBe(true);+ expect(mapFeatureFlagsEnvToState(config, 'user-2').enableSlimAgentState).toBe(false);+ });+ });+describe('agent_runtime_strip_operation_toolset', () => {it('is off by default', () => {expect(DEFAULT_FEATURE_FLAGS.agent_runtime_strip_operation_toolset).toBe(false);diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex b6bef495404..5b4917ac6bc 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -74,6 +74,16 @@ export const FeatureFlagsSchema = z.object({*/agent_runtime_strip_operation_toolset: FeatureFlagValue.optional(),+ /**+ * Keep copies the per-operation tool set already holds out of the agent state+ * blob rewritten at every step (`initialContext.payload.tools`, the manifests+ * of `activatedStepTools`, the deprecated top-level `expertise` mirror); they+ * are restored on load. Off: the blob keeps them inline. Server only;+ * `AGENT_RUNTIME_SLIM_STATE=0|1` overrides it. Array values are user ids (the+ * operation's owner).+ */+ agent_runtime_slim_state: FeatureFlagValue.optional(),+/*** Dashboards: monitoring widgets built by the `builtin-dashboard` agent tool,* the home / project dashboard pages, the widget Portal and in-chat widget@@ -220,6 +230,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {agent_deferred_init: false,agent_deferred_hetero_dispatch: false,agent_runtime_strip_operation_toolset: false,+ agent_runtime_slim_state: false,// Off until an admin publishes a user allowlist or flips it to true.dashboard: false,@@ -290,6 +301,11 @@ export const mapFeatureFlagsEnvToState = (userId,'agent_runtime_strip_operation_toolset',),+ enableSlimAgentState: evaluateFeatureFlag(+ config.agent_runtime_slim_state,+ userId,+ 'agent_runtime_slim_state',+ ),enableDashboard: evaluateFeatureFlag(config.dashboard, userId, 'dashboard'),enableMcpApps: evaluateFeatureFlag(config.mcp_apps, userId, 'mcp_apps'),enableWebhook: evaluateFeatureFlag(config.webhook, userId, 'webhook'),diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 39183caf54d..a5c42eb311b 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -98,6 +98,13 @@ export type IFeatureFlagsState = {* only; `AGENT_RUNTIME_STRIP_OPERATION_TOOLSET` (`0` / `1`) overrides it.*/enableStripOperationToolset: boolean | undefined;+ /**+ * Leave copies of the operation tool set (and the deprecated top-level+ * `expertise` mirror) out of the persisted agent state blob and restore them+ * on load (`agent_runtime_slim_state`). Server only;+ * `AGENT_RUNTIME_SLIM_STATE` (`0` / `1`) overrides it.+ */+ enableSlimAgentState: boolean | undefined;/** Hover previews of a topic's final answer (`topic_preview`). */enableTopicPreview: boolean | undefined;/**