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.

πŸ”₯ refactor(agent-runtime): remove the agent_runtime_strip_operation_toolset flag (#23364)

Arvin Xucbd8cacaeaba
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index a3e095b8c06..591686fbf7d 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -93,48 +93,20 @@ const writeToolSetCache = (operationId: string, json: string, ttlSeconds: number
};
/**
- * Whether a persisted blob may leave its tool set out.
- *
- * Reading the external key and writing it are two separate deploys. A queue
- * continuation targets the shared runtime URL, not a versioned deployment, so
- * during a rolling deploy (or a rollback) an operation saved by this build can
- * next execute on a worker running the previous one β€” and that worker's
- * `loadAgentState` never reads `agent_runtime_toolset`. Stripping on the first
- * 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 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;
-
-/**
- * Whether a persisted blob may also leave out the copies `slimStateForPersist`
+ * Whether a persisted blob may 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.
+ * The load path restores them unconditionally, so flipping it either way is
+ * safe for operations in flight.
+ *
+ * The flag is resolved per operation owner and cached here 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 is not slimmed rather than failing the
+ * save.
*/
-interface PersistOptions {
- slim: boolean;
- stripToolSet: boolean;
-}
+const SLIM_FLAG_CACHE_TTL_MS = 5000;
+const SLIM_FLAG_CACHE_MAX = 1024;
const envOverride = (name: string): boolean | undefined => {
const value = process.env[name];
@@ -144,72 +116,53 @@ const envOverride = (name: string): boolean | undefined => {
};
/**
- * Resolved values, keyed by owner ('' for the global value). One provider read
- * resolves both flags.
+ * 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.
+ * whose owner has no override. This cache bounds the lookup to once per owner
+ * per TTL.
*/
-const persistFlagCache = new Map<string, { expiresAt: number; value: PersistOptions }>();
+const slimFlagCache = new Map<string, { expiresAt: number; value: boolean }>();
-/** Clear the persistence-flag resolution cache (for testing). */
-export const resetStripOperationToolsetCache = () => {
- persistFlagCache.clear();
+/** Clear the slim-state flag resolution cache (for testing). */
+export const resetSlimAgentStateCache = () => {
+ slimFlagCache.clear();
};
-const resolveFlags = async (userId?: string): Promise<PersistOptions> => {
+const resolveSlimFlag = async (userId?: string): Promise<boolean> => {
// Owners without a user id all resolve the global value, so they share a key.
const cacheKey = userId ?? '';
- const cached = persistFlagCache.get(cacheKey);
+ const cached = slimFlagCache.get(cacheKey);
if (cached) {
if (cached.expiresAt > Date.now()) return cached.value;
- persistFlagCache.delete(cacheKey);
+ slimFlagCache.delete(cacheKey);
}
try {
const flags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
- const value: PersistOptions = {
- slim: flags.enableSlimAgentState === true,
- stripToolSet: flags.enableStripOperationToolset === true,
- };
+ const value = flags.enableSlimAgentState === true;
// Evict the oldest entry instead of growing with the number of owners.
- if (persistFlagCache.size >= STRIP_FLAG_CACHE_MAX) {
- const oldestKey = persistFlagCache.keys().next().value;
- if (oldestKey !== undefined) persistFlagCache.delete(oldestKey);
+ if (slimFlagCache.size >= SLIM_FLAG_CACHE_MAX) {
+ const oldestKey = slimFlagCache.keys().next().value;
+ if (oldestKey !== undefined) slimFlagCache.delete(oldestKey);
}
- persistFlagCache.set(cacheKey, { expiresAt: Date.now() + STRIP_FLAG_CACHE_TTL_MS, value });
+ slimFlagCache.set(cacheKey, { expiresAt: Date.now() + SLIM_FLAG_CACHE_TTL_MS, value });
return value;
} catch (error) {
- // Deliberately not cached: a transient read failure must not pin the flags
+ // Deliberately not cached: a transient read failure must not pin the flag
// off for a whole TTL.
- log('Failed to resolve agent state persistence flags, keeping inline: %O', error);
- return { slim: false, stripToolSet: false };
+ log('Failed to resolve agent state slim flag, keeping copies inline: %O', error);
+ return 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,
- };
-};
+const resolveSlim = async (userId?: string): Promise<boolean> =>
+ envOverride('AGENT_RUNTIME_SLIM_STATE') ?? (await resolveSlimFlag(userId));
export interface StepResult {
events?: AgentEvent[];
@@ -309,26 +262,19 @@ export class AgentStateManager {
* (group-member supervisor turns); the size win is forgone to avoid losing
* the prompt.
*/
- private serializeStateForPersist(state: AgentState, options: PersistOptions): string {
- const { slim, stripToolSet } = options;
+ private serializeStateForPersist(state: AgentState, slim: boolean): string {
// 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
- // `resolvePersistOptions`). It is immutable after creation, so a single
- // write per operation replaces re-serializing ~300–400 KB of tool schemas
- // at every step.
+ // blob. 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 } = source as AgentState & {
operationToolSet?: unknown;
};
- const persistable = (stripToolSet ? withoutToolSet : source) as AgentState & {
- messages?: unknown;
- operationToolSet?: unknown;
- };
+ const persistable = withoutToolSet as AgentState & { messages?: unknown };
if (
!state.origin?.agentId ||
!state.origin.topicId ||
@@ -390,17 +336,16 @@ export class AgentStateManager {
const stateKey = `${this.STATE_PREFIX}:${operationId}`;
try {
- const persistOptions = await resolvePersistOptions(state.origin?.userId);
- const { stripToolSet } = persistOptions;
- if (stripToolSet) await this.externalizeToolSet(operationId, state);
- const serializedState = this.serializeStateForPersist(state, persistOptions);
+ const slim = await resolveSlim(state.origin?.userId);
+ await this.externalizeToolSet(operationId, state);
+ const serializedState = this.serializeStateForPersist(state, slim);
// One MULTI, like `saveStepResult`: `loadAgentStatus` reads the status
// from the metadata hash, so it must never disagree with the blob.
const pipeline = this.redis.multi();
pipeline.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.
- if (stripToolSet) pipeline.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
+ pipeline.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
const metaKey = `${this.METADATA_PREFIX}:${operationId}`;
const metadata: Partial<AgentOperationMetadata> = {
lastActiveAt: new Date().toISOString(),
@@ -503,9 +448,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 persistOptions = await resolvePersistOptions(stepResult.newState.origin?.userId);
- const { stripToolSet } = persistOptions;
- if (stripToolSet) await this.externalizeToolSet(operationId, stepResult.newState);
+ const slim = await resolveSlim(stepResult.newState.origin?.userId);
+ await this.externalizeToolSet(operationId, stepResult.newState);
const pipeline = this.redis.multi();
@@ -514,10 +458,10 @@ export class AgentStateManager {
pipeline.setex(
stateKey,
this.DEFAULT_TTL,
- this.serializeStateForPersist(stepResult.newState, persistOptions),
+ this.serializeStateForPersist(stepResult.newState, slim),
);
// Refresh the externalized tool set's TTL alongside the blob.
- if (stripToolSet) pipeline.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
+ pipeline.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
// Save step history
const stepsKey = `${this.STEPS_PREFIX}:${operationId}`;
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index 10d0964c057..1669709804f 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -2,7 +2,7 @@ import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
-import { AgentStateManager, resetStripOperationToolsetCache } from '../AgentStateManager';
+import { AgentStateManager, resetSlimAgentStateCache } from '../AgentStateManager';
// Mock Redis client. Hoisted so individual tests can assert on the exact
// payloads handed to `setex` / `lpush`.
@@ -41,18 +41,18 @@ vi.mock('@/server/featureFlags', () => ({
getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(),
}));
-const mockStripFlag = (enabled: boolean) =>
+const mockSlimFlag = (enabled: boolean) =>
vi
.mocked(getServerFeatureFlagsStateFromRuntimeConfig)
- .mockResolvedValue({ enableStripOperationToolset: enabled } as any);
+ .mockResolvedValue({ enableSlimAgentState: enabled } as any);
describe('AgentStateManager', () => {
let stateManager: AgentStateManager;
beforeEach(() => {
vi.clearAllMocks();
- resetStripOperationToolsetCache();
- mockStripFlag(false);
+ resetSlimAgentStateCache();
+ mockSlimFlag(false);
stateManager = new AgentStateManager();
});
@@ -291,20 +291,6 @@ describe('AgentStateManager', () => {
describe('operationToolSet externalization', () => {
const toolSet = { enabledToolIds: ['foo'], manifestMap: { foo: { api: [] } }, tools: [{}] };
- // Stripping is opt-in so a previous-build worker can still execute an
- // operation mid-rollout (see `isToolSetStripEnabled`).
- const STRIP_FLAG = 'AGENT_RUNTIME_STRIP_OPERATION_TOOLSET';
- const originalFlag = process.env[STRIP_FLAG];
-
- beforeEach(() => {
- process.env[STRIP_FLAG] = '1';
- });
-
- afterAll(() => {
- if (originalFlag === undefined) delete process.env[STRIP_FLAG];
- else process.env[STRIP_FLAG] = originalFlag;
- });
-
it('writes the tool set to its own key and strips it from the state blob', async () => {
await stateManager.saveAgentState('op-ots-strip', {
operationToolSet: toolSet,
@@ -385,296 +371,6 @@ describe('AgentStateManager', () => {
});
});
- // A queue continuation targets the shared runtime URL, so an operation saved
- // by this build can next run on a previous-build worker that never reads the
- // external key. Until operators drain that build the blob must stay
- // self-contained.
- describe('operationToolSet externalization Β· rolling-deploy compatibility', () => {
- const STRIP_FLAG = 'AGENT_RUNTIME_STRIP_OPERATION_TOOLSET';
- const originalFlag = process.env[STRIP_FLAG];
-
- afterAll(() => {
- if (originalFlag === undefined) delete process.env[STRIP_FLAG];
- else process.env[STRIP_FLAG] = originalFlag;
- });
-
- it('keeps the inline tool set and writes no external key while stripping is off', async () => {
- delete process.env[STRIP_FLAG];
- const op = 'op-ots-compat-off';
- const toolSet = { enabledToolIds: ['compat'], manifestMap: { bar: {} }, tools: [{}] };
-
- await stateManager.saveAgentState(op, {
- operationToolSet: toolSet,
- status: 'running',
- stepCount: 1,
- } as any);
-
- expect(redisMock.setex.mock.calls.some((c) => c[0] === `agent_runtime_toolset:${op}`)).toBe(
- false,
- );
- expect(pipelineMock.expire).not.toHaveBeenCalledWith(
- `agent_runtime_toolset:${op}`,
- expect.anything(),
- );
- const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
- expect(JSON.parse(blob![2] as string).operationToolSet).toEqual(toolSet);
- });
-
- it('keeps the inline tool set in the step pipeline while stripping is off', async () => {
- delete process.env[STRIP_FLAG];
- const op = 'op-ots-compat-step';
- const toolSet = { enabledToolIds: ['compat-step'], manifestMap: {}, tools: [] };
-
- await stateManager.saveStepResult(op, {
- executionTime: 1,
- newState: { operationToolSet: toolSet, status: 'running', stepCount: 1 },
- stepIndex: 1,
- } as any);
-
- expect(pipelineMock.expire).not.toHaveBeenCalledWith(
- `agent_runtime_toolset:${op}`,
- expect.anything(),
- );
- const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
- expect(JSON.parse(blob![2] as string).operationToolSet).toEqual(toolSet);
- });
- });
-
- // 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];
- 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 () => {
- 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(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('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);
-
- // Both saves write the blob through a MULTI: saveAgentState first.
- const [saveBlob, stepBlob] = pipelineMock.setex.mock.calls.filter(
- (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(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, stepBlob] = pipelineMock.setex.mock.calls.filter(
- (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';
- process.env.AGENT_RUNTIME_SLIM_STATE = '0';
- const op = 'op-ff-force';
-
- await stateManager.saveAgentState(op, {
- operationToolSet: toolSet,
- origin,
- status: 'running',
- stepCount: 1,
- } as any);
-
- expect(getServerFeatureFlagsStateFromRuntimeConfig).not.toHaveBeenCalled();
- 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 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 = pipelineMock.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('slim state (agent_runtime_slim_state)', () => {
const manifest = { api: [{ name: 'x' }], identifier: 'x' };
const toolSet = {
@@ -695,13 +391,6 @@ describe('AgentStateManager', () => {
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(
@@ -709,15 +398,15 @@ describe('AgentStateManager', () => {
);
beforeEach(() => {
- for (const name of ENVS) delete process.env[name];
+ delete process.env.AGENT_RUNTIME_SLIM_STATE;
});
afterAll(() => {
- for (const name of ENVS) delete process.env[name];
+ delete process.env.AGENT_RUNTIME_SLIM_STATE;
});
it('leaves the copies out of the step blob when the flag is on', async () => {
- mockFlags({ slim: true, strip: true });
+ mockSlimFlag(true);
const op = 'op-slim-on';
await stateManager.saveStepResult(op, {
@@ -735,7 +424,7 @@ describe('AgentStateManager', () => {
});
it('loads a slimmed blob back to the full state', async () => {
- mockFlags({ slim: true, strip: true });
+ mockSlimFlag(true);
const op = 'op-slim-load';
await stateManager.saveStepResult(op, {
executionTime: 1,
@@ -755,26 +444,8 @@ describe('AgentStateManager', () => {
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 });
+ mockSlimFlag(false);
const op = 'op-slim-off';
const { operationToolSet: _toolSet, ...expected } = buildState();
@@ -787,24 +458,9 @@ describe('AgentStateManager', () => {
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 });
+ mockSlimFlag(true);
const op = 'op-slim-env-off';
await stateManager.saveStepResult(op, {
@@ -819,8 +475,8 @@ describe('AgentStateManager', () => {
expect(blob.operationToolSet).toBeUndefined();
});
- it('resolves both flags with one provider read per owner', async () => {
- mockFlags({ slim: true, strip: true });
+ it('resolves the flag for the owner once per cache window', async () => {
+ mockSlimFlag(true);
const op = 'op-slim-one-read';
for (const stepIndex of [2, 3]) {
@@ -831,8 +487,49 @@ describe('AgentStateManager', () => {
} as any);
}
+ // The per-step write must not pay a flag lookup on every step.
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-slim');
expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledTimes(1);
});
+
+ it('resolves the flag per operation owner', async () => {
+ mockSlimFlag(true);
+
+ for (const userId of ['user-a', 'user-b']) {
+ await stateManager.saveAgentState(`op-slim-owner-${userId}`, {
+ ...buildState(),
+ origin: { userId },
+ } as any);
+ }
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-a');
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-b');
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not slim, and does not cache, a failed resolution', async () => {
+ vi.mocked(getServerFeatureFlagsStateFromRuntimeConfig)
+ .mockRejectedValueOnce(new Error('down'))
+ .mockResolvedValue({ enableSlimAgentState: true } as any);
+ const op = 'op-slim-error-retry';
+
+ for (const stepIndex of [2, 3]) {
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: buildState(),
+ stepIndex,
+ } as any);
+ }
+
+ expect(getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledTimes(2);
+ const blobs = pipelineMock.setex.mock.calls
+ .filter((c) => c[0] === `agent_runtime_state:${op}`)
+ .map((c) => JSON.parse(c[2] as string));
+ // The tool set is stripped either way; only the retry is slimmed.
+ expect(blobs[0].operationToolSet).toBeUndefined();
+ expect(blobs[0].__slim).toBeUndefined();
+ expect(blobs.at(-1).__slim).toBeDefined();
+ });
});
describe('step execution lock', () => {
diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.ts
index eb5bbb7f733..ba94d02eeda 100644
--- a/packages/app-config/src/featureFlags/schema.test.ts
+++ b/packages/app-config/src/featureFlags/schema.test.ts
@@ -551,32 +551,6 @@ describe('mapFeatureFlagsEnvToState', () => {
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);
- 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);
- });
- });
});
describe('webhook flag', () => {
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index 5b4917ac6bc..6c46da1c079 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -65,15 +65,6 @@ export const FeatureFlagsSchema = z.object({
*/
agent_deferred_hetero_dispatch: 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(),
-
/**
* Keep copies the per-operation tool set already holds out of the agent state
* blob rewritten at every step (`initialContext.payload.tools`, the manifests
@@ -229,7 +220,6 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
agent_llm_relay: false,
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.
@@ -296,11 +286,6 @@ export const mapFeatureFlagsEnvToState = (
userId,
'agent_deferred_hetero_dispatch',
),
- enableStripOperationToolset: evaluateFeatureFlag(
- config.agent_runtime_strip_operation_toolset,
- userId,
- 'agent_runtime_strip_operation_toolset',
- ),
enableSlimAgentState: evaluateFeatureFlag(
config.agent_runtime_slim_state,
userId,
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index a5c42eb311b..047e7cc4d8f 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -92,12 +92,6 @@ export type IFeatureFlagsState = {
enableOnboardingV2: boolean | undefined;
enableRAGEval: boolean | undefined;
enableSTT: 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;
/**
* Leave copies of the operation tool set (and the deprecated top-level
* `expertise` mirror) out of the persisted agent state blob and restore them