Skip to content

🀯 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.

✨ feat(agent-runtime): gate operationToolSet stripping on a runtime feature flag (#22724)

Arvin Xub783134a28ec
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index 2ecfcce0659..3508be9b73d 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -8,6 +8,8 @@ import {
import debug from 'debug';
import { type Redis } from 'ioredis';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
import { hasNonPersistedMessage } from './messagePersistence';
import { getAgentRuntimeRedisClient } from './redis';
@@ -100,13 +102,79 @@ const writeToolSetCache = (operationId: string, json: string, ttlSeconds: number
* deploy would hand it a blob with no tool set, and the next LLM call would go
* out with the empty set `selectOperationToolSet` falls back to.
*
- * So this build ships the reader only: while the flag is off nothing changes β€”
- * the blob keeps its inline tool set byte-for-byte and no external key is
- * written. Operators flip it on once the previous build has drained, which is
- * when the mixed-version window is gone.
+ * So stripping is opt-in: while it is off nothing changes β€” the blob keeps its
+ * inline tool set byte-for-byte and no external key is written. It is gated by
+ * the runtime feature flag `agent_runtime_strip_operation_toolset` (published
+ * without a redeploy, per-user allowlists keyed on the operation's owner), and
+ * `AGENT_RUNTIME_STRIP_OPERATION_TOOLSET` overrides it: `0` is the kill switch
+ * and never touches the flag provider, `1` forces it on.
+ *
+ * Flipping the flag either way is safe for operations already in flight: the
+ * load path re-attaches an external tool set unconditionally and leaves an
+ * inline one alone, so a blob written under either setting loads the same.
+ *
+ * Resolution is cached here per operation owner for a few seconds on top of the
+ * runtime-config provider's own snapshot cache, so a publish still lands within
+ * seconds without a redeploy and a save pays no per-owner lookup. If resolution
+ * fails, the blob stays inline β€” the pre-flag behaviour β€” rather than failing
+ * the save.
+ */
+const STRIP_FLAG_CACHE_TTL_MS = 5000;
+const STRIP_FLAG_CACHE_MAX = 1024;
+
+/**
+ * Resolved values, keyed by owner ('' for the global value).
+ *
+ * `getMergedFeatureFlags` always reads the per-user override record when it is
+ * given a user id, and that provider does not cache a missing record
+ * (`cacheNullSnapshots: false`). Resolving with the owner on every save would
+ * therefore put a Redis GET on the per-step write path for every operation
+ * whose owner has no override β€” the common case, and the one that pays nothing
+ * back because stripping stays inline. This cache bounds the lookup to once per
+ * owner per TTL.
*/
-const isToolSetStripEnabled = (): boolean =>
- process.env.AGENT_RUNTIME_STRIP_OPERATION_TOOLSET === '1';
+const stripFlagCache = new Map<string, { expiresAt: number; value: boolean }>();
+
+/** Clear the strip-flag resolution cache (for testing). */
+export const resetStripOperationToolsetCache = () => {
+ stripFlagCache.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;
+
+ // Owners without a user id all resolve the global value, so they share a key.
+ const cacheKey = userId ?? '';
+ const cached = stripFlagCache.get(cacheKey);
+ if (cached) {
+ if (cached.expiresAt > Date.now()) return cached.value;
+ stripFlagCache.delete(cacheKey);
+ }
+
+ try {
+ const flags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
+ const enabled = 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);
+ }
+ stripFlagCache.set(cacheKey, {
+ expiresAt: Date.now() + STRIP_FLAG_CACHE_TTL_MS,
+ value: enabled,
+ });
+
+ return enabled;
+ } catch (error) {
+ // Deliberately not cached: a transient read failure must not pin the flag
+ // off for a whole TTL.
+ log('Failed to resolve agent_runtime_strip_operation_toolset, keeping inline: %O', error);
+ return false;
+ }
+};
export interface StepResult {
events?: AgentEvent[];
@@ -206,18 +274,18 @@ export class AgentStateManager {
* (group-member supervisor turns); the size win is forgone to avoid losing
* the prompt.
*/
- private serializeStateForPersist(state: AgentState): string {
+ private serializeStateForPersist(state: AgentState, stripToolSet: boolean): string {
// `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
- // `isToolSetStripEnabled`). It is immutable after creation, so a single
+ // `resolveStripOperationToolset`). 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 & {
operationToolSet?: unknown;
};
- const persistable = (isToolSetStripEnabled() ? withoutToolSet : state) as AgentState & {
+ const persistable = (stripToolSet ? withoutToolSet : state) as AgentState & {
messages?: unknown;
operationToolSet?: unknown;
};
@@ -282,9 +350,9 @@ export class AgentStateManager {
const stateKey = `${this.STATE_PREFIX}:${operationId}`;
try {
- const stripToolSet = isToolSetStripEnabled();
+ const stripToolSet = await resolveStripOperationToolset(state.origin?.userId);
if (stripToolSet) await this.externalizeToolSet(operationId, state);
- const serializedState = this.serializeStateForPersist(state);
+ const serializedState = this.serializeStateForPersist(state, stripToolSet);
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.
@@ -374,7 +442,7 @@ 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 = isToolSetStripEnabled();
+ const stripToolSet = await resolveStripOperationToolset(stepResult.newState.origin?.userId);
if (stripToolSet) await this.externalizeToolSet(operationId, stepResult.newState);
const pipeline = this.redis.multi();
@@ -384,7 +452,7 @@ export class AgentStateManager {
pipeline.setex(
stateKey,
this.DEFAULT_TTL,
- this.serializeStateForPersist(stepResult.newState),
+ this.serializeStateForPersist(stepResult.newState, stripToolSet),
);
// 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.ts
index e6b1a26c9a8..19396a5190e 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -1,6 +1,8 @@
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { AgentStateManager } from '../AgentStateManager';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
+import { AgentStateManager, resetStripOperationToolsetCache } from '../AgentStateManager';
// Mock Redis client. Hoisted so individual tests can assert on the exact
// payloads handed to `setex` / `lpush`.
@@ -34,11 +36,22 @@ vi.mock('../redis', () => ({
getAgentRuntimeRedisClient: () => redisMock,
}));
+vi.mock('@/server/featureFlags', () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(),
+}));
+
+const mockStripFlag = (enabled: boolean) =>
+ vi
+ .mocked(getServerFeatureFlagsStateFromRuntimeConfig)
+ .mockResolvedValue({ enableStripOperationToolset: enabled } as any);
+
describe('AgentStateManager', () => {
let stateManager: AgentStateManager;
beforeEach(() => {
vi.clearAllMocks();
+ resetStripOperationToolsetCache();
+ mockStripFlag(false);
stateManager = new AgentStateManager();
});
@@ -379,6 +392,243 @@ describe('AgentStateManager', () => {
});
});
+ // The runtime feature flag `agent_runtime_strip_operation_toolset` gates
+ // stripping without a redeploy; the env var overrides it either way.
+ describe('operationToolSet externalization Β· feature flag', () => {
+ const STRIP_FLAG = 'AGENT_RUNTIME_STRIP_OPERATION_TOOLSET';
+ const originalFlag = process.env[STRIP_FLAG];
+ const toolSet = { enabledToolIds: ['ff'], manifestMap: { ff: { api: [] } }, tools: [{}] };
+ const origin = { userId: 'user-ff' };
+
+ beforeEach(() => {
+ delete process.env[STRIP_FLAG];
+ });
+
+ afterAll(() => {
+ if (originalFlag === undefined) delete process.env[STRIP_FLAG];
+ else process.env[STRIP_FLAG] = originalFlag;
+ });
+
+ it('strips the saveAgentState blob when the flag is on, resolved for the owner', async () => {
+ mockStripFlag(true);
+ const op = 'op-ff-save-on';
+
+ await stateManager.saveAgentState(op, {
+ operationToolSet: toolSet,
+ origin,
+ status: 'running',
+ stepCount: 1,
+ } as any);
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-ff');
+ expect(redisMock.setex).toHaveBeenCalledWith(
+ `agent_runtime_toolset:${op}`,
+ 2 * 3600,
+ JSON.stringify(toolSet),
+ );
+ expect(redisMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
+ const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
+ });
+
+ it('strips the saveStepResult blob when the flag is on', async () => {
+ mockStripFlag(true);
+ const op = 'op-ff-step-on';
+
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: { operationToolSet: toolSet, origin, status: 'running', stepCount: 1 },
+ stepIndex: 1,
+ } as any);
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-ff');
+ expect(redisMock.setex).toHaveBeenCalledWith(
+ `agent_runtime_toolset:${op}`,
+ 2 * 3600,
+ JSON.stringify(toolSet),
+ );
+ expect(pipelineMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
+ const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
+ });
+
+ it('keeps both blobs byte-for-byte inline and writes no external key when the flag is off', async () => {
+ mockStripFlag(false);
+ const op = 'op-ff-off';
+ const state = { operationToolSet: toolSet, origin, status: 'running', stepCount: 1 };
+
+ await stateManager.saveAgentState(op, state as any);
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: state,
+ stepIndex: 1,
+ } as any);
+
+ const saveBlob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ const stepBlob = pipelineMock.setex.mock.calls.find(
+ (c) => c[0] === `agent_runtime_state:${op}`,
+ );
+ expect(saveBlob![2]).toBe(JSON.stringify(state));
+ expect(stepBlob![2]).toBe(JSON.stringify(state));
+ expect(redisMock.setex.mock.calls.some((c) => c[0] === `agent_runtime_toolset:${op}`)).toBe(
+ false,
+ );
+ expect(redisMock.expire).not.toHaveBeenCalledWith(
+ `agent_runtime_toolset:${op}`,
+ expect.anything(),
+ );
+ expect(pipelineMock.expire).not.toHaveBeenCalledWith(
+ `agent_runtime_toolset:${op}`,
+ expect.anything(),
+ );
+ });
+
+ it("env '0' overrides an enabled flag without consulting the flag provider", async () => {
+ process.env[STRIP_FLAG] = '0';
+ mockStripFlag(true);
+ const op = 'op-ff-kill';
+
+ await stateManager.saveAgentState(op, {
+ operationToolSet: toolSet,
+ origin,
+ status: 'running',
+ stepCount: 1,
+ } as any);
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: { operationToolSet: toolSet, origin, status: 'running', stepCount: 2 },
+ stepIndex: 2,
+ } as any);
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).not.toHaveBeenCalled();
+ expect(redisMock.setex.mock.calls.some((c) => c[0] === `agent_runtime_toolset:${op}`)).toBe(
+ false,
+ );
+ const saveBlob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ const stepBlob = pipelineMock.setex.mock.calls.find(
+ (c) => c[0] === `agent_runtime_state:${op}`,
+ );
+ expect(JSON.parse(saveBlob![2] as string).operationToolSet).toEqual(toolSet);
+ expect(JSON.parse(stepBlob![2] as string).operationToolSet).toEqual(toolSet);
+ });
+
+ it("env '1' forces stripping without consulting the flag provider", async () => {
+ process.env[STRIP_FLAG] = '1';
+ const op = 'op-ff-force';
+
+ await stateManager.saveAgentState(op, {
+ operationToolSet: toolSet,
+ origin,
+ status: 'running',
+ stepCount: 1,
+ } as any);
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).not.toHaveBeenCalled();
+ const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
+ });
+
+ it('keeps the blob inline when the flag provider fails', async () => {
+ vi.mocked(getServerFeatureFlagsStateFromRuntimeConfig).mockRejectedValue(new Error('down'));
+ const op = 'op-ff-error';
+
+ await stateManager.saveAgentState(op, {
+ operationToolSet: toolSet,
+ origin,
+ status: 'running',
+ stepCount: 1,
+ } as any);
+
+ const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(JSON.parse(blob![2] as string).operationToolSet).toEqual(toolSet);
+ });
+
+ it('rehydrates a stripped blob from its external key while the flag is off', async () => {
+ mockStripFlag(false);
+ const op = 'op-ff-rehydrate';
+ redisMock.get.mockImplementation((key: string) =>
+ key === `agent_runtime_state:${op}`
+ ? JSON.stringify({ origin, status: 'running', stepCount: 3 })
+ : key === `agent_runtime_toolset:${op}`
+ ? JSON.stringify(toolSet)
+ : null,
+ );
+
+ const loaded = await stateManager.loadAgentState(op);
+
+ expect(loaded?.operationToolSet).toEqual(toolSet);
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).not.toHaveBeenCalled();
+ });
+
+ it('resolves the flag once per cache window for one owner', async () => {
+ mockStripFlag(true);
+ const op = 'op-ff-cache-hit';
+ const state = { operationToolSet: toolSet, origin, status: 'running', stepCount: 1 };
+
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: state,
+ stepIndex: 1,
+ } as any);
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: { ...state, stepCount: 2 },
+ stepIndex: 2,
+ } as any);
+
+ // The per-step write must not pay a flag lookup on every step.
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledTimes(1);
+ });
+
+ it('resolves the flag per operation owner', async () => {
+ mockStripFlag(true);
+
+ await stateManager.saveAgentState('op-ff-owner-a', {
+ operationToolSet: toolSet,
+ origin: { userId: 'user-a' },
+ status: 'running',
+ stepCount: 1,
+ } as any);
+ await stateManager.saveAgentState('op-ff-owner-b', {
+ operationToolSet: toolSet,
+ origin: { userId: 'user-b' },
+ status: 'running',
+ stepCount: 1,
+ } as any);
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-a');
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-b');
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not cache a failed resolution', async () => {
+ vi.mocked(getServerFeatureFlagsStateFromRuntimeConfig)
+ .mockRejectedValueOnce(new Error('down'))
+ .mockResolvedValue({ enableStripOperationToolset: true } as any);
+ const op = 'op-ff-error-retry';
+ const state = { operationToolSet: toolSet, origin, status: 'running', stepCount: 1 };
+
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: state,
+ stepIndex: 1,
+ } as any);
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: { ...state, stepCount: 2 },
+ stepIndex: 2,
+ } as any);
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledTimes(2);
+ const blobs = pipelineMock.setex.mock.calls.filter(
+ (c) => c[0] === `agent_runtime_state:${op}`,
+ );
+ // First save keeps the blob inline, the retry strips it.
+ expect(JSON.parse(blobs[0][2] as string).operationToolSet).toEqual(toolSet);
+ expect(JSON.parse(blobs.at(-1)![2] as string).operationToolSet).toBeUndefined();
+ });
+ });
+
describe('step execution lock', () => {
it('claims an operation-scoped lock with the provided owner token', async () => {
redisMock.eval.mockResolvedValue(1);
diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.ts
index 45433788493..8acf5696db7 100644
--- a/packages/app-config/src/featureFlags/schema.test.ts
+++ b/packages/app-config/src/featureFlags/schema.test.ts
@@ -538,4 +538,30 @@ describe('mapFeatureFlagsEnvToState', () => {
expect(mappedState.enableChannels).toBe(true);
expect(mappedState.enableDashboard).toBe(false);
});
+
+ describe('agent_runtime_strip_operation_toolset', () => {
+ it('is off by default', () => {
+ expect(DEFAULT_FEATURE_FLAGS.agent_runtime_strip_operation_toolset).toBe(false);
+ expect(
+ mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableStripOperationToolset,
+ ).toBe(false);
+ });
+
+ it('maps true to enabled for every user', () => {
+ const config = { agent_runtime_strip_operation_toolset: true };
+
+ expect(mapFeatureFlagsEnvToState(config, 'user-1').enableStripOperationToolset).toBe(true);
+ expect(mapFeatureFlagsEnvToState(config).enableStripOperationToolset).toBe(true);
+ });
+
+ it('maps a user allowlist to the listed users only', () => {
+ const config = FeatureFlagsSchema.parse({
+ agent_runtime_strip_operation_toolset: ['user-1'],
+ });
+
+ expect(mapFeatureFlagsEnvToState(config, 'user-1').enableStripOperationToolset).toBe(true);
+ expect(mapFeatureFlagsEnvToState(config, 'user-2').enableStripOperationToolset).toBe(false);
+ expect(mapFeatureFlagsEnvToState(config).enableStripOperationToolset).toBe(false);
+ });
+ });
});
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index b238d976418..78d42dbb44f 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -63,6 +63,15 @@ export const FeatureFlagsSchema = z.object({
*/
agent_deferred_init: FeatureFlagValue.optional(),
+ /**
+ * Keep the immutable per-operation tool set out of the agent state blob that
+ * is rewritten at every step; it is written once to its own Redis key and
+ * re-attached on load. Off: the blob keeps its inline copy. Server only;
+ * `AGENT_RUNTIME_STRIP_OPERATION_TOOLSET=0|1` overrides it. Array values are
+ * user ids (the operation's owner).
+ */
+ agent_runtime_strip_operation_toolset: FeatureFlagValue.optional(),
+
/**
* Dashboards: monitoring widgets built by the `builtin-dashboard` agent tool,
* the home / project dashboard pages, the widget Portal and in-chat widget
@@ -215,6 +224,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
// Off until the client executor ships everywhere; allowlist first.
agent_llm_relay: false,
agent_deferred_init: false,
+ agent_runtime_strip_operation_toolset: false,
// Off until an admin publishes a user allowlist or flips it to true.
dashboard: false,
@@ -284,6 +294,11 @@ export const mapFeatureFlagsEnvToState = (
userId,
'agent_deferred_init',
),
+ enableStripOperationToolset: evaluateFeatureFlag(
+ config.agent_runtime_strip_operation_toolset,
+ userId,
+ 'agent_runtime_strip_operation_toolset',
+ ),
enableDashboard: evaluateFeatureFlag(config.dashboard, userId, 'dashboard'),
enableMcpApps: evaluateFeatureFlag(config.mcp_apps, userId, 'mcp_apps'),
enableAgentKnowledgeSpace: evaluateFeatureFlag(
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 463f0029afd..81300b953bf 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -89,6 +89,12 @@ export type IFeatureFlagsState = {
enableRAGEval: boolean | undefined;
enableSTT: boolean | undefined;
enableStorageOverage: boolean | undefined;
+ /**
+ * Keep the immutable `operationToolSet` out of the per-step agent state blob
+ * and in its own Redis key (`agent_runtime_strip_operation_toolset`). Server
+ * only; `AGENT_RUNTIME_STRIP_OPERATION_TOOLSET` (`0` / `1`) overrides it.
+ */
+ enableStripOperationToolset: boolean | undefined;
/** Hover previews of a topic's final answer (`topic_preview`). */
enableTopicPreview: boolean | undefined;
enableVoiceDictation: boolean | undefined;