π€― 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
β»οΈ refactor(agent): move the run policies and expertise into their slots (#19708)
Arvin Xu6503fb8c48b0
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.tsindex 27beecb9adb..f4bf2aa238f 100644--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts@@ -55,8 +55,10 @@ export const getDefaultReasonDetail = (finalState: any, reason?: string): string* it (e.g. `execSubAgent.onComplete`) receive the full state* via the local `HookContext` channel, not via the stream.* - `operationToolSet`, `toolManifestMap`, `toolSourceMap`, `tools`- * β operation-level snapshot; back-compat copies of one struct.- * - `expertise` β immutable operation-level snapshot retained in working state.+ * β operation-level snapshot; the four top-level names are the legacy+ * mirrors of the slot, kept here for operations that still carry them.+ * - `world.expertise` β immutable operation-level snapshot retained in working+ * state. The rest of `world` stays: the client renders from it.** Mirrors the `done`-event strip in `OperationTraceRecorder.appendStep`;* keep the two lists in sync if either set changes.@@ -72,9 +74,15 @@ const stripStateForStream = <T extends Record<string, any>>(toolManifestMap: _toolManifestMap,toolSourceMap: _toolSourceMap,tools: _tools,+ world,...rest} = state;- return rest as T;+ // `world` had to be destructured to reach its expertise snapshot, so it must be+ // put back: everything else on it (agent, group, channel β¦) has to survive.+ if (!world || typeof world !== 'object') return rest as T;+ if (!('expertise' in world)) return { ...rest, world } as unknown as T;+ const { expertise: _worldExpertise, ...worldRest } = world as Record<string, unknown>;+ return { ...rest, world: worldRest } as unknown as T;};/**diff --git a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.tsindex 40a45f4ad35..893618509e1 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts@@ -280,6 +280,15 @@ describe('StreamEventManager', () => {toolSourceMap: { x: 'plugin' },tools: [{ name: 'x' }],usage: { llm: { tokens: { total: 100 } } },+ world: {+ agent: { systemRole: 'you are a helpful agent' },+ expertise: {+ contentHash: 'hash',+ domains: [{ id: 'product-design', lessonIds: ['lesson-1'] }],+ renderedContext: '<expertise>heavy learned context</expertise>',+ schemaVersion: 1,+ },+ },};mockRedis.xadd.mockResolvedValue('event-id-strip');@@ -298,6 +307,12 @@ describe('StreamEventManager', () => {// Stripped: heavy / reconstructible fields goneexpect(parsed.finalState.expertise).toBeUndefined();+ // The expertise snapshot moved into `world`; the rest of the world, which+ // the client renders from, must survive the strip.+ expect(parsed.finalState.world.expertise).toBeUndefined();+ expect(parsed.finalState.world.agent).toEqual({+ systemRole: 'you are a helpful agent',+ });expect(parsed.finalState.messages).toBeUndefined();expect(parsed.finalState.operationToolSet).toBeUndefined();expect(parsed.finalState.toolManifestMap).toBeUndefined();@@ -315,6 +330,30 @@ describe('StreamEventManager', () => {// finalState passed as a param, so the error message survives.expect(parsed.reasonDetail).toBe('boom');});++ // Reaching `world.expertise` means destructuring `world`; a run without an+ // expertise snapshot β the common case β must still ship its world.+ it('keeps the world snapshot when it carries no expertise', async () => {+ const world = {+ agent: { systemRole: 'you are a helpful agent' },+ group: { agentMap: {} },+ userTimezone: 'Asia/Shanghai',+ };+ mockRedis.xadd.mockResolvedValue('event-id-world');++ await streamManager.publishAgentRuntimeEnd({+ finalState: { cost: { total: 1 }, messages: [], status: 'done', stepCount: 1, world },+ operationId: 'test-operation-id',+ reason: 'done',+ stepIndex: 1,+ });++ const dataArg = mockRedis.xadd.mock.calls[0]?.find(+ (a: any) => typeof a === 'string' && a.startsWith('{'),+ );++ expect(JSON.parse(dataArg).finalState.world).toEqual(world);+ });});it.each([undefined, 'execution_complete'])(diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex 23b1785b9e6..cf591eadac0 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -1,4 +1,9 @@-import type { AgentState, CallLLMPayload } from '@lobechat/agent-runtime';+import {+ type AgentState,+ type CallLLMPayload,+ selectEnableExpertise,+ selectExpertise,+} from '@lobechat/agent-runtime';import { gatherContextFacts } from '@lobechat/mecha';import type { ChatStreamPayload } from '@lobechat/model-runtime';import { SpanStatusCode } from '@lobechat/observability-otel/api';@@ -127,10 +132,10 @@ export const buildServerCallLlmContext = async ({botPlatformContext: state.world?.channel?.botPlatform,...(facts.step.workspaceContext && { workspaceContext: facts.step.workspaceContext }),discordContext: state.world?.channel?.discord,- enableExpertise: state.enableExpertise,+ enableExpertise: selectEnableExpertise(state),enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,evalContext: state.world?.eval,- expertise: state.expertise,+ expertise: selectExpertise(state),forceFinish: state.forceFinish,...(facts.step.groupAgentBuilderContext && {groupAgentBuilderContext: facts.step.groupAgentBuilderContext,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex b7c403ea53a..08f9829500d 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -549,6 +549,19 @@ describe('AgentRuntimeService', () => {});});+ it('records the approval mode as a run policy', async () => {+ await service.createOperation({+ ...mockParams,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ const [, state] = mockCoordinator.saveAgentState.mock.calls[0];+ expect(state.principal.policy.userIntervention).toEqual({ approvalMode: 'headless' });+ // Mirrored at the top level for the rolling-deploy window: a worker on the+ // pre-slot build reads only that, and would park this headless run.+ expect(state.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ });+it('stores the run tool set once, on the operation slot', async () => {const manifestMap = { 'lobe-web-browsing': { identifier: 'lobe-web-browsing' } };@@ -688,11 +701,14 @@ describe('AgentRuntimeService', () => {expertise,});+ // What the model is told about the run lives on the world slot, with the+ // top-level mirror kept for pre-slot workers during a rolling deploy.expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith('test-operation-1',expect.objectContaining({enableExpertise: true,expertise,+ world: expect.objectContaining({ enableExpertise: true, expertise }),}),);});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex beaa6be44b8..ed20d854242 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -1060,8 +1060,6 @@ export class AgentRuntimeService {const initialState = {activatedStepTools,createdAt: new Date().toISOString(),- enableExpertise,- expertise,// Store initialContext for executeSync to useinitialContext,lastModified: new Date().toISOString(),@@ -1140,8 +1138,19 @@ export class AgentRuntimeService {shareVisitor: agentShareVisitor,},audit: { clientIp: appContext?.clientIp, userAgent: appContext?.userAgent },- policy: { deviceAccess: deviceAccessPolicy },+ // What the run may do, decided once here: device access and the+ // approval mode its tool calls answer to.+ policy: { deviceAccess: deviceAccessPolicy, userIntervention: userInterventionConfig },},+ // Compat mirrors for a rolling deploy: a worker still running the+ // pre-slot build reads only these, and a missing approval mode defaults+ // to `manual` there β which parks a headless run on an approval nobody+ // can give. Drop them (and the matching entries in+ // `normalizeAgentState`'s COMPAT_MIRROR_PATHS) once no pre-slot worker+ // can pick up a step.+ enableExpertise,+ expertise,+ userInterventionConfig,// What the model is told about the run's world β frozen from here on;// the context engine reads it on every step.world: {@@ -1151,15 +1160,15 @@ export class AgentRuntimeService {}),connectorOwnershipNote,disabledPluginIds,+ enableExpertise,eval: evalContext,+ expertise,group: agentGroup,projectInstructions,searchDecision,userMemory,userTimezone,},- // User intervention config for headless mode in async tasks- userInterventionConfig,} as Partial<AgentState>;// Use coordinator to create operation, automatically sends initialization event.diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.tsindex 0b1509dbfb1..a4cad78c489 100644--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts@@ -385,8 +385,9 @@ export class OperationTraceRecorder {// Remove reconstructible fields from finalState:// - messages: from messagesBaseline + messagesDelta chain// - operationToolSet: from toolsetBaseline (step 0)- // - toolManifestMap/tools/toolSourceMap: backward-compat copies of operationToolSet- // - expertise: immutable operation-level snapshot retained in working state+ // - toolManifestMap/tools/toolSourceMap: legacy mirrors of operationToolSet+ // - world.expertise (and its legacy top-level copy): immutable+ // operation-level snapshot retained in working stateconst {expertise: _expertise,messages: _msgs,@@ -394,10 +395,15 @@ export class OperationTraceRecorder {toolManifestMap: _tmm,toolSourceMap: _tsm,tools: _tools,+ world: _world,// activatedStepTools is kept since it's the cumulative record...restState} = e.finalState;- return { ...e, finalState: restState };+ const { expertise: _worldExpertise, ...worldRest } = _world ?? {};+ return {+ ...e,+ finalState: _world ? { ...restState, world: worldRest } : restState,+ };}return e;}),diff --git a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.tsindex a0750212916..9c220ea1d3e 100644--- a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts@@ -88,6 +88,10 @@ describe('OperationTraceRecorder', () => {toolManifestMap: {},toolSourceMap: {},tools: [],+ world: {+ agent: { systemRole: 'kept' },+ expertise: { contentHash: 'hash', renderedContext: '<expertise/>' },+ },},reason: 'done',type: 'done',@@ -120,6 +124,8 @@ describe('OperationTraceRecorder', () => {expect(doneEvent.finalState.toolManifestMap).toBeUndefined();expect(doneEvent.finalState.toolSourceMap).toBeUndefined();expect(doneEvent.finalState.tools).toBeUndefined();+ // Only the expertise snapshot leaves `world`; the rest of it is kept.+ expect(doneEvent.finalState.world).toEqual({ agent: { systemRole: 'kept' } });});it('emits messagesDelta-only beyond step 0 and only stores messagesBaseline when isCompression', async () => {diff --git a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts b/apps/server/src/services/agentRuntime/agentInterventionNotification.tsindex 3f020b004b7..415a0e7db1d 100644--- a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts+++ b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts@@ -1,7 +1,9 @@import {DEFAULT_SECURITY_BLACKLIST,InterventionChecker,+ selectSecurityBlacklist,selectToolManifestMap,+ selectUserInterventionConfig,} from '@lobechat/agent-runtime';import {type ChatToolPayload,@@ -244,8 +246,10 @@ export const buildRuntimeInterventionNotification = async ({}const items: NotifyAgentInterventionItem[] = [];- const securityBlacklist = state?.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;- const resolvedApprovalMode = approvalMode(state?.userInterventionConfig?.approvalMode);+ const securityBlacklist = selectSecurityBlacklist(state ?? {}) ?? DEFAULT_SECURITY_BLACKLIST;+ const resolvedApprovalMode = approvalMode(+ selectUserInterventionConfig(state ?? {})?.approvalMode,+ );for (const tool of pendingTools) {const toolMessageId = toolMessageIds[tool.id];diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 1f288a73c0b..e24515e75f5 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -26,6 +26,7 @@ import {type SubAgentsBatchResultPayload,} from '../types';import { selectRunTools, selectToolManifestMap } from '../utils/operationToolSet';+import { selectSecurityBlacklist, selectUserInterventionConfig } from '../utils/stateSlots';import { shouldCompress } from '../utils/tokenCounter';const TOOL_NOT_ALLOWED_CONTENT =@@ -160,7 +161,7 @@ export class GeneralChatAgent implements Agent {const toolsToExecute: ChatToolPayload[] = [];// Get security blacklist for resolver metadata- const securityBlacklist = state.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;+ const securityBlacklist = selectSecurityBlacklist(state) ?? DEFAULT_SECURITY_BLACKLIST;// Resolvers see one flat record: the run ledger plus the facts they audit// against β the security blacklist and the plan's working directory (the@@ -172,7 +173,7 @@ export class GeneralChatAgent implements Agent {};// Get user config (default to 'manual' mode)- const userConfig = state.userInterventionConfig || { approvalMode: 'manual' };+ const userConfig = selectUserInterventionConfig(state) || { approvalMode: 'manual' };const { approvalMode, allowList = [] } = userConfig;// Global audits: default to security blacklist audit if not provided@@ -753,7 +754,7 @@ export class GeneralChatAgent implements Agent {// Request approval for tools that need intervention// Non-headless mode waits for human approval; headless mode returns blocked tool results.if (toolsNeedingIntervention.length > 0) {- if (state.userInterventionConfig?.approvalMode === 'headless') {+ if (selectUserInterventionConfig(state)?.approvalMode === 'headless') {instructions.push({payload: {blockedContent:diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 9ea14c52268..8ef8696262b 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -3428,57 +3428,72 @@ describe('GeneralChatAgent', () => {]);});- it('should resolve blocked tool in headless mode when global resolver with policy always triggers', async () => {- const customResolver: GlobalInterventionAuditConfig = {- type: 'customBlocker',- policy: 'always',- resolver: async (toolArgs) => toolArgs.blocked === true,- };+ // The approval mode lives on `principal.policy.userIntervention`; operations+ // created before the move carry it at the top level. Both must still reach+ // the decision, or a background run parks for an approval nobody can give.+ it.each([+ {+ shape: 'policy slot',+ state: { principal: { policy: { userIntervention: { approvalMode: 'headless' } } } },+ },+ {+ shape: 'legacy top level',+ state: { userInterventionConfig: { approvalMode: 'headless' } },+ },+ ])(+ 'should resolve blocked tool in headless mode when global resolver with policy always triggers (%s)',+ async ({ state: interventionState }) => {+ const customResolver: GlobalInterventionAuditConfig = {+ type: 'customBlocker',+ policy: 'always',+ resolver: async (toolArgs) => toolArgs.blocked === true,+ };- const agent = new GeneralChatAgent({- agentConfig: { maxSteps: 100 },- globalInterventionAudits: [customResolver],- operationId: 'test-session',- modelRuntimeConfig: mockModelRuntimeConfig,- });+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ globalInterventionAudits: [customResolver],+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });- const blockedTool: ChatToolPayload = {- id: 'call-1',- identifier: 'my-tool',- apiName: 'doSomething',- arguments: '{"blocked":true}',- type: 'default',- };+ const blockedTool: ChatToolPayload = {+ id: 'call-1',+ identifier: 'my-tool',+ apiName: 'doSomething',+ arguments: '{"blocked":true}',+ type: 'default',+ };- const state = createMockState({- toolManifestMap: {- 'my-tool': { identifier: 'my-tool' },- },- userInterventionConfig: { approvalMode: 'headless' },- });+ const state = createMockState({+ toolManifestMap: {+ 'my-tool': { identifier: 'my-tool' },+ },+ ...(interventionState as Record<string, unknown>),+ });- const context = createMockContext('llm_result', {- hasToolsCalling: true,- toolsCalling: [blockedTool],- parentMessageId: 'msg-1',- });+ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [blockedTool],+ parentMessageId: 'msg-1',+ });- const result = await agent.runner(context, state);+ const result = await agent.runner(context, state);- // Headless/CLI has no human intervention UI, so return a blocked tool result for replan.- expect(result).toEqual([- {- payload: {- blockedContent:- 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',- blockedReason: 'human_intervention_unavailable',- parentMessageId: 'msg-1',- toolsCalling: [blockedTool],+ // Headless/CLI has no human intervention UI, so return a blocked tool result for replan.+ expect(result).toEqual([+ {+ payload: {+ blockedContent:+ 'This run cannot wait for user interaction. Continue in a user-facing conversation to answer questions or approve tools.',+ blockedReason: 'human_intervention_unavailable',+ parentMessageId: 'msg-1',+ toolsCalling: [blockedTool],+ },+ type: 'resolve_blocked_tools',},- type: 'resolve_blocked_tools',- },- ]);- });+ ]);+ },+ );it('should execute tool in headless mode when global resolver with policy required triggers', async () => {const customResolver: GlobalInterventionAuditConfig = {diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex 1cbd4edcc54..c57bd18adcd 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -132,6 +132,10 @@ export interface AgentRunPrincipal {policy?: {/** Device-access decision; `reason` names the branch that granted or denied it. */deviceAccess?: { canUseDevice: boolean; reason: string };+ /** Tool-call patterns that always need a human. Unset falls back to the runtime default. */+ securityBlacklist?: SecurityBlacklistConfig;+ /** Approval mode for this run β `headless` for background and sub-agent runs. */+ userIntervention?: UserInterventionConfig;};}@@ -224,8 +228,12 @@ export interface AgentWorldSnapshot {* is kept apart for the rules that must hide those tools from the model.*/disabledPluginIds?: string[];+ /** Whether the context engine may inject {@link AgentWorldSnapshot.expertise}. */+ enableExpertise?: boolean;/** Evaluation prompt data for eval runs. */eval?: EvalContext;+ /** Expertise snapshot resolved once when this operation started. */+ expertise?: ExpertiseContextSnapshot;/** Multi-agent group roster (or bot-conversation fallback). */group?: AgentGroupConfig;/** Root instruction files of the bound project. */@@ -288,10 +296,10 @@ export interface AgentState {costLimit?: CostLimit;// --- Metadata ---createdAt: string;- /** Whether ContextEngine may inject the operation expertise snapshot. */+ /** @deprecated Use `world.enableExpertise`. */enableExpertise?: boolean;error?: any;- /** Immutable expertise snapshot resolved once when this operation starts. */+ /** @deprecated Use `world.expertise`. */expertise?: ExpertiseContextSnapshot;/*** When true, the agent is in force-finish mode (maxSteps exceeded).@@ -430,12 +438,7 @@ export interface AgentState {// --- Principal ---/** Under whose authority the run acts and what it may do. Frozen at creation. */principal?: AgentRunPrincipal;- /**- * Security blacklist configuration- * These rules will ALWAYS block execution and require human intervention,- * regardless of user settings (even in auto-run mode).- * If not provided, DEFAULT_SECURITY_BLACKLIST will be used.- */+ /** @deprecated Use `principal.policy.securityBlacklist`. */securityBlacklist?: SecurityBlacklistConfig;// --- State Machine ---status:@@ -507,10 +510,7 @@ export interface AgentState {*/usage: Usage;- /**- * User's global intervention configuration- * Controls how tools requiring approval are handled- */+ /** @deprecated Use `principal.policy.userIntervention`. */userInterventionConfig?: UserInterventionConfig;// --- World snapshot ---diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.tsindex ca5539fb5ff..dd058db6388 100644--- a/packages/agent-runtime/src/utils/index.ts+++ b/packages/agent-runtime/src/utils/index.ts@@ -4,6 +4,7 @@ export * from './normalizeAgentState';export * from './operationToolSet';export * from './replay';export * from './runtimeRetry';+export * from './stateSlots';export * from './status';export * from './stepContextComputer';export * from './tokenCounter';diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts b/packages/agent-runtime/src/utils/normalizeAgentState.test.tsindex 243d23996bd..2336932143a 100644--- a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts+++ b/packages/agent-runtime/src/utils/normalizeAgentState.test.ts@@ -259,6 +259,50 @@ describe('normalizeAgentState', () => {expect('toolManifestMap' in normalized).toBe(false);});+ it('lifts the run policies and the expertise snapshot into their slots', () => {+ const expertise = { contentHash: 'h', domains: [], renderedContext: '<e/>', schemaVersion: 1 };+ const state = {+ ...baseState(),+ // `false` is a decision, not an absent value.+ enableExpertise: false,+ expertise,+ securityBlacklist: { rules: [{ pattern: 'rm -rf', type: 'command' }] },+ userInterventionConfig: { approvalMode: 'headless' },+ } as unknown as AgentState;++ const normalized = normalizeAgentState(state);++ expect(normalized.principal?.policy).toEqual({+ securityBlacklist: { rules: [{ pattern: 'rm -rf', type: 'command' }] },+ userIntervention: { approvalMode: 'headless' },+ });+ expect(normalized.world?.expertise).toBe(expertise);+ expect(normalized.world?.enableExpertise).toBe(false);+ // Kept, not dropped: a worker still running the pre-slot build reads only+ // the top-level copy, and would park a headless run without it.+ for (const compat of [+ 'enableExpertise',+ 'expertise',+ 'securityBlacklist',+ 'userInterventionConfig',+ ]) {+ expect(compat in normalized).toBe(true);+ }+ });++ it('keeps a policy slot decision over the legacy top-level copy', () => {+ const state = {+ ...baseState(),+ principal: { policy: { userIntervention: { approvalMode: 'auto-run' } } },+ userInterventionConfig: { approvalMode: 'headless' },+ } as unknown as AgentState;++ const normalized = normalizeAgentState(state);++ expect(normalized.principal?.policy?.userIntervention).toEqual({ approvalMode: 'auto-run' });+ expect(normalized.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ });+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 16a53f02ecb..02bf54bb492 100644--- a/packages/agent-runtime/src/utils/normalizeAgentState.ts+++ b/packages/agent-runtime/src/utils/normalizeAgentState.ts@@ -63,10 +63,10 @@ const LEGACY_KEY_PATHS: Record<string, readonly string[]> = {};/**- * 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.+ * Top-level keys the `operationToolSet` slot absorbed, rather than legacy+ * `metadata` keys. The tool set used to be written twice, which doubled the+ * heaviest part of the blob on every step, so these are lifted into the slot and+ * dropped from the top level.*/const LEGACY_MIRROR_PATHS: Record<string, readonly string[]> = {toolExecutorMap: ['operationToolSet', 'executorMap'],@@ -75,16 +75,39 @@ const LEGACY_MIRROR_PATHS: Record<string, readonly string[]> = {tools: ['operationToolSet', 'tools'],};+/**+ * Run policies and the expertise snapshot: lifted into their slot but KEPT at+ * the top level.+ *+ * A rolling deploy runs old and new builds side by side over the same Redis+ * states. A worker on the pre-slot build reads only the top-level copy and+ * defaults a missing approval mode to `manual`, which parks a headless run on an+ * approval nobody can give β so dropping the copy here would strand exactly the+ * operations a new instance created during that window. The producer writes both+ * for the same reason.+ *+ * Remove both halves once no pre-slot worker can pick up a step.+ */+const COMPAT_MIRROR_PATHS: Record<string, readonly string[]> = {+ enableExpertise: ['world', 'enableExpertise'],+ expertise: ['world', 'expertise'],+ securityBlacklist: ['principal', 'policy', 'securityBlacklist'],+ userInterventionConfig: ['principal', 'policy', 'userIntervention'],+};+const LEGACY_MIRROR_KEYS = Object.keys(LEGACY_MIRROR_PATHS);+const COMPAT_MIRROR_KEYS = Object.keys(COMPAT_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 isPopulatedMirror = (value: unknown) => {+ if (Array.isArray(value)) return value.length > 0;+ if (value && typeof value === 'object') return Object.keys(value).length > 0;+ // A scalar mirror (`enableExpertise`) always carries its decision.+ return true;+};const LEGACY_KEYS = Object.keys(LEGACY_KEY_PATHS);@@ -123,18 +146,18 @@ const setIfAbsent = (root: Record<string, unknown>, path: readonly string[], val** 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}.+ * {@link LEGACY_MIRROR_PATHS}. The run policies and the expertise snapshot are+ * lifted but deliberately left in place for now β see {@link COMPAT_MIRROR_PATHS}.*/export const normalizeAgentState = <T extends AgentState>(state: T): T => {const metadata = state.metadata;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 topLevel = state as unknown as Record<string, unknown>;+ const hasMirror = (key: string) => isPresent(topLevel, key) && isPopulatedMirror(topLevel[key]);+ const mirrorKeys = LEGACY_MIRROR_KEYS.filter(hasMirror);+ const compatKeys = COMPAT_MIRROR_KEYS.filter(hasMirror);+ if (!hasLegacyMetadata && mirrorKeys.length === 0 && compatKeys.length === 0) return state;const next = { ...state } as Record<string, unknown>;@@ -150,20 +173,21 @@ export const normalizeAgentState = <T extends AgentState>(state: T): T => {next.metadata = strippedMetadata;}+ // Lifted and left in place: the old build still reads these (see above).+ for (const key of compatKeys) {+ setIfAbsent(next, COMPAT_MIRROR_PATHS[key], topLevel[key]);+ }+if (mirrorKeys.length > 0) {for (const key of mirrorKeys) {- setIfAbsent(- next,- LEGACY_MIRROR_PATHS[key],- (state as unknown as Record<string, unknown>)[key],- );+ setIfAbsent(next, LEGACY_MIRROR_PATHS[key], topLevel[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 = [];+ const toolSet = next.operationToolSet as Record<string, unknown> | undefined;+ if (toolSet && toolSet.enabledToolIds === undefined) toolSet.enabledToolIds = [];}return next as T;diff --git a/packages/agent-runtime/src/utils/stateSlots.ts b/packages/agent-runtime/src/utils/stateSlots.tsnew file mode 100644index 00000000000..9727c71fa57--- /dev/null+++ b/packages/agent-runtime/src/utils/stateSlots.ts@@ -0,0 +1,29 @@+import type { AgentState } from '../types';++/**+ * Read the run's policy and world facts from their typed slots.+ *+ * Each of these used to sit at the top level of the state; the slots say who+ * decided them and when (`principal.policy` is fixed per turn, `world` is what+ * the model is told). The legacy top-level copy is still accepted: a blob+ * written before the move is lifted by `normalizeAgentState` on load, but an+ * in-memory state a host assembles by hand may still carry the old shape, and a+ * missed intervention config would silently park a background run for approval.+ */+export const selectSecurityBlacklist = (+ state: Pick<AgentState, 'principal' | 'securityBlacklist'>,+): AgentState['securityBlacklist'] =>+ state.principal?.policy?.securityBlacklist ?? state.securityBlacklist;++export const selectUserInterventionConfig = (+ state: Pick<AgentState, 'principal' | 'userInterventionConfig'>,+): AgentState['userInterventionConfig'] =>+ state.principal?.policy?.userIntervention ?? state.userInterventionConfig;++export const selectExpertise = (+ state: Pick<AgentState, 'expertise' | 'world'>,+): AgentState['expertise'] => state.world?.expertise ?? state.expertise;++export const selectEnableExpertise = (+ state: Pick<AgentState, 'enableExpertise' | 'world'>,+): boolean | undefined => state.world?.enableExpertise ?? state.enableExpertise;diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 564ca4094ec..b8640c879fc 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -368,7 +368,8 @@ export class StreamingExecutorActionImpl {sourceMap: {},tools: toolsDetailed.tools ?? [],},- userInterventionConfig,+ // What this run may do β the approval mode its tool calls answer to.+ principal: { policy: { userIntervention: userInterventionConfig } },});const state: AgentState = {...baseState,