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): carve typed world/binding slots out of state.metadata (#19498)

Arvin Xu73a052854699
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index b0e7976a629..c401ca23dcb 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -2,6 +2,7 @@ import {
type AgentEvent,
type AgentRuntimeContext,
type AgentState,
+ normalizeAgentState,
} from '@lobechat/agent-runtime';
import debug from 'debug';
import { type Redis } from 'ioredis';
@@ -181,7 +182,9 @@ export class AgentStateManager {
return null;
}
- const state = JSON.parse(serializedState) as AgentState;
+ // Blobs written before the typed `world` / `binding` slots existed carry
+ // that context in `metadata`; lift it once here so readers see one shape.
+ const state = normalizeAgentState(JSON.parse(serializedState) as AgentState);
log('[%s] Loaded state (step %d)', operationId, state.stepCount);
return state;
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index c65565e0e5e..2a9ad096bf1 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -252,7 +252,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
void this.pushEvent(operationId, {
// Share-visitor runs must not receive the creator's raw AgentState
- // (metadata.userMemory / metadata.agentConfig, systemRole,
+ // (world.userMemory / world.agent, systemRole,
// userInterventionConfig, ...) over their WS channel β€” see
// `buildPublicEndEventData`.
data: endRedaction ? buildPublicEndEventData(endEventData) : endEventData,
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
index f16571992af..c6e7ac186b7 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryAgentStateManager.ts
@@ -1,4 +1,4 @@
-import { type AgentState } from '@lobechat/agent-runtime';
+import { type AgentState, normalizeAgentState } from '@lobechat/agent-runtime';
import debug from 'debug';
import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';
@@ -46,7 +46,7 @@ export class InMemoryAgentStateManager implements IAgentStateManager {
log('[%s] Loaded state (step %d)', operationId, state.stepCount);
// Return deep clone to prevent external modifications from affecting internal state
- return structuredClone(state);
+ return normalizeAgentState(structuredClone(state));
}
async saveStepResult(operationId: string, stepResult: StepResult): Promise<void> {
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index bb6508878cc..f9612289baf 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -1,6 +1,6 @@
import { type AgentState } from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
-import { ToolNameResolver } from '@lobechat/context-engine';
+import { type AgentGroupConfig, ToolNameResolver } from '@lobechat/context-engine';
import { consumeStreamUntilDone, ModelEmptyError } from '@lobechat/model-runtime';
import type * as ModelBank from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -409,18 +409,6 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);
const executors = createRuntimeExecutors({
...ctx,
- agentConfig: {
- chatConfig: {},
- plugins: [],
- systemRole: 'test',
- },
- searchDecision: {
- enabledSearch: true,
- isModelHasBuiltinSearch: false,
- isProviderHasBuiltinSearch: true,
- useApplicationBuiltinSearchTool: false,
- useModelSearch: true,
- },
});
await executors.call_llm!(
@@ -433,7 +421,22 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
type: 'call_llm' as const,
},
- createMockState(),
+ createMockState({
+ world: {
+ agent: {
+ chatConfig: {},
+ plugins: [],
+ systemRole: 'test',
+ },
+ searchDecision: {
+ enabledSearch: true,
+ isModelHasBuiltinSearch: false,
+ isProviderHasBuiltinSearch: true,
+ useApplicationBuiltinSearchTool: false,
+ useModelSearch: true,
+ },
+ },
+ }),
);
expect(mockChat).toHaveBeenCalledWith(
@@ -463,9 +466,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const engineSpy = vi.spyOn(ContextEngineering, 'serverMessagesEngine');
const executors = createRuntimeExecutors({
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
});
const state = createMockState({
+ world: { agent: { plugins: [], systemRole: 'test' } },
operationToolSet: {
enabledToolIds: ['workspace'],
manifestMap: {
@@ -873,15 +876,17 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { preserveThinking: true },
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { preserveThinking: true },
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
modelRuntimeConfig: {
model: 'qwen3.6-plus',
provider: 'qwen',
@@ -954,15 +959,17 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { preserveThinking: true },
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { preserveThinking: true },
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
modelRuntimeConfig: {
model: 'qwen3.6-plus',
provider: 'qwen',
@@ -1000,15 +1007,17 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { preserveThinking: false },
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { preserveThinking: false },
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
modelRuntimeConfig: {
model: 'kimi-k2.7-code',
provider: 'moonshot',
@@ -1046,15 +1055,17 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { preserveThinking: false },
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { preserveThinking: false },
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
modelRuntimeConfig: {
model: 'kimi-k2.7-code',
provider: BRANDING_PROVIDER,
@@ -1092,15 +1103,17 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { preserveThinking: true },
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { preserveThinking: true },
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
modelRuntimeConfig: {
model: 'my-qwen-custom-deployment',
provider: 'qwen',
@@ -1138,15 +1151,17 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { preserveThinking: true },
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { preserveThinking: true },
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
modelRuntimeConfig: {
model: 'gpt-4',
provider: 'openai',
@@ -1406,10 +1421,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
// reasoning_part capture via the state replay path.
const ctxWithThinking: RuntimeExecutorContext = {
...ctx,
- agentConfig: { chatConfig: { preserveThinking: true }, plugins: [], systemRole: 'test' },
};
const executors = createRuntimeExecutors(ctxWithThinking);
- const result = await executors.call_llm!(geminiInstruction(), createMockState());
+ const result = await executors.call_llm!(
+ geminiInstruction(),
+ createMockState({
+ world: {
+ agent: { chatConfig: { preserveThinking: true }, plugins: [], systemRole: 'test' },
+ },
+ }),
+ );
expect(result.newState.messages.at(-1)).toEqual(
expect.objectContaining({
@@ -2185,6 +2206,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
sourceMap: {},
tools: [],
},
+ world: { agent: { plugins: [], systemRole: 'test' } as any },
...overrides,
});
@@ -2195,7 +2217,6 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
) => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
...contextOverrides,
};
await createRuntimeExecutors(ctxWithConfig).call_llm!(
@@ -2350,13 +2371,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should process messages through serverMessagesEngine when agentConfig is set', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- plugins: [],
- systemRole: 'You are a helpful assistant',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ plugins: [],
+ systemRole: 'You are a helpful assistant',
+ },
+ },
+ });
const instruction = {
payload: {
@@ -2390,7 +2414,6 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should forward additional contexts without leaking model parameters', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
};
const additionalContexts = [
{
@@ -2418,7 +2441,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
},
type: 'call_llm',
},
- createMockState(),
+ createMockState({ world: { agent: { plugins: [], systemRole: 'test' } } }),
);
expect(engineSpy).toHaveBeenCalledWith(expect.objectContaining({ additionalContexts }));
@@ -2431,13 +2454,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should pass model knowledge cutoff into serverMessagesEngine', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- plugins: [],
- systemRole: 'You are a helpful assistant',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ plugins: [],
+ systemRole: 'You are a helpful assistant',
+ },
+ },
+ });
const instruction = {
payload: {
@@ -2458,13 +2484,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should resolve LobeHub routed model knowledge cutoff by model id fallback', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- plugins: [],
- systemRole: 'You are a helpful assistant',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ plugins: [],
+ systemRole: 'You are a helpful assistant',
+ },
+ },
+ });
await executors.call_llm!(
{
@@ -2486,13 +2515,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should omit model knowledge cutoff for unknown non-LobeHub providers', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- plugins: [],
- systemRole: 'You are a helpful assistant',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ plugins: [],
+ systemRole: 'You are a helpful assistant',
+ },
+ },
+ });
await executors.call_llm!(
{
@@ -2512,13 +2544,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should keep current turn when agent historyCount is 0', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { enableHistoryCount: true, historyCount: 0 },
- plugins: [],
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { enableHistoryCount: true, historyCount: 0 },
+ plugins: [],
+ },
+ },
+ });
const instruction = {
payload: {
@@ -2552,13 +2587,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should strip stored assistant reasoning before context processing when replay gate is off', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
+ });
const messages = [
{
content: 'Previous answer',
@@ -2595,13 +2633,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should strip stored reasoning from grouped assistant messages before context processing when replay gate is off', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
+ });
const groupedChild = {
content: 'Grouped answer',
id: 'group-child-1',
@@ -2668,14 +2709,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should keep stored assistant reasoning before context processing when replay gate is enabled', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- chatConfig: { preserveThinking: true },
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ chatConfig: { preserveThinking: true },
+ plugins: [],
+ systemRole: 'test',
+ },
+ },
modelRuntimeConfig: {
model: 'qwen3.6-plus',
provider: 'qwen',
@@ -2739,10 +2782,12 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should pass forceFinish flag to serverMessagesEngine and inject summary', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState({ forceFinish: true });
+ const state = createMockState({
+ world: { agent: { plugins: [], systemRole: 'test' } },
+ forceFinish: true,
+ });
const instruction = {
payload: {
@@ -2773,11 +2818,11 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
const evalContext = { expectedOutput: 'test answer', evalMode: true };
const ctxWithEval: RuntimeExecutorContext = {
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
- evalContext: evalContext as any,
};
const executors = createRuntimeExecutors(ctxWithEval);
- const state = createMockState();
+ const state = createMockState({
+ world: { agent: { plugins: [], systemRole: 'test' }, eval: evalContext as any },
+ });
const instruction = {
payload: {
@@ -2796,9 +2841,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('forwards the bot-originated agent identity snapshot to serverMessagesEngine', async () => {
// The bot/group member roster is resolved once at op creation
// (AiAgentService.execAgent β†’ buildBotConversationGroupContext) and
- // snapshotted into op metadata as `agentGroup`. The per-step executor no
+ // snapshotted into the op's world slot as `group`. The per-step executor no
// longer rebuilds it β€” it just forwards the snapshot to the engine.
- const agentGroup = {
+ const agentGroup: AgentGroupConfig = {
agentMap: {
'agent-support': {
name: 'Support Bot',
@@ -2819,12 +2864,6 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
};
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- description: 'Answers customer support questions.',
- plugins: [],
- systemRole: 'test',
- title: 'Support Bot',
- },
botContext: {
applicationId: 'discord-app',
isOwner: true,
@@ -2835,8 +2874,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
};
const executors = createRuntimeExecutors(ctxWithConfig);
const state = createMockState({
+ world: {
+ agent: {
+ description: 'Answers customer support questions.',
+ plugins: [],
+ systemRole: 'test',
+ title: 'Support Bot',
+ },
+ group: agentGroup,
+ },
metadata: {
- agentGroup,
agentId: 'agent-support',
botContext: ctxWithConfig.botContext,
topicId: 'topic-123',
@@ -2860,10 +2907,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should build capabilities from LOBE_DEFAULT_MODEL_LIST', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({ world: { agent: { plugins: [], systemRole: 'test' } } });
const instruction = {
payload: {
@@ -2905,22 +2951,25 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should filter disabled files and knowledgeBases from agentConfig', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- files: [
- { content: 'yes', enabled: true, id: 'f1', name: 'enabled.pdf' },
- { content: 'no', enabled: false, id: 'f2', name: 'disabled.pdf' },
- { content: 'maybe', enabled: null, id: 'f3', name: 'null.pdf' },
- ],
- knowledgeBases: [
- { enabled: true, id: 'kb1', name: 'Enabled KB' },
- { enabled: false, id: 'kb2', name: 'Disabled KB' },
- ],
- plugins: [],
- systemRole: 'test',
- },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ files: [
+ { content: 'yes', enabled: true, id: 'f1', name: 'enabled.pdf' },
+ { content: 'no', enabled: false, id: 'f2', name: 'disabled.pdf' },
+ { content: 'maybe', enabled: null, id: 'f3', name: 'null.pdf' },
+ ],
+ knowledgeBases: [
+ { enabled: true, id: 'kb1', name: 'Enabled KB' },
+ { enabled: false, id: 'kb2', name: 'Disabled KB' },
+ ],
+ plugins: [],
+ systemRole: 'test',
+ } as any,
+ },
+ });
const instruction = {
payload: {
@@ -2954,10 +3003,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should skip topic reference resolution when messages already contain topic_reference_context', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({ world: { agent: { plugins: [], systemRole: 'test' } } });
const instruction = {
payload: {
@@ -2984,10 +3032,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should resolve topic references when messages do not contain topic_reference_context', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: { plugins: [], systemRole: 'test' },
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({ world: { agent: { plugins: [], systemRole: 'test' } } });
const instruction = {
payload: {
@@ -3009,14 +3056,17 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should skip rebuilding onboarding context when messages already contain onboarding injection', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
- agentConfig: {
- plugins: ['lobe-web-onboarding'],
- slug: 'web-onboarding',
- systemRole: 'test',
- } as any,
};
const executors = createRuntimeExecutors(ctxWithConfig);
- const state = createMockState();
+ const state = createMockState({
+ world: {
+ agent: {
+ plugins: ['lobe-web-onboarding'],
+ slug: 'web-onboarding',
+ systemRole: 'test',
+ } as any,
+ },
+ });
const instruction = {
payload: {
@@ -4832,12 +4882,14 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
it('should pass toolResultMaxLength from agentConfig to executeTool', async () => {
const executors = createRuntimeExecutors(ctx);
const state = createMockState({
- metadata: {
- agentConfig: {
+ world: {
+ agent: {
chatConfig: {
toolResultMaxLength: 5000,
},
},
+ },
+ metadata: {
agentId: 'agent-123',
threadId: 'thread-123',
topicId: 'topic-123',
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts
index 35a515e9386..8a423a1526a 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts
@@ -7,9 +7,9 @@ import { buildServerAgentMemberRunner, buildServerVirtualSubAgentRunner } from '
/**
* The parent model a spawned `callSubAgent` follows must be the model the
- * parent run ACTUALLY uses. `metadata.agentConfig` alone is not enough: when a
+ * parent run ACTUALLY uses. `world.agent` alone is not enough: when a
* run continues a topic whose model was switched, execAgent keeps the
- * topic-pinned model only in `modelRuntimeConfig` while the metadata config
+ * topic-pinned model only in `modelRuntimeConfig` while the world config
* retains the agent default.
*/
describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {
@@ -36,12 +36,11 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {
return { execVirtualSubAgent, runner };
};
- it('follows the topic-pinned runtime model over the metadata agent default', async () => {
+ it('follows the topic-pinned runtime model over the world agent default', async () => {
const { execVirtualSubAgent, runner } = buildRunner({
- metadata: {
- agentConfig: { model: 'agent-default-model', provider: 'agent-default-provider' },
- agentId: 'agent-1',
- topicId: 'topic-1',
+ metadata: { agentId: 'agent-1', topicId: 'topic-1' },
+ world: {
+ agent: { model: 'agent-default-model', provider: 'agent-default-provider' } as any,
},
modelRuntimeConfig: { model: 'topic-pinned-model', provider: 'topic-pinned-provider' },
});
@@ -53,12 +52,11 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {
);
});
- it('falls back to the metadata agent config when no runtime model exists', async () => {
+ it('falls back to the world agent config when no runtime model exists', async () => {
const { execVirtualSubAgent, runner } = buildRunner({
- metadata: {
- agentConfig: { model: 'agent-default-model', provider: 'agent-default-provider' },
- agentId: 'agent-1',
- topicId: 'topic-1',
+ metadata: { agentId: 'agent-1', topicId: 'topic-1' },
+ world: {
+ agent: { model: 'agent-default-model', provider: 'agent-default-provider' } as any,
},
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index 1c9422f55a2..db61504c29a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -197,7 +197,7 @@ export class ServerToolTransport implements ToolTransport {
() =>
toolExecutionService.executeTool(chatToolPayload, {
activatedSkills: context.activatedSkills as any,
- activeDeviceId: resolveRunActiveDeviceId(context.state.metadata),
+ activeDeviceId: resolveRunActiveDeviceId(context.state),
activeDeviceScope: context.state.metadata?.activeDeviceScope,
agentId: context.state.metadata?.agentId,
agentMember: buildServerAgentMemberRunner(
@@ -230,14 +230,13 @@ export class ServerToolTransport implements ToolTransport {
// and telling the device otherwise would fence the wrong run.
localSandbox: context.state.metadata?.executionPlan
? isLocalSandboxEnabled(
- context.state.metadata?.agentConfig?.agencyConfig,
+ context.state.world?.agent?.agencyConfig,
context.state.metadata.executionPlan.target,
)
: undefined,
localSandboxNetwork:
- context.state.metadata?.agentConfig?.agencyConfig?.localSandboxNetwork === true,
- memoryToolPermission:
- context.state.metadata?.agentConfig?.chatConfig?.memory?.toolPermission,
+ context.state.world?.agent?.agencyConfig?.localSandboxNetwork === true,
+ memoryToolPermission: context.state.world?.agent?.chatConfig?.memory?.toolPermission,
messageId: context.state.metadata?.sourceMessageId,
operationId,
projectSkills: resolveRunProjectSkills(context.state.metadata),
@@ -259,7 +258,7 @@ export class ServerToolTransport implements ToolTransport {
toolResultMaxLength: context.toolResultMaxLength,
topicId: this.ctx.topicId,
userId,
- workingDirectory: context.state.metadata?.deviceSystemInfo?.workingDirectory,
+ workingDirectory: context.state.binding?.device?.systemInfo?.workingDirectory,
workspaceId: context.state.metadata?.workspaceId ?? this.ctx.workspaceId,
}),
{
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
index 835e0f3aa22..8ab1dc18dab 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
@@ -3,7 +3,8 @@ import { describe, expect, it } from 'vitest';
import { resolveServerCallLlmTooling } from '../serverCallLlmTooling';
-const buildState = (metadata?: AgentState['metadata']): AgentState => ({ metadata }) as AgentState;
+const buildState = (state: Pick<AgentState, 'binding' | 'metadata'> = {}): AgentState =>
+ state as AgentState;
describe('resolveServerCallLlmTooling', () => {
// Regression: `serverCallLlmContextBuilder` needs this to compute
@@ -16,9 +17,9 @@ describe('resolveServerCallLlmTooling', () => {
const result = resolveServerCallLlmTooling(
{ operationId: 'op-1', stepIndex: 0 },
buildState({
- activeDeviceId: 'device-1',
- executionPlan: { deviceId: 'device-1', kind: 'device' },
- } as AgentState['metadata']),
+ binding: { device: { id: 'device-1' } },
+ metadata: { executionPlan: { deviceId: 'device-1', kind: 'device' } },
+ }),
);
expect(result.activeDeviceId).toBe('device-1');
@@ -27,13 +28,13 @@ describe('resolveServerCallLlmTooling', () => {
it('leaves the active device id undefined when no device is routed', () => {
const result = resolveServerCallLlmTooling(
{ operationId: 'op-1', stepIndex: 0 },
- buildState({ executionPlan: { kind: 'sandbox' } } as AgentState['metadata']),
+ buildState({ metadata: { executionPlan: { kind: 'sandbox' } } }),
);
expect(result.activeDeviceId).toBeUndefined();
});
- it('leaves the active device id undefined with no metadata at all', () => {
+ it('leaves the active device id undefined with no binding at all', () => {
const result = resolveServerCallLlmTooling({ operationId: 'op-1', stepIndex: 0 }, buildState());
expect(result.activeDeviceId).toBeUndefined();
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts
index 2f4e9dc9de0..270d3bd536a 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts
@@ -1,4 +1,4 @@
-import type { AgentState, CallLLMPayload } from '@lobechat/agent-runtime';
+import type { AgentState, AgentWorldSnapshot, CallLLMPayload } from '@lobechat/agent-runtime';
import type { ResolvedToolSet } from '@lobechat/context-engine';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -53,7 +53,6 @@ vi.mock('@/server/modules/Mecha/ContextEngineering', () => ({
const createCtx = (overrides: Partial<RuntimeExecutorContext> = {}): RuntimeExecutorContext =>
({
- agentConfig: { chatConfig: {}, files: [], knowledgeBases: [] } as any,
messageModel: {} as RuntimeExecutorContext['messageModel'],
operationId: 'operation-1',
serverDB: {} as RuntimeExecutorContext['serverDB'],
@@ -65,7 +64,14 @@ const createCtx = (overrides: Partial<RuntimeExecutorContext> = {}): RuntimeExec
}) satisfies RuntimeExecutorContext;
const llmPayload = { messages: [] } as unknown as CallLLMPayload;
-const state = { metadata: {} } as unknown as AgentState;
+const agent = {
+ chatConfig: {},
+ files: [],
+ knowledgeBases: [],
+} as unknown as AgentWorldSnapshot['agent'];
+const createState = (overrides: Partial<AgentState> = {}): AgentState =>
+ ({ metadata: {}, world: { agent }, ...overrides }) as unknown as AgentState;
+const state = createState();
const tooling = {
resolved: {
enabledToolIds: [],
@@ -106,15 +112,15 @@ beforeEach(() => {
* received anything. So each link gets an assertion of its own.
*/
describe('buildServerCallLlmContext - system-message context reaches the engine', () => {
- it('forwards the project instructions off the operation context', async () => {
+ it('forwards the project instructions off the world snapshot', async () => {
const projectInstructions = [{ content: 'Use bun.', source: 'AGENTS.md' }];
await buildServerCallLlmContext({
- ctx: createCtx({ projectInstructions }),
+ ctx: createCtx(),
llmPayload,
model: 'gpt-4',
provider: 'openai',
- state,
+ state: createState({ world: { agent, projectInstructions } }),
tooling,
});
@@ -123,13 +129,15 @@ describe('buildServerCallLlmContext - system-message context reaches the engine'
);
});
- it('forwards the connector ownership note off the operation context', async () => {
+ it('forwards the connector ownership note off the world snapshot', async () => {
await buildServerCallLlmContext({
- ctx: createCtx({ connectorOwnershipNote: 'Gmail runs on Alice’s account.' }),
+ ctx: createCtx(),
llmPayload,
model: 'gpt-4',
provider: 'openai',
- state,
+ state: createState({
+ world: { agent, connectorOwnershipNote: 'Gmail runs on Alice’s account.' },
+ }),
tooling,
});
@@ -210,7 +218,7 @@ describe('buildServerCallLlmContext - workspace context', () => {
llmPayload,
model: 'gpt-4',
provider: 'openai',
- state: { metadata: { workspaceId: 'workspace-2' } } as unknown as AgentState,
+ state: createState({ metadata: { workspaceId: 'workspace-2' } }),
tooling,
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index fc4aeb3c668..d8bd67a1328 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -13,7 +13,6 @@ import { AGENT_PLAN_FILE_TYPE, COMPOSIO_APP_TYPES } from '@lobechat/const';
import type {
AgentBuilderContext,
AgentContextDocument,
- AgentGroupConfig,
GroupAgentBuilderContext,
GroupOfficialToolItem,
OfficialToolItem,
@@ -81,7 +80,7 @@ export const buildServerCallLlmContext = async ({
state,
tooling,
}: BuildServerCallLlmContextInput): Promise<ServerCallLlmContextBuildResult> => {
- const agentConfig = ctx.agentConfig;
+ const agentConfig = state.world?.agent;
if (!agentConfig) {
return {
processedMessages: llmPayload.messages as ChatStreamPayload['messages'],
@@ -97,6 +96,7 @@ export const buildServerCallLlmContext = async ({
llmPayload,
model,
provider,
+ world: state.world,
});
const {
capabilities,
@@ -278,7 +278,7 @@ export const buildServerCallLlmContext = async ({
// model's prompt without needing a separate context injector.
const lobehubSkillAgentId = state.metadata?.agentId;
const lobehubSkillTopicId = ctx.topicId ?? state.metadata?.topicId;
- const lobehubSkillAgentMeta = state.metadata?.agentConfig as
+ const lobehubSkillAgentMeta = state.world?.agent as
{ description?: string | null; title?: string | null } | undefined;
let lobehubSkillTopicTitle = '';
@@ -358,14 +358,12 @@ export const buildServerCallLlmContext = async ({
const sessionDate = new Intl.DateTimeFormat('en-US', {
day: 'numeric',
month: 'long',
- timeZone: ctx.userTimezone || 'UTC',
+ timeZone: state.world?.userTimezone || 'UTC',
weekday: 'long',
year: 'numeric',
}).format(new Date());
- const memoryEffort = String(
- (state.metadata?.agentConfig as any)?.chatConfig?.memory?.effort ?? '',
- );
+ const memoryEffort = String(agentConfig.chatConfig?.memory?.effort ?? '');
const messageTodos = extractTodosFromMessages(messagesForContext);
let planTodo: PlanTodoConfig | undefined =
@@ -671,14 +669,14 @@ export const buildServerCallLlmContext = async ({
// the model introduces itself by the user-given name.
agentIdentity: { name: agentConfig.name ?? undefined, title: agentConfig.title ?? undefined },
...(agentBuilderContext && { agentBuilderContext }),
- agentGroup: state.metadata?.agentGroup as AgentGroupConfig | undefined,
+ agentGroup: state.world?.group,
agentManagementContext: (state as any).initialContext?.initialContext?.mentionedAgents?.length
? {
mentionedAgents: (state as any).initialContext.initialContext.mentionedAgents,
}
: undefined,
additionalVariables: {
- ...state.metadata?.deviceSystemInfo,
+ ...state.binding?.device?.systemInfo,
...lobehubSkillVariables,
COMPOSIO_SERVICES_LIST: composioServicesListStr,
CREDS_LIST: credsListStr,
@@ -693,14 +691,14 @@ export const buildServerCallLlmContext = async ({
session_date: sessionDate,
username: serverUsername,
},
- userTimezone: ctx.userTimezone,
+ userTimezone: state.world?.userTimezone,
capabilities,
- botPlatformContext: ctx.botPlatformContext,
+ botPlatformContext: state.world?.channel?.botPlatform,
...(workspaceContext && { workspaceContext }),
- discordContext: ctx.discordContext,
+ discordContext: state.world?.channel?.discord,
enableExpertise: state.enableExpertise,
enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,
- evalContext: ctx.evalContext,
+ evalContext: state.world?.eval,
expertise: state.expertise,
forceFinish: state.forceFinish,
...(groupAgentBuilderContext && { groupAgentBuilderContext }),
@@ -727,15 +725,15 @@ export const buildServerCallLlmContext = async ({
modelKnowledgeCutoff,
provider,
...(planTodo && { planTodo }),
- connectorOwnershipNote: ctx.connectorOwnershipNote,
- projectInstructions: ctx.projectInstructions,
+ connectorOwnershipNote: state.world?.connectorOwnershipNote,
+ projectInstructions: state.world?.projectInstructions,
systemRole: agentConfig.systemRole ?? undefined,
toolDiscoveryConfig,
toolsConfig: {
manifests: Object.values(resolved.promptManifestMap),
tools: resolved.enabledToolIds,
},
- userMemory: state.metadata?.userMemory,
+ userMemory: state.world?.userMemory,
...(resolvedSkills?.enabledSkills?.length && {
skillsConfig: { enabledSkills: resolvedSkills.enabledSkills },
}),
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
index 243d087a22a..c3093608b05 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
@@ -33,9 +33,8 @@ vi.mock('@/database/models/topic', () => ({
},
}));
-const createCtx = (agentConfig: any): RuntimeExecutorContext =>
+const createCtx = (): RuntimeExecutorContext =>
({
- agentConfig,
messageModel: {} as RuntimeExecutorContext['messageModel'],
operationId: 'operation-1',
serverDB: {} as RuntimeExecutorContext['serverDB'],
@@ -96,7 +95,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
}
const hints = await resolveServerCallLlmContextHints({
ctx: {
- ...createCtx({}),
+ ...createCtx(),
modelRuntimeConfig: {
mediaCapabilities: { vision: true },
model: 'custom-model',
@@ -118,7 +117,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
])('does not reuse a snapshot for $model/$provider', async ({ model, provider }) => {
const hints = await resolveServerCallLlmContextHints({
ctx: {
- ...createCtx({}),
+ ...createCtx(),
modelRuntimeConfig: {
mediaCapabilities: { vision: true },
model: 'custom-model',
@@ -137,7 +136,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
findByIdAndProviderMock.mockResolvedValue({ abilities: { vision: true } });
const hints = await resolveServerCallLlmContextHints({
ctx: {
- ...createCtx({}),
+ ...createCtx(),
modelRuntimeConfig: {
mediaCapabilities: {},
model: 'custom-model',
@@ -157,7 +156,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
const model = 'custom-vision-model';
const provider = 'custom-provider';
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({}),
+ ctx: createCtx(),
llmPayload,
model,
provider,
@@ -200,7 +199,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
]);
findByIdAndProviderMock.mockResolvedValue({ abilities: { [ability]: true } });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({}),
+ ctx: createCtx(),
llmPayload,
model: 'model',
provider: 'provider',
@@ -227,7 +226,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
]);
findByIdAndProviderMock.mockResolvedValue({ abilities });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({}),
+ ctx: createCtx(),
llmPayload,
model: 'model',
provider: 'provider',
@@ -238,7 +237,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
it('does not apply the active row to a different model under the same provider', async () => {
findByIdAndProviderMock.mockResolvedValue({ abilities: { vision: true } });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({}),
+ ctx: createCtx(),
llmPayload,
model: 'custom-model',
provider: 'custom-provider',
@@ -248,7 +247,7 @@ describe('resolveServerCallLlmContextHints - user media capabilities', () => {
});
describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
- const ctxWithTopic = (agentConfig: any) => ({ ...createCtx(agentConfig), topicId: 'topic-1' });
+ const ctxWithTopic = () => ({ ...createCtx(), topicId: 'topic-1' });
it.each([
['supervisor', 'high'],
@@ -263,7 +262,8 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
provider: 'openai',
});
const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({ id, chatConfig: {} }),
+ ctx: ctxWithTopic(),
+ world: { agent: { id, chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -280,7 +280,8 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
});
const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({ chatConfig: {} }),
+ ctx: ctxWithTopic(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -299,7 +300,8 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
});
await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({ chatConfig: {} }),
+ ctx: ctxWithTopic(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -323,7 +325,8 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
});
const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({ chatConfig: {} }),
+ ctx: ctxWithTopic(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -342,7 +345,8 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
});
const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({ chatConfig: {} }),
+ ctx: ctxWithTopic(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -357,7 +361,8 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
findTopicByIdMock.mockResolvedValue({ metadata: {}, model: 'gpt-4', provider: 'openai' });
const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({ chatConfig: {} }),
+ ctx: ctxWithTopic(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -374,10 +379,13 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
});
const hints = await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({
- chatConfig: {},
- subAgentChatConfigOverride: { reasoningEffort: 'medium' },
- }),
+ ctx: ctxWithTopic(),
+ world: {
+ agent: {
+ chatConfig: {},
+ subAgentChatConfigOverride: { reasoningEffort: 'medium' },
+ },
+ },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -388,7 +396,8 @@ describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
it('should not read the topic for models without reasoning extend params', async () => {
await resolveServerCallLlmContextHints({
- ctx: ctxWithTopic({ chatConfig: {} }),
+ ctx: ctxWithTopic(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4o-mini',
provider: 'openai',
@@ -430,7 +439,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
{ content: 'Continue', id: 'user-2', role: 'user' },
];
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: { preserveThinking } }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: { preserveThinking } } },
llmPayload: { messages } as unknown as CallLLMPayload,
model,
provider,
@@ -455,7 +465,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: {} }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -473,7 +484,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: {} }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'my-custom-model',
provider: 'custom-provider',
@@ -492,7 +504,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: {} }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4o-mini',
provider: 'openai',
@@ -510,7 +523,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: {} }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -522,7 +536,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
it('should skip the reasoning config DB read for models without reasoning extend params', async () => {
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: {} }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'gpt-4o-mini',
provider: 'openai',
@@ -534,7 +549,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
it('should ignore stale reasoning fields left in agent chatConfig', async () => {
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: { reasoningEffort: 'low' } }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: { reasoningEffort: 'low' } } },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -547,7 +563,7 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'medium' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({}),
+ ctx: createCtx(),
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -560,10 +576,13 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({
- chatConfig: {},
- subAgentChatConfigOverride: { reasoningEffort: 'high' },
- }),
+ ctx: createCtx(),
+ world: {
+ agent: {
+ chatConfig: {},
+ subAgentChatConfigOverride: { reasoningEffort: 'high' },
+ },
+ },
llmPayload,
model: 'gpt-4',
provider: 'openai',
@@ -577,7 +596,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
const hints = await resolveServerCallLlmContextHints({
// stale agent value says 'high', but the instance config opts out
- ctx: createCtx({ chatConfig: { deepseekV4ReasoningEffort: 'high' } }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: { deepseekV4ReasoningEffort: 'high' } } },
llmPayload,
model: 'deepseek-v4-pro',
provider: 'deepseek',
@@ -591,7 +611,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ deepseekV4GAReasoningEffort: 'none' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: { deepseekV4GAReasoningEffort: 'high' } }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: { deepseekV4GAReasoningEffort: 'high' } } },
llmPayload,
model: 'deepseek-v4-flash',
provider: 'deepseek',
@@ -611,7 +632,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
getModelReasoningConfigMock.mockResolvedValue({ deepseekV4ReasoningEffort: 'none' });
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: {} }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'deepseek-v4-flash',
provider: 'deepseek',
@@ -623,7 +645,8 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
it('should keep DeepSeek V4 forced reasoning replay when no opt-out is saved', async () => {
const hints = await resolveServerCallLlmContextHints({
- ctx: createCtx({ chatConfig: {} }),
+ ctx: createCtx(),
+ world: { agent: { chatConfig: {} } },
llmPayload,
model: 'deepseek-v4-pro',
provider: 'deepseek',
@@ -633,7 +656,7 @@ describe('resolveServerCallLlmContextHints - model-instance reasoning config', (
});
it('should not read the instance config when the ctx has no user scope', async () => {
- const ctx = createCtx({ chatConfig: {} });
+ const ctx = createCtx();
ctx.userId = undefined;
await resolveServerCallLlmContextHints({
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
index 728923b9e01..a48814ccdc6 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
@@ -1,4 +1,8 @@
-import { type CallLLMPayload, stripAssistantReasoningForReplay } from '@lobechat/agent-runtime';
+import {
+ type AgentWorldSnapshot,
+ type CallLLMPayload,
+ stripAssistantReasoningForReplay,
+} from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import {
applyModelExtendParams,
@@ -29,6 +33,7 @@ interface ResolveServerCallLlmContextHintsInput {
llmPayload: CallLLMPayload;
model: string;
provider: string;
+ world?: AgentWorldSnapshot;
}
export interface ServerCallLlmContextHints {
@@ -148,8 +153,9 @@ export const resolveServerCallLlmContextHints = async ({
llmPayload,
model,
provider,
+ world,
}: ResolveServerCallLlmContextHintsInput): Promise<ServerCallLlmContextHints> => {
- const agentConfig = ctx.agentConfig;
+ const agentConfig = world?.agent;
const { loadModels } = await import('@/business/client/model-bank/loadModels');
const builtinModels = await loadModels();
@@ -208,7 +214,7 @@ export const resolveServerCallLlmContextHints = async ({
if (
topic?.model === model &&
topic.provider === provider &&
- (!topic.groupId || topic.agentId === ctx.agentConfig?.id)
+ (!topic.groupId || topic.agentId === agentConfig?.id)
) {
modelReasoningConfig = topic.metadata?.reasoningConfig;
}
@@ -297,7 +303,7 @@ export const resolveServerCallLlmContextHints = async ({
model,
})
: undefined;
- const searchDecision = ctx.searchDecision;
+ const searchDecision = world?.searchDecision;
const enabledSearch =
searchDecision?.enabledSearch && searchDecision.useModelSearch ? true : undefined;
const resolvedExtendParams =
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
index d6ae8d0ed9b..82b829437f5 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
@@ -57,7 +57,7 @@ export const resolveServerCallLlmTooling = (
// enabled tools), so any id that reaches it WILL inject local-system.
// `resolveRunActiveDeviceId` swallows the id whenever the plan/policy
// forbids devices β€” the same filter the tool executors apply.
- const activeDeviceId = resolveRunActiveDeviceId(state.metadata);
+ const activeDeviceId = resolveRunActiveDeviceId(state);
const executionTarget = (state.metadata?.executionPlan as ExecutionPlan | undefined)?.target;
const operationToolSet: OperationToolSet = state.operationToolSet ?? {
enabledToolIds: [],
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index 7e8eff6ae87..30aa2ac3812 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -1,16 +1,13 @@
import { type AgentState } from '@lobechat/agent-runtime';
-import type { BotPlatformContext, ProjectInstructionFile } from '@lobechat/context-engine';
import {
type AgentShareVisitorContext,
type ExecSubAgentParams,
type ExecSubAgentResult,
type ExecVirtualSubAgentParams,
} from '@lobechat/types';
-import type { SearchDecision } from 'model-bank';
import { type MessageModel } from '@/database/models/message';
import { type LobeChatDatabase } from '@/database/type';
-import { type EvalContext } from '@/server/modules/Mecha/ContextEngineering/types';
import type { HookDispatcher } from '@/server/services/agentRuntime/hooks/HookDispatcher';
import type {
ExecGroupMemberParams,
@@ -27,7 +24,6 @@ export interface RuntimeExecutorContext {
* is no in-process controller to share with whoever requested the stop).
*/
abortSignal?: AbortSignal;
- agentConfig?: any;
/**
* Shared-agent visitor marker, read back from
* `state.metadata.agentShareVisitor`. Present ONLY for a share-visitor run;
@@ -45,11 +41,6 @@ export interface RuntimeExecutorContext {
*/
allowEarlyFinalAnswerVisibleOutputEnd?: boolean;
botContext?: unknown;
- botPlatformContext?: BotPlatformContext;
- /** Borrowed-connector attribution, injected into the system message. */
- connectorOwnershipNote?: string;
- discordContext?: any;
- evalContext?: EvalContext;
/**
* Callback to fork a group member ("call agent member") under a
* `lobe-group-management` tool call. Injected by AiAgentService; powers the
@@ -73,9 +64,6 @@ export interface RuntimeExecutorContext {
messageModel: MessageModel;
modelRuntimeConfig?: AgentState['modelRuntimeConfig'];
operationId: string;
- /** A project's root instruction files, injected into the system message. */
- projectInstructions?: ProjectInstructionFile[];
- searchDecision?: SearchDecision;
serverDB: LobeChatDatabase;
stepIndex: number;
stream?: boolean;
@@ -95,7 +83,6 @@ export interface RuntimeExecutorContext {
*/
tracingContextEngine?: (input: unknown, output: unknown) => void;
userId?: string;
- userTimezone?: string;
/**
* Workspace scoping for ownership filters on models/services constructed
* inside the agent runtime. Threaded down from the originating request
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index 3722c59319e..3aa121e031a 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -224,8 +224,8 @@ export const buildServerVirtualSubAgentRunner = (
const topicId = ctx.topicId ?? state.metadata?.topicId;
if (!agentId || !topicId) return undefined;
- const parentAgentConfig = state.metadata?.agentConfig as LobeAgentConfig | undefined;
- // The model the parent run ACTUALLY uses. `metadata.agentConfig` alone is not
+ const parentAgentConfig = state.world?.agent as LobeAgentConfig | undefined;
+ // The model the parent run ACTUALLY uses. `world.agent` alone is not
// enough: when a run continues a topic whose model was switched, execAgent
// keeps the topic-pinned model only in `modelRuntimeConfig` while the
// metadata config retains the agent default.
@@ -359,7 +359,7 @@ export const buildServerAgentMemberRunner = (
return {
run: async ({ members, mode, onComplete, disableTools, timeout }) => {
const agentMap = (
- state.metadata?.agentGroup as { agentMap?: Record<string, { name: string }> } | undefined
+ state.world?.group as { agentMap?: Record<string, { name: string }> } | undefined
)?.agentMap;
const resolvedMembers = members.map((member) => ({
...member,
diff --git a/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts b/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
index ca28543e55c..fc09c7927d1 100644
--- a/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/__tests__/resolveRunActiveDeviceId.test.ts
@@ -6,8 +6,8 @@ describe('resolveRunActiveDeviceId', () => {
it('passes the id through when the plan routed a device', () => {
expect(
resolveRunActiveDeviceId({
- activeDeviceId: 'device-1',
- executionPlan: { deviceId: 'device-1', kind: 'device' },
+ binding: { device: { id: 'device-1' } },
+ metadata: { executionPlan: { deviceId: 'device-1', kind: 'device' } },
}),
).toBe('device-1');
});
@@ -18,8 +18,8 @@ describe('resolveRunActiveDeviceId', () => {
it('passes a mid-run activated id through under a device-unrouted plan', () => {
expect(
resolveRunActiveDeviceId({
- activeDeviceId: 'device-1',
- executionPlan: { kind: 'device-unrouted', reason: 'no-bound-device' },
+ binding: { device: { id: 'device-1' } },
+ metadata: { executionPlan: { kind: 'device-unrouted', reason: 'no-bound-device' } },
}),
).toBe('device-1');
});
@@ -28,8 +28,8 @@ describe('resolveRunActiveDeviceId', () => {
for (const kind of ['sandbox', 'none']) {
expect(
resolveRunActiveDeviceId({
- activeDeviceId: 'device-1',
- executionPlan: { kind },
+ binding: { device: { id: 'device-1' } },
+ metadata: { executionPlan: { kind } },
}),
).toBeUndefined();
}
@@ -38,15 +38,23 @@ describe('resolveRunActiveDeviceId', () => {
it('swallows the id when the device access policy denies the sender', () => {
expect(
resolveRunActiveDeviceId({
- activeDeviceId: 'device-1',
- deviceAccessPolicy: { canUseDevice: false, reason: 'external-bot' },
- executionPlan: { deviceId: 'device-1', kind: 'device' },
+ binding: { device: { id: 'device-1' } },
+ metadata: {
+ deviceAccessPolicy: { canUseDevice: false, reason: 'external-bot' },
+ executionPlan: { deviceId: 'device-1', kind: 'device' },
+ },
}),
).toBeUndefined();
});
it('falls back to the policy-only gate when no plan exists (old/resumed operations)', () => {
- expect(resolveRunActiveDeviceId({ activeDeviceId: 'device-1' })).toBe('device-1');
- expect(resolveRunActiveDeviceId(undefined)).toBeUndefined();
+ expect(resolveRunActiveDeviceId({ binding: { device: { id: 'device-1' } } })).toBe('device-1');
+ expect(resolveRunActiveDeviceId({})).toBeUndefined();
+ });
+
+ it('ignores a device that only has system info but no id', () => {
+ expect(
+ resolveRunActiveDeviceId({ binding: { device: { systemInfo: { workingDirectory: '/w' } } } }),
+ ).toBeUndefined();
});
});
diff --git a/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
index e297dcb034d..d443efbb2c1 100644
--- a/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
+++ b/apps/server/src/modules/AgentRuntime/executors/resolveRunActiveDeviceId.ts
@@ -1,10 +1,12 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+
import { type ExecutionPlan, isDeviceCapablePlan } from '@/helpers/executionTarget';
import { type DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAudit';
/**
* Single-track device gate shared by the run executors: the execution plan
* (and the device access policy) is the only authority on whether this run
- * may touch a device. `metadata.activeDeviceId` alone is NOT sufficient β€” a
+ * may touch a device. `binding.device.id` alone is NOT sufficient β€” a
* mid-run side effect can leave it stale β€” so every consumer (LLM tool
* injection in `callLlm`, tool execution contexts in `callTool` /
* `callToolsBatch`) must read the id through this filter. Plans absent on
@@ -15,21 +17,19 @@ import { type DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAud
* (`aiAgent` sets it only for `kind === 'device'`), so an id appearing under
* a `device-unrouted` plan can only come from a legitimate mid-run activation
* β€” the model selecting a device with the `lobe-remote-device` tool, whose
- * pluginState `computeDeviceContext` folds back into the metadata at the next
- * step boundary while the plan still says unrouted. Tightening the gate to
+ * pluginState `computeDeviceContext` folds back into `binding.device` at the
+ * next step boundary while the plan still says unrouted. Tightening the gate to
* `kind === 'device'` would swallow exactly that flow.
*/
-export const resolveRunActiveDeviceId = (metadata?: {
- activeDeviceId?: string;
- deviceAccessPolicy?: unknown;
- executionPlan?: unknown;
-}): string | undefined => {
- const devicePolicy = metadata?.deviceAccessPolicy as
+export const resolveRunActiveDeviceId = (
+ state: Pick<AgentState, 'binding' | 'metadata'>,
+): string | undefined => {
+ const devicePolicy = state.metadata?.deviceAccessPolicy as
{ canUseDevice: boolean; reason: DeviceAccessReason } | undefined;
- const executionPlan = metadata?.executionPlan as ExecutionPlan | undefined;
+ const executionPlan = state.metadata?.executionPlan as ExecutionPlan | undefined;
const planAllowsDevice = !executionPlan || isDeviceCapablePlan(executionPlan);
if (devicePolicy?.canUseDevice === false || !planAllowsDevice) return undefined;
- return metadata?.activeDeviceId;
+ return state.binding?.device?.id;
};
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 38e67ceecde..92b8fa134b6 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -451,11 +451,11 @@ describe('AgentRuntimeService', () => {
stepCount: 0,
messages: [],
metadata: {
- agentConfig: mockParams.agentConfig,
modelRuntimeConfig: mockParams.modelRuntimeConfig,
userId: mockParams.userId,
},
toolManifestMap: {},
+ world: expect.objectContaining({ agent: mockParams.agentConfig }),
}),
);
@@ -509,7 +509,7 @@ describe('AgentRuntimeService', () => {
);
});
- it('should pass evalContext to metadata when provided', async () => {
+ it('should place evalContext on the world snapshot when provided', async () => {
mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');
const evalContext = { envPrompt: 'You are in a test environment' };
@@ -518,14 +518,12 @@ describe('AgentRuntimeService', () => {
expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(
'test-operation-1',
expect.objectContaining({
- metadata: expect.objectContaining({
- evalContext,
- }),
+ world: expect.objectContaining({ eval: evalContext }),
}),
);
});
- it('should persist the system-message context in metadata', async () => {
+ it('should persist the system-message context on the world snapshot', async () => {
mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');
const projectInstructions = [{ content: 'Use bun.', source: 'AGENTS.md' }];
@@ -536,14 +534,13 @@ describe('AgentRuntimeService', () => {
projectInstructions,
});
- // `metadata` is assembled from an explicit field list, so a value not
- // named there is dropped without a word β€” and steps can be claimed by
- // another worker, so anything the context engine needs has to survive on
- // the operation rather than in memory.
+ // Steps can be claimed by another worker, so anything the context engine
+ // needs has to survive on the persisted operation state β€” in the typed
+ // `world` slot, which is the only place the engine reads it from.
expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(
'test-operation-1',
expect.objectContaining({
- metadata: expect.objectContaining({ connectorOwnershipNote, projectInstructions }),
+ world: expect.objectContaining({ connectorOwnershipNote, projectInstructions }),
}),
);
});
@@ -758,8 +755,8 @@ describe('AgentRuntimeService', () => {
});
await (serviceWithFactory as any).createAgentRuntime({
+ world: { agent: { chatConfig: { enableContextCompression: true } } as any },
metadata: {
- agentConfig: { chatConfig: { enableContextCompression: true } },
modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },
},
operationId: 'test-operation-1',
@@ -793,8 +790,8 @@ describe('AgentRuntimeService', () => {
});
await (serviceWithFactory as any).createAgentRuntime({
+ world: { agent: { chatConfig: { enableContextCompression: true } } as any },
metadata: {
- agentConfig: { chatConfig: { enableContextCompression: true } },
modelRuntimeConfig: { model: 'unknown-model', provider: 'openai' },
},
operationId: 'test-operation-1',
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index a14827c705c..ee24245347f 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -995,22 +995,23 @@ export class AgentRuntimeService {
lastModified: new Date().toISOString(),
// Use the passed initial messages
messages: initialMessages,
+ // Late-bound execution facts. The device may be unrouted here and get
+ // bound at a later step boundary (`computeDeviceContext`).
+ ...((activeDeviceId || deviceSystemInfo) && {
+ binding: {
+ device: {
+ ...(activeDeviceId && { id: activeDeviceId }),
+ ...(deviceSystemInfo && { systemInfo: deviceSystemInfo }),
+ },
+ },
+ }),
metadata: {
- activeDeviceId,
activeDeviceScope,
- agentConfig,
- agentGroup,
agentShareVisitor,
botContext,
- botPlatformContext,
- connectorOwnershipNote,
deviceAccessPolicy,
- deviceSystemInfo,
- discordContext,
- evalContext,
evalRuntime,
executionPlan,
- projectInstructions,
...(interventionResolution
? { agentInterventionContinuation: interventionResolution }
: {}),
@@ -1018,12 +1019,9 @@ export class AgentRuntimeService {
modelRuntimeConfig,
queueRetries,
queueRetryDelay,
- ...(searchDecision && { searchDecision }),
stream,
operationSkillSet,
userId,
- userMemory,
- userTimezone,
workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,
workspaceId,
...appContext,
@@ -1039,6 +1037,21 @@ export class AgentRuntimeService {
toolExecutorMap: operationToolSet.executorMap,
toolManifestMap: operationToolSet.manifestMap,
toolSourceMap: operationToolSet.sourceMap,
+ // What the model is told about the run's world β€” frozen from here on;
+ // the context engine reads it on every step.
+ world: {
+ agent: agentConfig,
+ ...((botPlatformContext || discordContext) && {
+ channel: { botPlatform: botPlatformContext, discord: discordContext },
+ }),
+ connectorOwnershipNote,
+ eval: evalContext,
+ group: agentGroup,
+ projectInstructions,
+ searchDecision,
+ userMemory,
+ userTimezone,
+ },
tools: operationToolSet.tools,
// User intervention config for headless mode in async tasks
userInterventionConfig,
@@ -1603,7 +1616,7 @@ export class AgentRuntimeService {
await this.rehydrateStateMessagesFromDB(agentState);
// Enrich invoke_agent span with agent identity now that state is loaded.
- const stateAgentConfig = agentState.metadata?.agentConfig as
+ const stateAgentConfig = agentState.world?.agent as
{ description?: string | null; title?: string | null } | undefined;
const stateModel =
agentState.modelRuntimeConfig?.model ?? agentState.metadata?.modelRuntimeConfig?.model;
@@ -1902,12 +1915,17 @@ export class AgentRuntimeService {
// Pre-step computation: extract device context from DB messages
// Follows front-end computeStepContext pattern β€” computed at step boundary, not inside executors
- if (!currentState.metadata?.activeDeviceId) {
+ if (!currentState.binding?.device?.id) {
const deviceContext = await this.computeDeviceContext(currentState);
- if (deviceContext && currentState.metadata) {
- currentState.metadata.activeDeviceId = deviceContext.activeDeviceId;
- currentState.metadata.devicePlatform = deviceContext.devicePlatform;
- currentState.metadata.deviceSystemInfo = deviceContext.deviceSystemInfo;
+ if (deviceContext) {
+ currentState.binding = {
+ ...currentState.binding,
+ device: {
+ id: deviceContext.activeDeviceId,
+ platform: deviceContext.devicePlatform,
+ systemInfo: deviceContext.deviceSystemInfo,
+ },
+ };
log(
'[%s][%d] Pre-step: device context computed from messages (deviceId: %s)',
operationId,
@@ -3795,11 +3813,13 @@ export class AgentRuntimeService {
)
: undefined;
+ const world = (agentState as AgentState | undefined)?.world;
+
// Create Agent instance β€” use custom factory if provided, otherwise default to GeneralChatAgent
const generalConfig = {
- agentConfig: metadata?.agentConfig,
+ agentConfig: world?.agent,
compressionConfig: {
- enabled: metadata?.agentConfig?.chatConfig?.enableContextCompression ?? true,
+ enabled: world?.agent?.chatConfig?.enableContextCompression ?? true,
maxWindowToken: contextWindowTokens ?? undefined,
},
dynamicInterventionAudits,
@@ -3828,7 +3848,6 @@ export class AgentRuntimeService {
// Create streaming executor context
const executorContext: RuntimeExecutorContext = {
abortSignal,
- agentConfig: metadata?.agentConfig,
// The factory may be a Graph-aware dispatcher that still returns the
// default agent for ordinary conversations. Keep the early visible
// output end behavior tied to the actual agent, not factory presence.
@@ -3843,12 +3862,6 @@ export class AgentRuntimeService {
allowEarlyFinalAnswerVisibleOutputEnd:
agent instanceof GeneralChatAgent && !stateHasEntityFileEdits(agentState),
botContext: metadata?.botContext,
- botPlatformContext: metadata?.botPlatformContext,
- connectorOwnershipNote: metadata?.connectorOwnershipNote,
- discordContext: metadata?.discordContext,
- userTimezone: metadata?.userTimezone,
- evalContext: metadata?.evalContext,
- projectInstructions: metadata?.projectInstructions,
execSubAgent: this.delegate.execSubAgent,
execVirtualSubAgent: this.delegate.execVirtualSubAgent,
execGroupMember: this.delegate.execGroupMember,
@@ -3857,7 +3870,6 @@ export class AgentRuntimeService {
messageModel: this.messageModel,
modelRuntimeConfig: metadata?.modelRuntimeConfig,
operationId,
- searchDecision: metadata?.searchDecision,
serverDB: this.serverDB,
stepIndex,
stream: metadata?.stream,
diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
index 934e8d3e0b7..fd73364022b 100644
--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
@@ -232,11 +232,9 @@ export class OperationTraceRecorder {
private initPartialHeader(partial: any, agentState: any): void {
if (partial.startedAt) return;
partial.startedAt = Date.now();
- partial.model =
- (agentState?.metadata as any)?.agentConfig?.model ?? agentState?.modelRuntimeConfig?.model;
+ partial.model = agentState?.world?.agent?.model ?? agentState?.modelRuntimeConfig?.model;
partial.provider =
- (agentState?.metadata as any)?.agentConfig?.provider ??
- agentState?.modelRuntimeConfig?.provider;
+ agentState?.world?.agent?.provider ?? agentState?.modelRuntimeConfig?.provider;
}
private buildStepSnapshot(params: AppendStepParams): StepSnapshot {
diff --git a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
index ed01dd8acf6..da573eda389 100644
--- a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts
@@ -49,7 +49,7 @@ describe('OperationTraceRecorder', () => {
afterStepSignalEvents: [],
agentState: {
messages: [],
- metadata: { agentConfig: { model: 'claude-sonnet-4-6', provider: 'lobehub' } },
+ world: { agent: { model: 'claude-sonnet-4-6', provider: 'lobehub' } },
},
beforeStepSignalEvents: [],
currentContext: { phase: 'user_input' },
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index ad250ff3007..2eb168786e9 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -397,7 +397,7 @@ export interface OperationCreationParams {
agentConfig?: any;
/**
* Multi-agent group (or bot-conversation fallback) context, resolved once at
- * op creation and forwarded into `state.metadata.agentGroup`. The per-step
+ * op creation and forwarded into `state.world.group`. The per-step
* context engine reads it back to inject the participant roster (with real
* `agt_*` IDs) β€” no per-step DB lookup, mirroring `botContext`.
*/
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index d4b7fbbbd4f..9515a5f2edc 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -830,7 +830,7 @@ export const prepareOperation = async (
// the local-system tool's {{workingDirectory}} placeholder β€” the channel
// the model uses to know where it is and reach for absolute paths β€” and,
// downstream, the runCommand cwd / search scope (RuntimeExecutors reads
- // state.metadata.deviceSystemInfo.workingDirectory). Resume-safe via the
+ // state.binding.device.systemInfo.workingDirectory). Resume-safe via the
// existing deviceSystemInfo plumbing (computeDeviceContext).
if (workspaceInit.boundCwd) {
deviceSystemInfo.workingDirectory = workspaceInit.boundCwd;
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index c667bdf9785..5d216519592 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -662,7 +662,7 @@ export const discoverTools = async (
// never route to a device, offline bindings stay unrouted, unbound runs
// auto-activate only with exactly one device online). Without the
// `canUseDevice` gate an external bot sender's turn would still populate
- // `state.metadata.activeDeviceId`, and `buildStepToolDelta` re-injects
+ // `state.binding.device.id`, and `buildStepToolDelta` re-injects
// `LocalSystemManifest` whenever activeDeviceId is set, bypassing the
// engine's enabledToolIds exclusion β€” resolving the plan here closes
// that bypass at the source.
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/noActiveDevice.ts b/apps/server/src/services/toolExecution/serverRuntimes/noActiveDevice.ts
index 2975102a8c1..3e95175a61c 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/noActiveDevice.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/noActiveDevice.ts
@@ -12,7 +12,7 @@ import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
* flow), so a call can arrive before any device was activated.
* - Type 2 β€” lost mid-run: the device dropped offline between steps, the next
* operation re-resolves its plan to `device-unrouted`
- * (`bound-device-offline`), and `metadata.activeDeviceId` is cleared.
+ * (`bound-device-offline`), and `binding.device.id` is left unset.
*
* Historically the runtime factory guards threw a bare
* `activeDeviceId is required for ...` error string. The model received no
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index 93c23d71ef8..be79853df3c 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -178,7 +178,7 @@ const createRunContext = ({
}): ToolRunContext => {
const toolName = toolNameOf(tool);
const toolSource = resolveToolSource(state, tool);
- const agentConfig = state.metadata?.agentConfig as
+ const agentConfig = state.world?.agent as
{ chatConfig?: { toolResultMaxLength?: number } } | undefined;
return {
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index caeba490422..3d0dc1512ab 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -1,19 +1,115 @@
import type {
ActivatedStepSkill,
ActivatedStepTool,
+ AgentGroupConfig,
+ BotPlatformContext,
+ DiscordContext,
+ EvalContext,
OperationToolSet,
+ ProjectInstructionFile,
ToolExecutor,
ToolSource,
+ UserMemoryConfig,
} from '@lobechat/context-engine';
import type {
ChatToolPayload,
ExpertiseContextSnapshot,
+ LobeAgentChatConfig,
+ LobeAgentConfig,
SecurityBlacklistConfig,
UserInterventionConfig,
} from '@lobechat/types';
import type { Cost, CostLimit, Usage } from './usage';
+/**
+ * Search route resolved once before the run starts. Declared here rather than
+ * imported so the runtime package does not depend on the model catalog;
+ * structurally identical to the resolver output in `model-bank`.
+ */
+export interface SearchDecisionSnapshot {
+ enabledSearch: boolean;
+ isModelHasBuiltinSearch: boolean;
+ isProviderHasBuiltinSearch: boolean;
+ useApplicationBuiltinSearchTool: boolean;
+ useModelSearch: boolean;
+}
+
+/**
+ * The agent definition as the host resolved it for this run.
+ *
+ * `Partial` because hosts snapshot only what the run needs; the identity
+ * fields and the sub-agent override are run-level facts the host stamps on
+ * top of the stored agent config.
+ */
+export interface RunAgentSnapshot extends Partial<LobeAgentConfig> {
+ /** Agent-row description; surfaces in tracing spans and skill placeholders. */
+ description?: string | null;
+ id?: string;
+ slug?: string | null;
+ /**
+ * Raw callSubAgent chatConfig override, stamped alongside the merged
+ * chatConfig so explicit sub-agent reasoning choices can be re-applied over
+ * the user's model-instance defaults.
+ */
+ subAgentChatConfigOverride?: Partial<LobeAgentChatConfig>;
+}
+
+/**
+ * What the model is told about the run's world.
+ *
+ * Frozen when the operation is created: every field is a fact the host
+ * resolved once (agent definition, group roster, project instructions, user
+ * memory, channel facts) and the context engine only reads it back on each
+ * step to assemble the system message. Nothing in here changes while the run
+ * executes β€” a run that needs a different world is a different operation.
+ */
+export interface AgentWorldSnapshot {
+ /** Agent definition snapshot: systemRole, chatConfig, agencyConfig … */
+ agent?: RunAgentSnapshot;
+ /** Channel-specific facts the model should know (bot platform, Discord …). */
+ channel?: {
+ botPlatform?: BotPlatformContext;
+ discord?: DiscordContext;
+ };
+ /** Borrowed-connector attribution rendered into the system message. */
+ connectorOwnershipNote?: string;
+ /** Evaluation prompt data for eval runs. */
+ eval?: EvalContext;
+ /** Multi-agent group roster (or bot-conversation fallback). */
+ group?: AgentGroupConfig;
+ /** Root instruction files of the bound project. */
+ projectInstructions?: ProjectInstructionFile[];
+ /** Search route resolved before the run started. */
+ searchDecision?: SearchDecisionSnapshot;
+ /** User memory the model may recall from. */
+ userMemory?: UserMemoryConfig;
+ /** IANA timezone used to render "now" for the model. */
+ userTimezone?: string;
+}
+
+/**
+ * Execution facts that are bound late.
+ *
+ * Unlike {@link AgentWorldSnapshot} and the execution plan, this is the one
+ * business slot the runtime host may rewrite at a step boundary: a device
+ * that was unrouted at creation can be bound once a tool result names it
+ * (`computeDeviceContext`), and the bound device's system info feeds both
+ * prompt placeholders and tool cwd resolution.
+ */
+export interface AgentRunBinding {
+ /**
+ * Device routed for this run. `id` stays absent until a device is bound;
+ * `systemInfo` may already carry a working directory for runs whose cwd was
+ * resolved from a persisted device row.
+ */
+ device?: {
+ id?: string;
+ platform?: string;
+ systemInfo?: Record<string, string>;
+ };
+}
+
/**
* Agent's serializable state.
* This is the "passport" that can be persisted and transferred.
@@ -23,12 +119,18 @@ export interface AgentState {
activatedStepSkills?: ActivatedStepSkill[];
/** Cumulative record of tools activated at step level */
activatedStepTools?: ActivatedStepTool[];
+ // --- Late-bound execution facts ---
+ /**
+ * Execution facts bound at a step boundary (device routing). The only
+ * business slot the host may write after creation.
+ */
+ binding?: AgentRunBinding;
+
/**
* Current calculated cost for this session.
* Updated after each billable operation.
*/
cost: Cost;
-
/**
* Optional cost limits configuration.
* If set, execution will stop when limits are exceeded.
@@ -73,7 +175,12 @@ export interface AgentState {
// --- Core Context ---
messages: any[];
- // --- Extensible metadata ---
+ /**
+ * Un-converged run context. Keys that have a business home live in the
+ * typed slots (`world`, `binding`, …); anything left here is either host
+ * plumbing the runtime does not interpret or context that has not been
+ * placed yet. `normalizeAgentState` lifts legacy keys out on load.
+ */
metadata?: Record<string, any>;
/**
@@ -210,6 +317,13 @@ export interface AgentState {
* Controls how tools requiring approval are handled
*/
userInterventionConfig?: UserInterventionConfig;
+
+ // --- World snapshot ---
+ /**
+ * What the model is told about the run's world. Frozen at creation and
+ * read by the context engine on every step.
+ */
+ world?: AgentWorldSnapshot;
}
/**
diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.ts
index 559cfd01b4b..6998b900fcb 100644
--- a/packages/agent-runtime/src/utils/index.ts
+++ b/packages/agent-runtime/src/utils/index.ts
@@ -1,5 +1,6 @@
export * from './llmErrorClassifier';
export * from './messageSelectors';
+export * from './normalizeAgentState';
export * from './replay';
export * from './runtimeRetry';
export * from './status';
diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts b/packages/agent-runtime/src/utils/normalizeAgentState.test.ts
new file mode 100644
index 00000000000..c7f30d50fd6
--- /dev/null
+++ b/packages/agent-runtime/src/utils/normalizeAgentState.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+
+import type { AgentState } from '../types';
+import { normalizeAgentState } from './normalizeAgentState';
+
+const baseState = (): AgentState =>
+ ({
+ cost: { total: 0 },
+ createdAt: '2026-01-01T00:00:00.000Z',
+ lastModified: '2026-01-01T00:00:00.000Z',
+ messages: [],
+ operationId: 'op_1',
+ status: 'idle',
+ stepCount: 0,
+ toolManifestMap: {},
+ usage: {},
+ }) as unknown as AgentState;
+
+describe('normalizeAgentState', () => {
+ it('returns the same object when metadata carries no legacy keys', () => {
+ const state = { ...baseState(), metadata: { userId: 'u1', _hooks: [] } };
+ expect(normalizeAgentState(state)).toBe(state);
+ });
+
+ it('lifts legacy metadata keys into world and binding and strips them from metadata', () => {
+ const state = {
+ ...baseState(),
+ metadata: {
+ activeDeviceId: 'dev_1',
+ agentConfig: { systemRole: 'hi' },
+ agentGroup: { agentMap: {} },
+ botPlatformContext: { platformName: 'slack', supportsMarkdown: true },
+ connectorOwnershipNote: 'note',
+ devicePlatform: 'darwin',
+ deviceSystemInfo: { workingDirectory: '/tmp' },
+ discordContext: { guildId: 'g' },
+ evalContext: { caseId: 'c' },
+ projectInstructions: [{ content: 'x', source: 'AGENTS.md' }],
+ searchDecision: { enabledSearch: true },
+ userId: 'u1',
+ userMemory: { enabled: true },
+ userTimezone: 'Asia/Shanghai',
+ },
+ };
+
+ const normalized = normalizeAgentState(state);
+
+ expect(normalized.world).toEqual({
+ agent: { systemRole: 'hi' },
+ channel: {
+ botPlatform: { platformName: 'slack', supportsMarkdown: true },
+ discord: { guildId: 'g' },
+ },
+ connectorOwnershipNote: 'note',
+ eval: { caseId: 'c' },
+ group: { agentMap: {} },
+ projectInstructions: [{ content: 'x', source: 'AGENTS.md' }],
+ searchDecision: { enabledSearch: true },
+ userMemory: { enabled: true },
+ userTimezone: 'Asia/Shanghai',
+ });
+ expect(normalized.binding).toEqual({
+ device: { id: 'dev_1', platform: 'darwin', systemInfo: { workingDirectory: '/tmp' } },
+ });
+ expect(normalized.metadata).toEqual({ userId: 'u1' });
+ // Input is not mutated.
+ expect(state.metadata.agentConfig).toEqual({ systemRole: 'hi' });
+ });
+
+ it('keeps slot values over legacy keys when both are present', () => {
+ const state = {
+ ...baseState(),
+ binding: { device: { id: 'dev_new' } },
+ metadata: { activeDeviceId: 'dev_old', agentConfig: { systemRole: 'old' } },
+ world: { agent: { systemRole: 'new' } as any },
+ };
+
+ const normalized = normalizeAgentState(state);
+
+ expect(normalized.world?.agent).toEqual({ systemRole: 'new' });
+ expect(normalized.binding?.device?.id).toBe('dev_new');
+ expect(normalized.metadata).toEqual({});
+ });
+
+ it('lifts a partial device binding without inventing an id', () => {
+ const state = {
+ ...baseState(),
+ metadata: { deviceSystemInfo: { workingDirectory: '/w' } },
+ };
+
+ const normalized = normalizeAgentState(state);
+
+ expect(normalized.binding).toEqual({ device: { systemInfo: { workingDirectory: '/w' } } });
+ expect(normalized.world).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.ts b/packages/agent-runtime/src/utils/normalizeAgentState.ts
new file mode 100644
index 00000000000..50f405fbcfb
--- /dev/null
+++ b/packages/agent-runtime/src/utils/normalizeAgentState.ts
@@ -0,0 +1,88 @@
+import type { AgentRunBinding, AgentState, AgentWorldSnapshot } from '../types';
+
+/**
+ * Legacy `state.metadata` keys that now have a typed home on the state, and
+ * where each one goes. Kept as data so the lift and the key strip stay in
+ * sync and the mapping is greppable from either side.
+ */
+const WORLD_KEYS = {
+ agentConfig: 'agent',
+ agentGroup: 'group',
+ connectorOwnershipNote: 'connectorOwnershipNote',
+ evalContext: 'eval',
+ projectInstructions: 'projectInstructions',
+ searchDecision: 'searchDecision',
+ userMemory: 'userMemory',
+ userTimezone: 'userTimezone',
+} as const satisfies Record<string, keyof AgentWorldSnapshot>;
+
+const CHANNEL_KEYS = {
+ botPlatformContext: 'botPlatform',
+ discordContext: 'discord',
+} as const satisfies Record<string, keyof NonNullable<AgentWorldSnapshot['channel']>>;
+
+const DEVICE_KEYS = {
+ activeDeviceId: 'id',
+ devicePlatform: 'platform',
+ deviceSystemInfo: 'systemInfo',
+} as const satisfies Record<string, keyof NonNullable<AgentRunBinding['device']>>;
+
+const LEGACY_KEYS = [
+ ...Object.keys(WORLD_KEYS),
+ ...Object.keys(CHANNEL_KEYS),
+ ...Object.keys(DEVICE_KEYS),
+];
+
+const hasOwn = (record: Record<string, unknown>, key: string) =>
+ Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined;
+
+/**
+ * Lift legacy `metadata.*` run context into the typed `world` / `binding`
+ * slots so every reader can rely on the slots alone.
+ *
+ * Runs at the persistence boundary (state load) for blobs written before the
+ * slots existed. Slot values already present win over legacy keys, and the
+ * legacy keys are removed from `metadata` so the blob is not carried twice
+ * (the in-flight state blob has a hard 10MB ceiling). Returns the same object
+ * when nothing needed lifting.
+ */
+export const normalizeAgentState = <T extends AgentState>(state: T): T => {
+ const metadata = state.metadata;
+ if (!metadata || !LEGACY_KEYS.some((key) => hasOwn(metadata, key))) return state;
+
+ const world: AgentWorldSnapshot = { ...state.world };
+ for (const [legacyKey, slotKey] of Object.entries(WORLD_KEYS)) {
+ if (hasOwn(metadata, legacyKey) && world[slotKey] === undefined) {
+ (world as Record<string, unknown>)[slotKey] = metadata[legacyKey];
+ }
+ }
+
+ const channel = { ...world.channel };
+ for (const [legacyKey, slotKey] of Object.entries(CHANNEL_KEYS)) {
+ if (hasOwn(metadata, legacyKey) && channel[slotKey] === undefined) {
+ (channel as Record<string, unknown>)[slotKey] = metadata[legacyKey];
+ }
+ }
+ if (Object.keys(channel).length > 0) world.channel = channel;
+
+ const device = { ...state.binding?.device };
+ for (const [legacyKey, slotKey] of Object.entries(DEVICE_KEYS)) {
+ if (hasOwn(metadata, legacyKey) && device[slotKey] === undefined) {
+ (device as Record<string, unknown>)[slotKey] = metadata[legacyKey];
+ }
+ }
+ const binding: AgentRunBinding | undefined =
+ Object.keys(device).length > 0 ? { ...state.binding, device } : state.binding;
+
+ const strippedMetadata: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(metadata)) {
+ if (!LEGACY_KEYS.includes(key)) strippedMetadata[key] = value;
+ }
+
+ return {
+ ...state,
+ ...(binding && { binding }),
+ metadata: strippedMetadata,
+ ...(Object.keys(world).length > 0 && { world }),
+ };
+};