π€― 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-runtime): carve the typed origin slot out of state.metadata (#19505)
Arvin Xu518059aed113
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex f9612289baf..83807656758 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -335,7 +335,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -1288,7 +1288,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {},{ content: 'created', id: 'tool-msg-1', role: 'tool', tool_call_id: 'call_1' },] as any,- metadata: {+ origin: {agentId: 'agent-123',sourceMessageId: 'user-msg-1',threadId: 'thread-123',@@ -1333,7 +1333,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {{ content: 'old result', id: 'old-tool-msg', role: 'tool', tool_call_id: 'old_call' },{ content: 'What model are you?', id: 'user-msg-2', role: 'user' },] as any,- metadata: {+ origin: {agentId: 'agent-123',sourceMessageId: 'user-msg-2',threadId: 'thread-123',@@ -1621,7 +1621,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {});const state = createMockState({messages: [{ content: 'history', role: 'user' }],- metadata: {+ origin: {agentId: 'agent-123',},});@@ -2340,7 +2340,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {const content = await callWithMessages([{ content: 'Continue', role: 'user' }],- stateWithLobeAgent({ metadata: { agentId: 'agent-123' } }),+ stateWithLobeAgent({ origin: { agentId: 'agent-123' } }),{ topicId: 'context-topic' },);@@ -2884,8 +2884,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {group: agentGroup,},metadata: {- agentId: 'agent-support',botContext: ctxWithConfig.botContext,+ },+ origin: {+ agentId: 'agent-support',topicId: 'topic-123',},});@@ -3233,7 +3235,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -3760,7 +3762,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {role: 'assistant',} as any,],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -3970,7 +3972,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -4570,7 +4572,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should query messages with correct metadata fields when state.metadata is defined', async () => {const executors = createRuntimeExecutors(ctx);const state = createMockState({- metadata: {+ origin: {agentId: 'agent-abc',threadId: 'thread-xyz',topicId: 'topic-abc-123',@@ -4711,9 +4713,12 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {{ content: 'Response', role: 'assistant', tool_calls: [] },],metadata: {+ // topicId is undefined+ },+ origin: {agentId: 'agent-123',threadId: 'thread-123',- topicId: undefined, // topicId is undefined+ topicId: undefined,},});@@ -4889,7 +4894,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {},},},- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -4926,7 +4931,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should pass agentId from runtime metadata to executeTool', async () => {const executors = createRuntimeExecutors(ctx);const state = createMockState({- metadata: {+ origin: {agentId: 'agent-docs-123',threadId: 'thread-123',topicId: 'topic-123',@@ -4963,8 +4968,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {const executors = createRuntimeExecutors(ctx);const state = createMockState({metadata: {- agentId: 'agent-123',clientIp: '203.0.113.7',+ },+ origin: {+ agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',},@@ -4999,7 +5006,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should pass Agent Signal procedure identity fields to executeTool', async () => {const executors = createRuntimeExecutors(ctx);const state = createMockState({- metadata: {+ origin: {agentId: 'agent-docs-123',sourceMessageId: 'user-msg-123',threadId: 'thread-123',@@ -5043,7 +5050,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -5111,7 +5118,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -5381,7 +5388,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -5917,7 +5924,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: { agentId: 'agent-123', topicId: 'topic-123' },+ origin: { agentId: 'agent-123', topicId: 'topic-123' },operationId: 'op-123',status: 'running',stepCount: 0,@@ -6186,7 +6193,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {};const executors = createRuntimeExecutors(ctxWithHooks);- const state = createToolState({ metadata: { agentId: 'agent-123', topicId: 'topic-123' } });+ const state = createToolState({ origin: { agentId: 'agent-123', topicId: 'topic-123' } });const instruction = {payload: {@@ -6260,7 +6267,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'parent-agent-id',topicId: 'topic-123',},@@ -6470,10 +6477,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {const executors = createRuntimeExecutors(ctxWithCallback);const state = createMockState({- metadata: {+ origin: {agentId: 'parent-agent-id',- isSubAgent: true,topicId: 'topic-123',+ lineage: { isSubAgent: true },},});diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.tsindex 8a423a1526a..bccc879ae34 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts@@ -25,7 +25,7 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {const runner = buildServerVirtualSubAgentRunner(ctx,{- metadata: { agentId: 'agent-1', topicId: 'topic-1' },+ origin: { agentId: 'agent-1', topicId: 'topic-1' },operationId: 'parent-op',...state,} as AgentState,@@ -38,7 +38,7 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {it('follows the topic-pinned runtime model over the world agent default', async () => {const { execVirtualSubAgent, runner } = buildRunner({- metadata: { agentId: 'agent-1', topicId: 'topic-1' },+ origin: { agentId: 'agent-1', topicId: 'topic-1' },world: {agent: { model: 'agent-default-model', provider: 'agent-default-provider' } as any,},@@ -54,7 +54,7 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {it('falls back to the world agent config when no runtime model exists', async () => {const { execVirtualSubAgent, runner } = buildRunner({- metadata: { agentId: 'agent-1', topicId: 'topic-1' },+ origin: { agentId: 'agent-1', topicId: 'topic-1' },world: {agent: { model: 'agent-default-model', provider: 'agent-default-provider' } as any,},@@ -98,7 +98,7 @@ describe('runner builders fail closed for share-visitor runs', () => {} as unknown as RuntimeExecutorContext;const state = {- metadata: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },+ origin: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },operationId: 'parent-op',} as unknown as AgentState;diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex 395bcafdf32..bac4aeba73e 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -339,8 +339,8 @@ export class ServerLLMTransport implements LLMTransport {agentShareVisitorIds: input.state.metadata?.agentShareVisitor? toAgentShareVisitorIds(input.state.metadata.agentShareVisitor): undefined,- topicId: input.state.metadata?.topicId,- trigger: input.state.metadata?.trigger,+ topicId: input.state.origin?.topicId,+ trigger: input.state.origin?.trigger,userAgent: input.state.metadata?.userAgent,});diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex db61504c29a..f6b1419c4fb 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -51,7 +51,7 @@ export class ServerToolTransport implements ToolTransport {async registerWork(registration: ToolWorkRegistration, state: AgentState): Promise<void> {await registerWorkFromIntent({- agentId: state.metadata?.agentId ?? null,+ agentId: state.origin?.agentId ?? null,intent: registration.intent,rootOperationId: this.ctx.operationId,serverDB: this.ctx.serverDB,@@ -60,10 +60,10 @@ export class ServerToolTransport implements ToolTransport {sourceToolIdentifier: registration.sourceToolIdentifier,sourceToolName: registration.sourceToolName,state: registration.state,- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,+ threadId: state.origin?.threadId,+ topicId: state.origin?.topicId,userId: this.ctx.userId,- workspaceId: state.metadata?.workspaceId ?? this.ctx.workspaceId,+ workspaceId: state.origin?.workspaceId ?? this.ctx.workspaceId,});}@@ -126,7 +126,7 @@ export class ServerToolTransport implements ToolTransport {apiName: chatToolPayload.apiName,botContext: context.state.metadata?.botContext,canUseDevice: policy?.canUseDevice ?? true,- messageId: context.state.metadata?.sourceMessageId,+ messageId: context.state.origin?.sourceMessageId,operationId,reason: policy?.reason ?? 'first-party',toolIdentifier: chatToolPayload.identifier,@@ -161,19 +161,19 @@ export class ServerToolTransport implements ToolTransport {if (context.abortSignal?.aborted) return this.abortedBeforeLaunch();const dispatchResult = await dispatchClientTool(chatToolPayload, {- agentId: context.state.metadata?.agentId,+ agentId: context.state.origin?.agentId,assistantMessageId: context.parentMessageId,- documentId: context.state.metadata?.documentId,- groupId: context.state.metadata?.groupId,+ documentId: context.state.origin?.documentId,+ groupId: context.state.origin?.groupId,operationId,rootOperationId: operationId,- scope: context.state.metadata?.scope,- sourceMessageId: context.state.metadata?.sourceMessageId,+ scope: context.state.origin?.scope,+ sourceMessageId: context.state.origin?.sourceMessageId,streamManager,- taskId: context.state.metadata?.taskId,- threadId: context.state.metadata?.threadId,+ taskId: context.state.origin?.taskId,+ threadId: context.state.origin?.threadId,timeoutMs,- topicId: context.state.metadata?.topicId ?? this.ctx.topicId,+ topicId: context.state.origin?.topicId ?? this.ctx.topicId,});execution = { attempts: 1, result: dispatchResult };} else {@@ -199,7 +199,7 @@ export class ServerToolTransport implements ToolTransport {activatedSkills: context.activatedSkills as any,activeDeviceId: resolveRunActiveDeviceId(context.state),activeDeviceScope: context.state.metadata?.activeDeviceScope,- agentId: context.state.metadata?.agentId,+ agentId: context.state.origin?.agentId,agentMember: buildServerAgentMemberRunner(this.ctx,context.state,@@ -217,13 +217,13 @@ export class ServerToolTransport implements ToolTransport {deviceCapable: context.state.metadata?.executionPlan? isDeviceCapablePlan(context.state.metadata.executionPlan): undefined,- documentId: context.state.metadata?.documentId,+ documentId: context.state.origin?.documentId,editingAgentId: context.state.metadata?.editingAgentId,editingGroupId: context.state.metadata?.editingGroupId,execSubAgent: this.ctx.execSubAgent,executionTimeoutMs: timeoutMs,- groupId: context.state.metadata?.groupId,- isSubAgent: context.state.metadata?.isSubAgent === true,+ groupId: context.state.origin?.groupId,+ isSubAgent: context.state.origin?.lineage?.isSubAgent === true,// Sandboxing qualifies a `local` run, so it is gated on the plan's// resolved target rather than the stored flag: a config that says// `localSandbox` but landed on `sandbox`/`device` was never fenced,@@ -237,11 +237,11 @@ export class ServerToolTransport implements ToolTransport {localSandboxNetwork:context.state.world?.agent?.agencyConfig?.localSandboxNetwork === true,memoryToolPermission: context.state.world?.agent?.chatConfig?.memory?.toolPermission,- messageId: context.state.metadata?.sourceMessageId,+ messageId: context.state.origin?.sourceMessageId,operationId,projectSkills: resolveRunProjectSkills(context.state.metadata),rootOperationId: operationId,- scope: context.state.metadata?.scope,+ scope: context.state.origin?.scope,serverDB,skipResultTruncation: true,subAgent: buildServerVirtualSubAgentRunner(@@ -250,8 +250,8 @@ export class ServerToolTransport implements ToolTransport {chatToolPayload,context.parentMessageId,),- taskId: context.state.metadata?.taskId,- threadId: context.state.metadata?.threadId,+ taskId: context.state.origin?.taskId,+ threadId: context.state.origin?.threadId,toolCallId: chatToolPayload.id,toolManifestMap: context.effectiveManifestMap,toolMessageId: context.toolMessageId,@@ -259,7 +259,7 @@ export class ServerToolTransport implements ToolTransport {topicId: this.ctx.topicId,userId,workingDirectory: context.state.binding?.device?.systemInfo?.workingDirectory,- workspaceId: context.state.metadata?.workspaceId ?? this.ctx.workspaceId,+ workspaceId: context.state.origin?.workspaceId ?? this.ctx.workspaceId,}),{isInterrupted: () => isOperationInterrupted(this.ctx),@@ -289,14 +289,14 @@ export class ServerToolTransport implements ToolTransport {executionTime: execution.result.executionTime ?? 0,};const executionResult = await archiveRuntimeToolResult(resultWithExecutionTime, {- agentId: context.state.metadata?.agentId,+ agentId: context.state.origin?.agentId,identifier: chatToolPayload.identifier,limit: context.toolResultMaxLength,serverDB,toolCallId: chatToolPayload.id,- topicId: this.ctx.topicId ?? context.state.metadata?.topicId,+ topicId: this.ctx.topicId ?? context.state.origin?.topicId,userId,- workspaceId: context.state.metadata?.workspaceId ?? this.ctx.workspaceId,+ workspaceId: context.state.origin?.workspaceId ?? this.ctx.workspaceId,});await this.dispatchAfterToolCall(chatToolPayload, context, executionResult, toolCallMocked);@@ -413,8 +413,8 @@ export class ServerToolTransport implements ToolTransport {private async resolveAgentVisibility(context: ToolRunContext) {if (context.mode !== 'single') return undefined;- const agentId = context.state.metadata?.agentId;- const workspaceId = context.state.metadata?.workspaceId ?? this.ctx.workspaceId;+ const agentId = context.state.origin?.agentId;+ const workspaceId = context.state.origin?.workspaceId ?? this.ctx.workspaceId;if (!agentId || !this.ctx.serverDB || !this.ctx.userId) return null;try {diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.tsindex 270d3bd536a..c376d59ca51 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts@@ -218,7 +218,7 @@ describe('buildServerCallLlmContext - workspace context', () => {llmPayload,model: 'gpt-4',provider: 'openai',- state: createState({ metadata: { workspaceId: 'workspace-2' } }),+ state: createState({ origin: { workspaceId: 'workspace-2' } }),tooling,});diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex d8bd67a1328..ae933ccff62 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -177,13 +177,13 @@ export const buildServerCallLlmContext = async ({// no setting that could grant file access.const agentDocumentsAllowedForShare = !ctx.agentShareVisitor;let agentDocuments: AgentContextDocument[] | undefined;- const agentId = state.metadata?.agentId;+ const agentId = state.origin?.agentId;if (agentId && ctx.serverDB && ctx.userId && agentDocumentsAllowedForShare) {try {const agentDocService = new AgentDocumentsService(ctx.serverDB,ctx.userId,- state.metadata?.workspaceId ?? ctx.workspaceId,+ state.origin?.workspaceId ?? ctx.workspaceId,);const docs = await agentDocService.getAgentContextDocuments(agentId);if (docs.length > 0) {@@ -233,7 +233,7 @@ export const buildServerCallLlmContext = async ({const docService = new AgentDocumentsService(ctx.serverDB,ctx.userId,- state.metadata?.workspaceId ?? ctx.workspaceId,+ state.origin?.workspaceId ?? ctx.workspaceId,);const personaModel = new UserPersonaModel(ctx.serverDB, ctx.userId);@@ -276,8 +276,8 @@ export const buildServerCallLlmContext = async ({// (`packages/builtin-skills/src/lobehub/content.ts`) so it can render// `{{agent_id}}` / `{{agent_title}}` / `{{topic_id}}` etc. into the// model's prompt without needing a separate context injector.- const lobehubSkillAgentId = state.metadata?.agentId;- const lobehubSkillTopicId = ctx.topicId ?? state.metadata?.topicId;+ const lobehubSkillAgentId = state.origin?.agentId;+ const lobehubSkillTopicId = ctx.topicId ?? state.origin?.topicId;const lobehubSkillAgentMeta = state.world?.agent as{ description?: string | null; title?: string | null } | undefined;@@ -380,7 +380,7 @@ export const buildServerCallLlmContext = async ({const topicDocumentModel = new TopicDocumentModel(ctx.serverDB,ctx.userId,- state.metadata?.workspaceId ?? ctx.workspaceId,+ state.origin?.workspaceId ?? ctx.workspaceId,);const [planDocument] = await topicDocumentModel.findByTopicId(lobehubSkillTopicId, {type: AGENT_PLAN_FILE_TYPE,@@ -826,7 +826,7 @@ const resolveWorkspaceContext = async (if (ctx.agentShareVisitor) return undefined;const appUrl = getAppUrl();- const workspaceId = state.metadata?.workspaceId ?? ctx.workspaceId;+ const workspaceId = state.origin?.workspaceId ?? ctx.workspaceId;// Personal space: the origin alone is enough to anchor links.if (!workspaceId) return appUrl ? { appUrl } : undefined;diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 3aa121e031a..a1a88fe2f2b 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -220,8 +220,8 @@ export const buildServerVirtualSubAgentRunner = (const execVirtualSubAgent = ctx.execVirtualSubAgent;if (!execVirtualSubAgent) return undefined;- const agentId = state.metadata?.agentId;- const topicId = ctx.topicId ?? state.metadata?.topicId;+ const agentId = state.origin?.agentId;+ const topicId = ctx.topicId ?? state.origin?.topicId;if (!agentId || !topicId) return undefined;const parentAgentConfig = state.world?.agent as LobeAgentConfig | undefined;@@ -259,12 +259,12 @@ export const buildServerVirtualSubAgentRunner = (const placeholder = await ctx.messageModel.create({agentId,content: '',- groupId: state.metadata?.groupId ?? undefined,+ groupId: state.origin?.groupId ?? undefined,parentId: parentMessageId,plugin: chatToolPayload as any,pluginState: { status: 'pending' },role: 'tool',- threadId: state.metadata?.threadId,+ threadId: state.origin?.threadId,tool_call_id: chatToolPayload.id,topicId,});@@ -275,7 +275,7 @@ export const buildServerVirtualSubAgentRunner = (const result = (await execVirtualSubAgent({agentId: targetAgentId ?? agentId,chatConfig: subAgentChatConfig,- groupId: state.metadata?.groupId ?? undefined,+ groupId: state.origin?.groupId ?? undefined,instruction,model: subAgentModel?.model,parentMessageId: placeholder.id,@@ -351,9 +351,9 @@ export const buildServerAgentMemberRunner = (const execGroupMember = ctx.execGroupMember;if (!execGroupMember) return undefined;- const agentId = state.metadata?.agentId;- const topicId = ctx.topicId ?? state.metadata?.topicId;- const groupId = state.metadata?.groupId ?? undefined;+ const agentId = state.origin?.agentId;+ const topicId = ctx.topicId ?? state.origin?.topicId;+ const groupId = state.origin?.groupId ?? undefined;if (!agentId || !topicId || !groupId) return undefined;return {@@ -388,7 +388,7 @@ export const buildServerAgentMemberRunner = (plugin: chatToolPayload as any,pluginState: { expectedMembers, onComplete, status: 'pending' },role: 'tool',- threadId: state.metadata?.threadId,+ threadId: state.origin?.threadId,tool_call_id: chatToolPayload.id,topicId,});@@ -413,7 +413,7 @@ export const buildServerAgentMemberRunner = (plugin: { ...(chatToolPayload as any), id: memberToolCallId },pluginState: { status: 'pending' },role: 'tool',- threadId: state.metadata?.threadId,+ threadId: state.origin?.threadId,tool_call_id: memberToolCallId,topicId,});diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.tsindex d29627bfe28..91219c36902 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroIntervention.test.ts@@ -936,11 +936,6 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {appContext: { sourceMessageId: messageId },id: continuationOperationId,metadata: {- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: operationId,- sourceToolMessageIds: [messageId],- },agentInterventionDispatch: {deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),messageId: 'qstash-message-published-retry',@@ -948,6 +943,11 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {scheduledAt: new Date().toISOString(),state: 'scheduled',},+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },},status: 'running',topicId: 'topic-runtime',@@ -1040,17 +1040,17 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {appContext: { sourceMessageId: messageId },id: continuationOperationId,metadata: {- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: operationId,- sourceToolMessageIds: [messageId],- },agentInterventionPreparation: {deduplicationId,resolutionRequestId,state: 'ready',stepIndex: 0,},+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },},status: 'running',topicId: 'topic-ack-backfill',@@ -1058,18 +1058,20 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {});aiAgentService.loadInterventionContinuationState.mockResolvedValue({metadata: {- agentId: 'agent-ack-backfill',- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: operationId,- sourceToolMessageIds: [messageId],- },agentInterventionPreparation: {deduplicationId,resolutionRequestId,state: 'ready',stepIndex: 0,},+ },+ origin: {+ agentId: 'agent-ack-backfill',+ continuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },sourceMessageId: messageId,topicId: 'topic-ack-backfill',userId,@@ -1157,17 +1159,17 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {appContext: { sourceMessageId: messageId },id: continuationOperationId,metadata: {- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: operationId,- sourceToolMessageIds: [messageId],- },agentInterventionPreparation: {deduplicationId,resolutionRequestId,state: 'ready',stepIndex: 0,},+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },},status: 'running',topicId: 'topic-ready-disappears',@@ -1176,18 +1178,20 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {aiAgentService.loadInterventionContinuationState.mockResolvedValueOnce({metadata: {- agentId: 'agent-ready-disappears',- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: operationId,- sourceToolMessageIds: [messageId],- },agentInterventionPreparation: {deduplicationId,resolutionRequestId,state: 'ready',stepIndex: 0,},+ },+ origin: {+ agentId: 'agent-ready-disappears',+ continuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },sourceMessageId: messageId,topicId: 'topic-ready-disappears',userId,@@ -1276,17 +1280,17 @@ describe('aiAgentRouter β remote Human-in-the-loop', () => {},id: continuationOperationId,metadata: {- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: operationId,- sourceToolMessageIds: [messageId],- },agentInterventionPreparation: {deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),resolutionRequestId,state: 'ready',stepIndex: 0,},+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: operationId,+ sourceToolMessageIds: [messageId],+ },},status: 'running',topicId: 'topic-durable-ready-missing',diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 04586d2884a..aba981bec50 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -362,8 +362,7 @@ const probeRuntimeActionDispatch = async (: { state: 'conflict' };}- const stateProvenance = state.metadata?.agentInterventionContinuation as- typeof provenance | undefined;+ const stateProvenance = state.origin?.continuation as typeof provenance | undefined;const statePreparation = state.metadata?.agentInterventionPreparation as| {deduplicationId?: unknown;@@ -374,20 +373,20 @@ const probeRuntimeActionDispatch = async (| undefined;const stateContextMatches =state.operationId === continuationOperationId &&- state.metadata?.userId === resolution.ownerUserId &&+ state.origin?.userId === resolution.ownerUserId &&sameNullable(- state.metadata?.workspaceId,+ state.origin?.workspaceId,resolution.workspaceId ?? ctx.workspaceId ?? undefined,) &&- state.metadata?.agentId === continuation.agentId &&- state.metadata?.topicId === continuation.appContext.topicId &&- sameNullable(state.metadata?.threadId, continuation.appContext.threadId) &&- sameNullable(state.metadata?.taskId, continuation.appContext.taskId) &&- sameNullable(state.metadata?.groupId, continuation.appContext.groupId) &&- sameNullable(state.metadata?.documentId, continuation.appContext.documentId) &&- sameNullable(state.metadata?.scope, continuation.appContext.scope) &&- sameNullable(state.metadata?.sessionId, continuation.appContext.sessionId) &&- state.metadata?.sourceMessageId === continuation.parentMessageId &&+ state.origin?.agentId === continuation.agentId &&+ state.origin?.topicId === continuation.appContext.topicId &&+ sameNullable(state.origin?.threadId, continuation.appContext.threadId) &&+ sameNullable(state.origin?.taskId, continuation.appContext.taskId) &&+ sameNullable(state.origin?.groupId, continuation.appContext.groupId) &&+ sameNullable(state.origin?.documentId, continuation.appContext.documentId) &&+ sameNullable(state.origin?.scope, continuation.appContext.scope) &&+ sameNullable(state.origin?.sessionId, continuation.appContext.sessionId) &&+ state.origin?.sourceMessageId === continuation.parentMessageId &&stateProvenance?.resolutionRequestId === resolution.resolutionRequestId &&stateProvenance.sourceOperationId === continuation.operationId &&Array.isArray(stateProvenance.sourceToolMessageIds) &&diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex 364eb2b68d4..21f285374cb 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -321,7 +321,7 @@ export const shareChatRouter = router({// Not `RequestTrigger.Chat`: a share run is billed to the CREATOR,// so its spend rows must be separable from the creator's own chat// spend (they land on the same account). The trigger rides- // `state.metadata.trigger` all the way into the spend-log metadata.+ // `state.origin.trigger` all the way into the spend-log metadata.trigger: RequestTrigger.AgentShare,userAgent: ctx.userAgent ?? undefined,});diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex 12f5e2d9d3d..c44a90ef950 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -113,15 +113,10 @@ export class AbandonOperationService {const metadata = (state.metadata ?? {}) as {assistantMessageId?: string;- isSubAgent?: boolean;- orchestrationRole?: 'supervisor' | 'member';/** Present only for shared-agent visitor runs (visitor owns the stream). */streamOwnerUserId?: string;- threadId?: string | null;- topicId?: string | null;- userId?: string;- workspaceId?: string;};+ const origin = state.origin ?? {};const shouldDispatchAbandonedLifecycle =state.status === 'running' ||state.status === 'waiting_for_human' ||@@ -166,12 +161,12 @@ export class AbandonOperationService {// path must opt in when this flag is present.const includeShareVisitor = Boolean(metadata.streamOwnerUserId);- if (metadata.userId && metadata.assistantMessageId) {+ if (origin.userId && metadata.assistantMessageId) {try {const messageModel = new MessageModel(this.db,- metadata.userId,- metadata.workspaceId,+ origin.userId,+ origin.workspaceId,undefined,{ includeShareVisitor },);@@ -182,24 +177,20 @@ export class AbandonOperationService {}}- if (metadata.topicId && metadata.userId) {+ if (origin.topicId && origin.userId) {try {- const topicModel = new TopicModel(- this.db,- metadata.userId,- metadata.workspaceId,- undefined,- { includeShareVisitor },- );- await topicModel.settleRunningOperation(metadata.topicId, operationId);+ const topicModel = new TopicModel(this.db, origin.userId, origin.workspaceId, undefined, {+ includeShareVisitor,+ });+ await topicModel.settleRunningOperation(origin.topicId, operationId);} catch (e) {log('[%s] abandoned op runningOperation cleanup failed (non-fatal): %O', operationId, e);}}- if (!metadata.isSubAgent && metadata.userId && shouldDispatchAbandonedLifecycle) {+ if (!origin.lineage?.isSubAgent && origin.userId && shouldDispatchAbandonedLifecycle) {try {- await new CompletionLifecycle(this.db, metadata.userId, metadata.workspaceId, {+ await new CompletionLifecycle(this.db, origin.userId, origin.workspaceId, {includeShareVisitor,}).dispatchHooks(operationId, finalState, 'error', {skipErrorMessageWrite: result.assistantMessageUpdated,@@ -224,21 +215,23 @@ export class AbandonOperationService {// `scheduleGroupMemberTimeout`) β routing them through the sub-agent bridge// would backfill the wrong message and never satisfy the group barrier. They// are tagged `orchestrationRole: 'member'`, so skip them here.- if (metadata.isSubAgent && metadata.orchestrationRole !== 'member' && metadata.userId) {+ if (+ origin.lineage?.isSubAgent &&+ origin.lineage?.orchestrationRole !== 'member' &&+ origin.userId+ ) {try {const opRow = await new AgentOperationModel(this.db,- metadata.userId,- metadata.workspaceId,+ origin.userId,+ origin.workspaceId,).findById(operationId);const parentOperationId = opRow?.parentOperationId ?? undefined;- const threadId = opRow?.threadId ?? metadata.threadId ?? undefined;+ const threadId = opRow?.threadId ?? origin.threadId ?? undefined;if (parentOperationId && threadId) {- const thread = await new ThreadModel(- this.db,- metadata.userId,- metadata.workspaceId,- ).findById(threadId);+ const thread = await new ThreadModel(this.db, origin.userId, origin.workspaceId).findById(+ threadId,+ );const toolMessageId = thread?.sourceMessageId ?? undefined;if (toolMessageId) {result.subAgentResume = {@@ -250,8 +243,8 @@ export class AbandonOperationService {streamOwnerUserId: metadata.streamOwnerUserId,threadId,toolMessageId,- userId: metadata.userId,- workspaceId: metadata.workspaceId,+ userId: origin.userId,+ workspaceId: origin.workspaceId,};} else {log('[%s] sub-agent abandon: thread %s has no sourceMessageId', operationId, threadId);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 92b8fa134b6..090f6940334 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -452,8 +452,8 @@ describe('AgentRuntimeService', () => {messages: [],metadata: {modelRuntimeConfig: mockParams.modelRuntimeConfig,- userId: mockParams.userId,},+ origin: expect.objectContaining({ userId: mockParams.userId }),toolManifestMap: {},world: expect.objectContaining({ agent: mockParams.agentConfig }),}),@@ -2090,7 +2090,7 @@ describe('AgentRuntimeService', () => {stubMessageService(service, queryMessages);const result = await service.queryUiMessages({- metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },} as any);expect(queryMessages).toHaveBeenCalledWith(@@ -2110,7 +2110,7 @@ describe('AgentRuntimeService', () => {stubMessageService(service, queryMessages);await service.queryUiMessages({- metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },} as any);expect(queryMessages).toHaveBeenCalledWith(expect.anything(), { allowShareVisitor: true });@@ -2125,7 +2125,7 @@ describe('AgentRuntimeService', () => {stubMessageService(service, queryMessages);await service.queryUiMessages({- metadata: { agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' },+ origin: { agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' },} as any);expect(queryMessages).toHaveBeenCalledWith(@@ -2139,7 +2139,7 @@ describe('AgentRuntimeService', () => {stubMessageService(service, queryMessages);await service.queryUiMessages({- metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },} as any);expect(queryMessages.mock.calls[0][0].threadId).toBeUndefined();@@ -2150,10 +2150,10 @@ describe('AgentRuntimeService', () => {stubMessageService(service, queryMessages);const noAgent = await service.queryUiMessages({- metadata: { topicId: 'tpc_1' },+ origin: { topicId: 'tpc_1' },} as any);const noTopic = await service.queryUiMessages({- metadata: { agentId: 'agt_1' },+ origin: { agentId: 'agt_1' },} as any);const noMeta = await service.queryUiMessages({} as any);@@ -2168,7 +2168,7 @@ describe('AgentRuntimeService', () => {stubMessageService(service, queryMessages);const result = await service.queryUiMessages({- metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },} as any);expect(result).toBeUndefined();@@ -2491,7 +2491,7 @@ describe('AgentRuntimeService', () => {{ content: 'question', role: 'user' },{ content: 'final answer', role: 'assistant' },],- metadata: { agentId: 'agent-a' },+ origin: { agentId: 'agent-a' },modelRuntimeConfig: { model: 'gpt-test' },status: 'done',usage: { llm: { tokens: { total: 42 } }, tools: { totalCalls: 2 } },diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex ee24245347f..e894e71478e 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -630,7 +630,7 @@ export class AgentRuntimeService {const state = await this.coordinator.loadAgentState(operationId);if (!state) return 'missing';- const provenance = state.metadata?.agentInterventionContinuation as+ const provenance = state.origin?.continuation as| {resolutionRequestId?: unknown;sourceOperationId?: unknown;@@ -910,7 +910,7 @@ export class AgentRuntimeService {chatGroupId: appContext?.groupId ?? null,maxSteps,// Persist the Agent Signal run marker on the operation row so server-side- // self-iteration tools can read it back (metadata.agentSignal) at tool-call+ // self-iteration tools can read it back (operation.metadata.agentSignal) at tool-call// time β the trimmed appContext above intentionally drops it....(appContext?.agentSignal || interventionResolution? {@@ -1009,22 +1009,44 @@ export class AgentRuntimeService {activeDeviceScope,agentShareVisitor,botContext,+ clientIp: appContext?.clientIp,deviceAccessPolicy,evalRuntime,executionPlan,- ...(interventionResolution- ? { agentInterventionContinuation: interventionResolution }- : {}),// need be removedmodelRuntimeConfig,queueRetries,queueRetryDelay,stream,operationSkillSet,- userId,+ userAgent: appContext?.userAgent,workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,+ },+ // Where the run came from β frozen from here on. Mirrors the+ // agent_operations row so the runtime can hang its output on the right+ // conversation node without a lookup.+ origin: {+ agentId: appContext?.agentId,+ continuation: interventionResolution,+ defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,+ documentId: appContext?.documentId ?? undefined,+ groupId: appContext?.groupId ?? undefined,+ lineage: {+ isSubAgent: appContext?.isSubAgent,+ orchestrationRole: appContext?.orchestrationRole,+ parentOperationId,+ progressAnchor: appContext?.subAgentProgress,+ },+ scope: appContext?.scope ?? undefined,+ sessionId: appContext?.sessionId,+ signal: appContext?.agentSignal,+ sourceMessageId: appContext?.sourceMessageId,+ taskId: appContext?.taskId,+ threadId: appContext?.threadId ?? undefined,+ topicId: appContext?.topicId ?? undefined,+ trigger: appContext?.trigger,+ userId,workspaceId,- ...appContext,},maxSteps,// modelRuntimeConfig at state level for executor fallback@@ -1229,17 +1251,17 @@ export class AgentRuntimeService {skipWorks?: boolean;},): Promise<UIChatMessage[] | undefined> {- const agentId: string | undefined = agentState?.metadata?.agentId;- const topicId: string | undefined = agentState?.metadata?.topicId;+ const agentId: string | undefined = agentState?.origin?.agentId;+ const topicId: string | undefined = agentState?.origin?.topicId;// groupId scopes group conversations. Without it the query falls into the// standard branch (`groupId IS NULL`) and returns ZERO group messages, so// the step_start uiMessages snapshot would be empty and clobber the client.- const groupId: string | undefined = agentState?.metadata?.groupId;+ const groupId: string | undefined = agentState?.origin?.groupId;// threadId scopes a subtopic run. Without it the snapshot is the topic's// MAIN conversation, and the client writes that into the thread's bucket at// step_start / agent_runtime_end β wiping the turn the run just produced, so// the subtopic panel falls back to showing the main conversation.- const threadId: string | undefined = agentState?.metadata?.threadId ?? undefined;+ const threadId: string | undefined = agentState?.origin?.threadId ?? undefined;if (!agentId || !topicId) return undefined;try {@@ -1627,9 +1649,9 @@ export class AgentRuntimeService {invokeAgentSpan.setAttributes(buildInvokeAgentAttributes({agentDescription: stateAgentConfig?.description ?? undefined,- agentId: agentState.metadata?.agentId,+ agentId: agentState.origin?.agentId,agentName: stateAgentConfig?.title ?? undefined,- conversationId: agentState.metadata?.topicId,+ conversationId: agentState.origin?.topicId,operationId,provider: stateProvider,requestModel: stateModel,@@ -1724,6 +1746,7 @@ export class AgentRuntimeService {// Dispatch beforeStep hookstry {const beforeStepMetadata = agentState?.metadata || {};+ const beforeStepOrigin = agentState?.origin ?? {};// Agent Share visitor runs execute AS the creator, so this// `userId`-scoped source event would record creator-owned Agent// Signal state for a turn an anonymous link visitor triggered β same@@ -1734,20 +1757,20 @@ export class AgentRuntimeService {: await emitAgentSignalSourceEvent({payload: {- agentId: beforeStepMetadata?.agentId,+ agentId: beforeStepOrigin.agentId,operationId,serializedContext: undefined,stepIndex,- topicId: beforeStepMetadata?.topicId,+ topicId: beforeStepOrigin.topicId,turnCount: agentState?.stepCount || 0,},sourceId: `${operationId}:before:${stepIndex}`,sourceType: 'runtime.before_step',},{- agentId: beforeStepMetadata?.agentId,+ agentId: beforeStepOrigin.agentId,db: this.serverDB,- userId: beforeStepMetadata?.userId || this.userId,+ userId: beforeStepOrigin.userId || this.userId,workspaceId: this.workspaceId,},{ ignoreError: true },@@ -1757,12 +1780,12 @@ export class AgentRuntimeService {operationId,'beforeStep',{- agentId: beforeStepMetadata?.agentId || '',+ agentId: beforeStepOrigin.agentId || '',finalState: agentState,operationId,stepIndex,steps: agentState?.stepCount || 0,- userId: beforeStepMetadata?.userId || this.userId,+ userId: beforeStepOrigin.userId || this.userId,},beforeStepMetadata._hooks,);@@ -2098,6 +2121,7 @@ export class AgentRuntimeService {// Dispatch afterStep hooks (enriched with step presentation + tracking data)try {const metadata = stepResult.newState?.metadata || {};+ const origin = stepResult.newState?.origin ?? {};const tracking = metadata._stepTracking || {};const elapsedMs = stepResult.newState?.createdAt? Date.now() - new Date(stepResult.newState.createdAt).getTime()@@ -2112,20 +2136,20 @@ export class AgentRuntimeService {: await emitAgentSignalSourceEvent({payload: {- agentId: metadata?.agentId,+ agentId: origin.agentId,operationId,serializedContext: undefined,stepIndex,- topicId: metadata?.topicId,+ topicId: origin.topicId,turnCount: stepResult.newState?.stepCount || 0,},sourceId: `${operationId}:after:${stepIndex}`,sourceType: 'runtime.after_step',},{- agentId: metadata?.agentId,+ agentId: origin.agentId,db: this.serverDB,- userId: metadata?.userId || this.userId,+ userId: origin.userId || this.userId,},{ ignoreError: true },),@@ -2135,7 +2159,7 @@ export class AgentRuntimeService {operationId,'afterStep',{- agentId: metadata?.agentId || '',+ agentId: origin.agentId || '',content,elapsedMs,executionTimeMs: stepPresentationData.executionTimeMs,@@ -2155,14 +2179,14 @@ export class AgentRuntimeService {toolCalls: stepResult.newState?.usage?.tools?.totalCalls,toolsCalling: stepPresentationData.toolsCalling,toolsResult: stepPresentationData.toolsResult,- topicId: metadata?.topicId,+ topicId: origin.topicId,totalCost: stepPresentationData.totalCost,totalInputTokens: stepPresentationData.totalInputTokens,totalOutputTokens: stepPresentationData.totalOutputTokens,totalSteps: stepPresentationData.totalSteps,totalTokens: stepPresentationData.totalTokens,totalToolCalls: (tracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0),- userId: metadata?.userId || this.userId,+ userId: origin.userId || this.userId,},metadata._hooks,);@@ -3125,7 +3149,7 @@ export class AgentRuntimeService {* Best-effort: a publish failure must not fail the sub-agent's step.*/private async publishSubAgentProgress(state: AgentState, stepIndex: number): Promise<void> {- const anchor = state?.metadata?.subAgentProgress as+ const anchor = state?.origin?.lineage?.progressAnchor as{ parentOperationId: string; toolMessageId: string } | undefined;if (!anchor?.parentOperationId || !anchor.toolMessageId) return;@@ -3451,7 +3475,7 @@ export class AgentRuntimeService {);}}- const agentLabel = (finalState?.metadata?.agentId as string | undefined) ?? 'member';+ const agentLabel = (finalState?.origin?.agentId as string | undefined) ?? 'member';const memberErrorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;const anchorContent = failed? memberErrorReason@@ -3618,13 +3642,13 @@ export class AgentRuntimeService {return this.messageModel.query({- agentId: state.metadata?.agentId,+ agentId: state.origin?.agentId,// Group runs must pass groupId, else the query filters `groupId IS NULL`// and returns no group messages β the next LLM step then gets an empty// context and the provider rejects it ("at least one message is required").- groupId: state.metadata?.groupId,- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,+ groupId: state.origin?.groupId,+ threadId: state.origin?.threadId,+ topicId: state.origin?.topicId,},// The run's own topic is already resolved and authorized; an agent-share// visitor run executes under the CREATOR's identity, so it must opt out@@ -3710,7 +3734,7 @@ export class AgentRuntimeService {if (!Array.isArray(state.messages)) state.messages = [];- if (!state.metadata?.agentId || !state.metadata?.topicId) return;+ if (!state.origin?.agentId || !state.origin?.topicId) return;try {const refreshed = await this.refreshMessagesFromDB(state);@@ -3814,6 +3838,7 @@ export class AgentRuntimeService {: undefined;const world = (agentState as AgentState | undefined)?.world;+ const origin = (agentState as AgentState | undefined)?.origin;// Create Agent instance β use custom factory if provided, otherwise default to GeneralChatAgentconst generalConfig = {@@ -3825,11 +3850,11 @@ export class AgentRuntimeService {dynamicInterventionAudits,modelRuntimeConfig: metadata?.modelRuntimeConfig,operationId,- userId: metadata?.userId,+ userId: origin?.userId,};if (- metadata?.trigger === RequestTrigger.Eval &&+ origin?.trigger === RequestTrigger.Eval &&metadata.evalRuntime?.toolForwarding &&!hookDispatcher.hasHook(operationId, EVAL_TOOL_FORWARDING_HOOK_ID)) {@@ -3875,9 +3900,9 @@ export class AgentRuntimeService {stream: metadata?.stream,streamManager: this.streamManager,toolExecutionService: this.toolExecutionService,- topicId: metadata?.topicId,+ topicId: origin?.topicId,tracingContextEngine,- userId: metadata?.userId,+ userId: origin?.userId,workspaceId: this.workspaceId,};@@ -3897,12 +3922,12 @@ export class AgentRuntimeService {try {const dbMessages = await this.messageModel.query({- agentId: state.metadata?.agentId,+ agentId: state.origin?.agentId,// Group runs need groupId or the query returns no group messages// (standard branch filters `groupId IS NULL`), losing the device context.- groupId: state.metadata?.groupId,- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,+ groupId: state.origin?.groupId,+ threadId: state.origin?.threadId,+ topicId: state.origin?.topicId,},{ allowShareVisitor: true },);diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 81ef7f064c0..75a59f4f0c6 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -23,6 +23,7 @@ import {import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';+import { parseAgentSignalMarker } from '@/server/services/agentSignal/operationMarker';import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';import { registerWorksForOperation } from '@/server/services/workRegistration';@@ -252,7 +253,7 @@ export class CompletionLifecycle {const notification = await buildRuntimeInterventionNotification({operationId,state,- userId: state?.metadata?.userId || this.userId,+ userId: state?.origin?.userId || this.userId,workspaceId: this.workspaceId,});if (!notification) return;@@ -344,9 +345,9 @@ export class CompletionLifecycle {? reason: this.statusForReason(reason);- const metadata = state?.metadata ?? {};- const agentId = metadata?.agentId;- const topicId = metadata?.topicId;+ const runOrigin = state?.origin ?? {};+ const agentId = runOrigin.agentId;+ const topicId = runOrigin.topicId;const traceS3Key =agentId && topicId ? buildFinalSnapshotKey(agentId, topicId, operationId) : null;@@ -373,7 +374,7 @@ export class CompletionLifecycle {// rejected up front, so a child never has children of its own and the query// would always return zero.const rollup =- metadata?.isSubAgent === true ? undefined : await this.sumChildUsage(operationId);+ runOrigin.lineage?.isSubAgent === true ? undefined : await this.sumChildUsage(operationId);const add = (own: number | null | undefined, child: number): number | null => {if (!child) return own ?? null;@@ -489,9 +490,13 @@ export class CompletionLifecycle {*/async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {try {- const { assistantMessageId, metadata } = this.buildLifecycleEvent(operationId, state, reason);+ const {+ assistantMessageId,+ metadata,+ origin: runOrigin,+ } = this.buildLifecycleEvent(operationId, state, reason);- // Agent Share visitor runs execute AS the creator (`metadata.userId` is+ // Agent Share visitor runs execute AS the creator (`runOrigin.userId` is// the creator's id β see `isAgentShareRun`'s JSDoc), so every completion// signal below (`agent.execution.completed` / `.failed`) would otherwise// run synchronous policy processing and record creator-scoped windows /@@ -516,10 +521,10 @@ export class CompletionLifecycle {if (operationMetadata?.agentSignal) {selfIteration = extractSelfIterationCompletionPayload({...state,- metadata: {- ...operationMetadata,- ...metadata,- userId: metadata?.userId || this.userId,+ origin: {+ ...runOrigin,+ signal: parseAgentSignalMarker(operationMetadata.agentSignal),+ userId: runOrigin.userId || this.userId,},});}@@ -535,7 +540,7 @@ export class CompletionLifecycle {log('[completion-lifecycle] emit agent.execution.completed op=%s userId=%s assistant=%s metaAssistant=%s selfIteration=%s',operationId,- metadata?.userId || this.userId,+ runOrigin.userId || this.userId,assistantMessageId ?? 'undefined',metadata?.assistantMessageId ?? 'undefined',selfIteration@@ -548,21 +553,21 @@ export class CompletionLifecycle {? await emitAgentSignalSourceEvent({payload: {- agentId: metadata?.agentId,+ agentId: runOrigin.agentId,errorMessage: this.extractErrorMessage(state?.error),operationId,reason,serializedContext: undefined,- topicId: metadata?.topicId,+ topicId: runOrigin.topicId,turnCount: state?.stepCount || 0,},sourceId: `${operationId}:complete:${reason}`,sourceType: 'agent.execution.failed',},{- agentId: metadata?.agentId,+ agentId: runOrigin.agentId,db: this.serverDB,- userId: metadata?.userId || this.userId,+ userId: runOrigin.userId || this.userId,workspaceId: this.workspaceId,},{ ignoreError: true },@@ -570,7 +575,7 @@ export class CompletionLifecycle {: await emitAgentSignalSourceEvent({payload: {- agentId: metadata?.agentId,+ agentId: runOrigin.agentId,// Anchor the deferred skill synthesis to the completed assistant// turn: the completion-stage skill handler walks this id back// to the user message to read the parked candidate and seeds@@ -592,16 +597,16 @@ export class CompletionLifecycle {selfIteration,serializedContext: undefined,steps: state?.stepCount || 0,- topicId: metadata?.topicId,+ topicId: runOrigin.topicId,turnCount: state?.stepCount || 0,},sourceId: `${operationId}:complete:${reason}`,sourceType: 'agent.execution.completed',},{- agentId: metadata?.agentId,+ agentId: runOrigin.agentId,db: this.serverDB,- userId: metadata?.userId || this.userId,+ userId: runOrigin.userId || this.userId,workspaceId: this.workspaceId,},{ ignoreError: true },@@ -675,9 +680,11 @@ export class CompletionLifecycle {],metadata: {_hooks: input.serializedHooks,- agentId: input.agentId,assistantMessageId: input.assistantMessageId,- orchestrationRole: input.orchestrationRole,+ },+ origin: {+ agentId: input.agentId,+ lineage: { orchestrationRole: input.orchestrationRole },topicId: input.topicId,userId: input.userId ?? this.userId,},@@ -689,7 +696,7 @@ export class CompletionLifecycle {}/**- * The facts the recall gate needs. The trigger rides on `state.metadata` for+ * The facts the recall gate needs. The trigger rides on `state.origin` for* in-process runs (the appContext spread); synthetic terminals* ({@link buildStateFromInput}) have none, so fall back to the op row* `recordStart` stamped β which also reveals `parentOperationId`, marking@@ -698,10 +705,10 @@ export class CompletionLifecycle {*/private async resolveRunRecallFacts(operationId: string,- metadata: { trigger?: unknown } | undefined,+ runOrigin: { trigger?: unknown } | undefined,): Promise<{ isChildRun: boolean; trigger: string | undefined }> {- if (typeof metadata?.trigger === 'string')- return { isChildRun: false, trigger: metadata.trigger };+ if (typeof runOrigin?.trigger === 'string')+ return { isChildRun: false, trigger: runOrigin.trigger };try {const operation = await this.agentOperationModel.findById(operationId);@@ -725,9 +732,9 @@ export class CompletionLifecycle {private async recallUserOnCompletion(operationId: string,event: { agentId?: string; duration?: number; lastAssistantContent?: string; topicId?: string },- metadata: { trigger?: unknown; userId?: string } | undefined,+ runOrigin: { trigger?: unknown; userId?: string } | undefined,): Promise<void> {- const { isChildRun, trigger } = await this.resolveRunRecallFacts(operationId, metadata);+ const { isChildRun, trigger } = await this.resolveRunRecallFacts(operationId, runOrigin);if (isChildRun) {log('[%s] Skipping completion push for internal child run', operationId);return;@@ -743,7 +750,7 @@ export class CompletionLifecycle {lastAssistantContent: event.lastAssistantContent,operationId,topicId: event.topicId,- userId: metadata?.userId || this.userId,+ userId: runOrigin?.userId || this.userId,// Personal runs leave this undefined β bare deep link; workspace// runs carry the id so the business slot can slug-prefix the URL.workspaceId: this.workspaceId,@@ -796,14 +803,14 @@ export class CompletionLifecycle {finalUsage: state?.usage ?? null,operationId,serverDB: this.serverDB,- userId: state?.metadata?.userId || this.userId,+ userId: state?.origin?.userId || this.userId,workspaceId: this.workspaceId,});// Skill tools may have registered Works before the terminal file scan.// Query the registry instead of inferring output from display messages.const works = await new WorkModel(this.serverDB,- state?.metadata?.userId || this.userId,+ state?.origin?.userId || this.userId,this.workspaceId,).listByRootOperation({ includeFileWorks: true, limit: 1, rootOperationId: operationId });if (works.length > 0) {@@ -819,7 +826,7 @@ export class CompletionLifecycle {metadata: {work: {rootOperationId: operationId,- userMessageId: state?.metadata?.sourceMessageId,+ userMessageId: state?.origin?.sourceMessageId,},},});@@ -882,11 +889,12 @@ export class CompletionLifecycle {let shouldRetainHooksForRetry = false;try {- const { assistantMessageId, event, metadata } = this.buildLifecycleEvent(- operationId,- state,- reason,- );+ const {+ assistantMessageId,+ event,+ metadata,+ origin: runOrigin,+ } = this.buildLifecycleEvent(operationId, state, reason);// Finalize the agent_operations row before user hooks fire so// downstream consumers see the row in its terminal shape.@@ -920,8 +928,8 @@ export class CompletionLifecycle {const recovered = await this.recoverLastAssistantContent(operationId,assistantMessageId,- metadata?.userId || this.userId,- typeof metadata?.topicId === 'string' ? metadata.topicId : undefined,+ runOrigin.userId || this.userId,+ typeof runOrigin.topicId === 'string' ? runOrigin.topicId : undefined,);if (recovered) event.lastAssistantContent = recovered;}@@ -948,11 +956,11 @@ export class CompletionLifecycle {// from creator-facing surfaces.if (isSuccessLikeCompletionReason(reason) &&- metadata?.isSubAgent !== true &&- metadata?.orchestrationRole !== 'member' &&+ runOrigin.lineage?.isSubAgent !== true &&+ runOrigin.lineage?.orchestrationRole !== 'member' &&!isAgentShareRun(metadata)) {- void this.recallUserOnCompletion(operationId, event, metadata).catch((error) =>+ void this.recallUserOnCompletion(operationId, event, runOrigin).catch((error) =>log('[%s] Completion notification failed (non-fatal): %O', operationId, error),);}@@ -980,7 +988,7 @@ export class CompletionLifecycle {await this.createVerifyMessage(operationId,metadata?.assistantMessageId,- metadata?.userId || this.userId,+ runOrigin.userId || this.userId,);// `after`, not a bare `void`: judging is minutes of LLM calls and the// step handler must not wait for it, but a detached promise has nobody@@ -992,7 +1000,7 @@ export class CompletionLifecycle {after(() =>runVerifyOnCompletion(this.serverDB,- metadata?.userId || this.userId,+ runOrigin.userId || this.userId,{deliverable: event.lastAssistantContent ?? '',goal,@@ -1148,6 +1156,7 @@ export class CompletionLifecycle {private buildLifecycleEvent(operationId: string, state: any, reason: string) {const metadata = state?.metadata || {};+ const runOrigin = state?.origin ?? {};const messages = normalizeCompletionMessages(Array.isArray(state?.messages) ? state.messages : [],);@@ -1193,7 +1202,7 @@ export class CompletionLifecycle {return {assistantMessageId,event: {- agentId: metadata?.agentId || '',+ agentId: runOrigin.agentId || '',attachments: attachments.length > 0 ? attachments : undefined,cost: state?.cost?.total,duration,@@ -1210,11 +1219,12 @@ export class CompletionLifecycle {status: state?.status || reason,steps: state?.stepCount || 0,toolCalls: state?.usage?.tools?.totalCalls,- topicId: metadata?.topicId,+ topicId: runOrigin.topicId,totalTokens: state?.usage?.llm?.tokens?.total,- userId: metadata?.userId || this.userId,+ userId: runOrigin.userId || this.userId,},metadata,+ origin: runOrigin,};}}diff --git a/apps/server/src/services/agentRuntime/HumanInterventionHandler.ts b/apps/server/src/services/agentRuntime/HumanInterventionHandler.tsindex 16c2bb4a0ca..c9e59bd2ace 100644--- a/apps/server/src/services/agentRuntime/HumanInterventionHandler.ts+++ b/apps/server/src/services/agentRuntime/HumanInterventionHandler.ts@@ -96,7 +96,7 @@ export class HumanInterventionHandler {action: 'approve',operationId: state.metadata?.operationId ?? '',toolCallId: approvedToolCall.id,- userId: state.metadata?.userId,+ userId: state.origin?.userId,},state.metadata?._hooks,)@@ -180,7 +180,7 @@ export class HumanInterventionHandler {operationId: state.metadata?.operationId ?? '',rejectionReason,toolCallId: rejectedToolCallId,- userId: state.metadata?.userId,+ userId: state.origin?.userId,},state.metadata?._hooks,)@@ -213,7 +213,7 @@ export class HumanInterventionHandler {operationId: state.metadata?.operationId ?? '',rejectionReason,toolCallId: rejectedToolCallId,- userId: state.metadata?.userId,+ userId: state.origin?.userId,},state.metadata?._hooks,)diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.tsindex fd73364022b..aa27f144782 100644--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts@@ -160,9 +160,10 @@ export class OperationTraceRecorder {}const metadata = (params.state?.metadata ?? {}) as any;+ const origin = params.state?.origin ?? {};const finalizedSteps = (partial.steps ?? []).sort((a, b) => a.stepIndex - b.stepIndex);const snapshot = {- agentId: metadata?.agentId,+ agentId: origin.agentId,completedAt: Date.now(),completionReason: params.completionReason,error: params.error,@@ -177,7 +178,7 @@ export class OperationTraceRecorder {typeof metadata?.queueRetryDelay === 'string' ? metadata.queueRetryDelay : undefined,startedAt: partial.startedAt ?? Date.now(),steps: finalizedSteps,- topicId: metadata?.topicId,+ topicId: origin.topicId,totalCost: params.state?.cost?.total ?? 0,// Trust the finalized step array over `state.stepCount`: on the error// path stepCount comes from Redis and reflects the last completed@@ -185,7 +186,7 @@ export class OperationTraceRecorder {totalSteps: finalizedSteps.length || (params.state?.stepCount ?? 0),totalTokens: params.state?.usage?.llm?.tokens?.total ?? 0,traceId: operationId,- userId: metadata?.userId,+ userId: origin.userId,};await this.store.save(snapshot as any);diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex fc9ca783c61..02edd90dc44 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -77,8 +77,10 @@ vi.mock('@/database/models/topic', () => ({const stateWith = (overrides: Record<string, any> = {}) => ({cost: { total: 0.1 },metadata: {- agentId: 'agt_x',assistantMessageId: 'msg_assist_1',+ },+ origin: {+ agentId: 'agt_x',topicId: 'tpc_x',userId: 'user_x',},@@ -420,7 +422,9 @@ describe('AbandonOperationService', () => {it('does not crash when state has no metadata.assistantMessageId', async () => {const coord = buildCoordinator({- loadAgentState: vi.fn().mockResolvedValue(stateWith({ metadata: { userId: 'user_x' } })),+ loadAgentState: vi+ .fn()+ .mockResolvedValue(stateWith({ metadata: {}, origin: { userId: 'user_x' } })),});const store = buildStore();store.loadPartial.mockResolvedValue({ steps: [{ stepIndex: 0 }], startedAt: 1 });@@ -472,10 +476,12 @@ describe('AbandonOperationService', () => {stateWith({metadata: {assistantMessageId: 'msg_assist_1',- isSubAgent: true,+ },+ origin: {threadId: 'thread_1',userId: 'user_x',workspaceId: 'ws_1',+ lineage: { isSubAgent: true },},}),),@@ -515,12 +521,13 @@ describe('AbandonOperationService', () => {stateWith({metadata: {assistantMessageId: 'msg_assist_1',- isSubAgent: true,- orchestrationRole: 'member',+ },+ origin: {threadId: 'thread_g',topicId: 'tpc_x',userId: 'user_x',workspaceId: 'ws_1',+ lineage: { isSubAgent: true, orchestrationRole: 'member' },},}),),@@ -558,9 +565,11 @@ describe('AbandonOperationService', () => {loadAgentState: vi.fn().mockResolvedValue(stateWith({metadata: {- agentId: 'agt_x',assistantMessageId: 'msg_assist_1',streamOwnerUserId: 'visitor_1',+ },+ origin: {+ agentId: 'agt_x',topicId: 'tpc_x',userId: 'user_owner',workspaceId: 'ws_1',diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 66c2565522c..63149d923dd 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -177,7 +177,7 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {{ content: 'user prompt', role: 'user' },{ content: 'final answer', role: 'assistant' },],- metadata: { agentId: 'agent-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', userId: 'user-1' },};const { event } = callBuild(state);@@ -264,7 +264,7 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {role: 'assistantGroup',},],- metadata: { agentId: 'agent-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', userId: 'user-1' },};const { assistantMessageId, event } = callBuild(state);@@ -434,7 +434,7 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {});it('handles missing messages array gracefully', () => {- const { event } = callBuild({ metadata: { agentId: 'a' } });+ const { event } = callBuild({ origin: { agentId: 'a' } });expect(event.lastAssistantContent).toBeUndefined();expect(event.attachments).toBeUndefined();@@ -448,7 +448,7 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {// runtime error via formatErrorForState and surface these taxonomy fields.const state = {error: { error: { message: 'fetch failed' }, errorType: 'ProviderNetworkError' },- metadata: { agentId: 'agent-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', userId: 'user-1' },};const { event } = callBuild(state, 'error');@@ -473,7 +473,7 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {error: { message: 'Workspace budget exceeded' },errorType: 'InsufficientBudgetForModel',},- metadata: { agentId: 'agent-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', userId: 'user-1' },};const { event } = callBuild(state, 'error');@@ -508,7 +508,7 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {{ content: 'final answer', id: 'msg-assistant', role: 'assistant' },{ content: 'trailing tool result', id: 'msg-tool-2', role: 'tool' },],- metadata: { agentId: 'agent-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', userId: 'user-1' },};const { assistantMessageId } = callBuild(state, 'done');@@ -522,7 +522,8 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {// client already persisted the parked candidate against.const state = {messages: [{ content: 'final answer', id: 'msg-from-state', role: 'assistant' }],- metadata: { agentId: 'agent-1', assistantMessageId: 'msg-from-metadata' },+ metadata: { assistantMessageId: 'msg-from-metadata' },+ origin: { agentId: 'agent-1' },};const { assistantMessageId } = callBuild(state, 'done');@@ -651,7 +652,7 @@ describe('CompletionLifecycle.dispatchHooks β verify plan race', () => {expect(instantiateSpy).toHaveBeenCalledTimes(1);// Completion fires while the plan instantiation is still in flight.- const doneState = { metadata: { agentId: 'a', _hooks: [] }, status: 'done' };+ const doneState = { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'done' };const dispatch = lifecycle.dispatchHooks('op-1', doneState, 'done');// The gate must stay blocked on the pending instantiation, not race past it.@@ -686,7 +687,8 @@ describe('CompletionLifecycle.dispatchHooks β async-tool park', () => {});const parkedState = {- metadata: { agentId: 'a', _hooks: [] },+ metadata: { _hooks: [] },+ origin: { agentId: 'a' },status: 'waiting_for_async_tool',};@@ -709,7 +711,7 @@ describe('CompletionLifecycle.dispatchHooks β async-tool park', () => {const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);const unregisterSpy = vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});- const doneState = { metadata: { agentId: 'a', _hooks: [] }, status: 'done' };+ const doneState = { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'done' };await lifecycle.dispatchHooks('op-1', doneState, 'done');expect(dispatchSpy).toHaveBeenCalledWith('op-1', 'onComplete', expect.anything(), []);@@ -733,10 +735,11 @@ describe('CompletionLifecycle.dispatchHooks β completion notification', () =>(lifecycle as any).agentOperationModel = { findById: vi.fn(async () => null) };};- const buildDoneState = (metadata: Record<string, unknown> = {}) => ({+ const buildDoneState = (origin: Record<string, unknown> = {}) => ({createdAt: new Date(Date.now() - 90_000).toISOString(),messages: [{ content: 'final reply', role: 'assistant' }],- metadata: { _hooks: [], agentId: 'agt_1', topicId: 'tpc_1', ...metadata },+ metadata: { _hooks: [] },+ origin: { agentId: 'agt_1', topicId: 'tpc_1', ...origin },status: 'done',});@@ -834,7 +837,11 @@ describe('CompletionLifecycle.dispatchHooks β completion notification', () =>const lifecycle = buildLifecycle();stubSideEffects(lifecycle);- await lifecycle.dispatchHooks('op-1', buildDoneState({ isSubAgent: true }), 'done');+ await lifecycle.dispatchHooks(+ 'op-1',+ buildDoneState({ lineage: { isSubAgent: true } }),+ 'done',+ );await flushMicrotasks();expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();@@ -846,7 +853,11 @@ describe('CompletionLifecycle.dispatchHooks β completion notification', () =>// execAgentMember stamps in-group members with orchestrationRole: 'member'// but NOT isSubAgent β they are internal steps of the supervisor run.- await lifecycle.dispatchHooks('op-1', buildDoneState({ orchestrationRole: 'member' }), 'done');+ await lifecycle.dispatchHooks(+ 'op-1',+ buildDoneState({ lineage: { orchestrationRole: 'member' } }),+ 'done',+ );await flushMicrotasks();expect(mockNotifyAgentRunCompleted).not.toHaveBeenCalled();@@ -860,7 +871,7 @@ describe('CompletionLifecycle.dispatchHooks β completion notification', () =>orchestrationRole: 'member',});- expect(state.metadata.orchestrationRole).toBe('member');+ expect(state.origin.lineage.orchestrationRole).toBe('member');});it.each(['max_steps', 'cost_limit'])(@@ -882,7 +893,7 @@ describe('CompletionLifecycle.dispatchHooks β completion notification', () =>await lifecycle.dispatchHooks('op-1',- { metadata: { _hooks: [], agentId: 'agt_1' }, status: 'error' },+ { metadata: { _hooks: [] }, origin: { agentId: 'agt_1' }, status: 'error' },'error',);@@ -897,7 +908,7 @@ describe('CompletionLifecycle.dispatchHooks β completion notification', () =>// and leak into later dispatchHooks('done') tests in this file.mockNotifyAgentRunCompleted.mockRejectedValueOnce(new Error('push provider down'));- const doneState = { metadata: { _hooks: [], agentId: 'agt_1' }, status: 'done' };+ const doneState = { metadata: { _hooks: [] }, origin: { agentId: 'agt_1' }, status: 'done' };await expect(lifecycle.dispatchHooks('op-1', doneState, 'done')).resolves.toBeUndefined();await flushMicrotasks();@@ -1015,7 +1026,7 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file worksawait lifecycle.dispatchHooks('op-1',- { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },'waiting_for_human',);@@ -1052,7 +1063,7 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file worksawait expect(lifecycle.dispatchHooks('op-1',- { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },'waiting_for_human',),).rejects.toBeInstanceOf(CriticalAgentInterventionPersistenceError);@@ -1072,7 +1083,7 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file worksawait expect(lifecycle.dispatchHooks('op-1',- { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },'waiting_for_human',),).rejects.toMatchObject({@@ -1101,7 +1112,7 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file worksawait expect(lifecycle.dispatchHooks('op-1',- { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },'waiting_for_human',),).resolves.toBeUndefined();@@ -1116,7 +1127,7 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file worksawait lifecycle.dispatchHooks('op-1',- { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' },+ { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'waiting_for_human' },'waiting_for_human',);@@ -1136,7 +1147,11 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file worksvi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});- const parkedState = { metadata: { _hooks: [], agentId: 'a' }, status: 'waiting_for_human' };+ const parkedState = {+ metadata: { _hooks: [] },+ origin: { agentId: 'a' },+ status: 'waiting_for_human',+ };await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_human');expect(mockRegister).not.toHaveBeenCalled();@@ -1150,7 +1165,8 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file worksvi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);const parkedState = {- metadata: { _hooks: [], agentId: 'a' },+ metadata: { _hooks: [] },+ origin: { agentId: 'a' },status: 'waiting_for_async_tool',};await lifecycle.dispatchHooks('op-1', parkedState, 'waiting_for_async_tool');@@ -1169,7 +1185,8 @@ describe('CompletionLifecycle.dispatchHooks β lastAssistantContent DB recovery{ content: 'user prompt', id: 'msg-user', role: 'user' },{ content: assistantContent, id: 'msg-assistant', role: 'assistant' },],- metadata: { _hooks: [], agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },+ metadata: { _hooks: [] },+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },status: 'done',});@@ -1223,7 +1240,8 @@ describe('CompletionLifecycle.dispatchHooks β lastAssistantContent DB recoveryrole: 'assistantGroup',},],- metadata: { _hooks: [], agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },+ metadata: { _hooks: [] },+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },status: 'done',},'done',@@ -1418,7 +1436,7 @@ describe('CompletionLifecycle.emitSignalEvents β assistant anchor', () => {{ content: 'user prompt', id: 'msg-user', role: 'user' },{ content: 'final answer', id: 'msg-assistant', role: 'assistant' },],- metadata: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },stepCount: 2,};@@ -1455,7 +1473,7 @@ describe('CompletionLifecycle.emitSignalEvents β assistant anchor', () => {'op-1',{messages: [{ content: 'review complete', id: 'msg-assistant', role: 'assistant' }],- metadata: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },stepCount: 1,},'done',@@ -1491,7 +1509,8 @@ describe('CompletionLifecycle.registerFileWorks', () => {.mockResolvedValue({ success: true });const state = {messages: [{ id: 'display-group', role: 'assistantGroup', children: [] }],- metadata: { workAssistantMessageId: 'final-assistant', sourceMessageId: 'source-user' },+ metadata: { workAssistantMessageId: 'final-assistant' },+ origin: { sourceMessageId: 'source-user' },};await lifecycle.registerFileWorks('op-1', state);@@ -1577,7 +1596,8 @@ describe('CompletionLifecycle.registerFileWorks', () => {const lifecycle = buildLifecycle();const state = {cost: { total: 1.25 },- metadata: { userId: 'user-2' },+ metadata: {},+ origin: { userId: 'user-2' },usage: { llm: { apiCalls: 2 } },} as any;diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.workAnchors.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.workAnchors.integration.test.tsindex 003a64361f7..43084b7f167 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.workAnchors.integration.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.workAnchors.integration.test.ts@@ -98,7 +98,8 @@ describe('completion Work anchors with persisted messages and registered outputsexpect(folded.some((message) => message.role === 'assistantGroup')).toBe(true);const state = {messages: folded,- metadata: { workAssistantMessageId: 'final', sourceMessageId: 'source' },+ metadata: { workAssistantMessageId: 'final' },+ origin: { sourceMessageId: 'source' },};await lifecycle.registerFileWorks(operationId, state);const result = await messageModel.query({ topicId });diff --git a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.tsindex da573eda389..a0750212916 100644--- a/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/OperationTraceRecorder.test.ts@@ -257,7 +257,7 @@ describe('OperationTraceRecorder', () => {completionReason: 'done',state: {cost: { total: 0.5 },- metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'u-1' },+ origin: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'u-1' },stepCount: 1,usage: { llm: { tokens: { total: 200 } } },},diff --git a/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.tsindex 695be1f6f5d..c9b7156fda2 100644--- a/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/agentInterventionNotification.test.ts@@ -18,7 +18,7 @@ const binaryTool = {};const buildState = (overrides: Record<string, unknown> = {}) => ({- metadata: {+ origin: {agentId: 'agent-1',scope: 'main',sessionId: 'session-1',diff --git a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.tsindex ca4654e9ffe..8046e81bd64 100644--- a/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts@@ -124,7 +124,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {createdAt: new Date().toISOString(),lastModified: new Date().toISOString(),messages: [{ content: 'hello', role: 'user' }],- metadata: {+ origin: {agentId: 'agent-1',topicId: 'topic-1',userId: 'user-1',@@ -141,7 +141,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {events: [{ result: { content: 'done' }, type: 'llm_result' }],newState: {createdAt: new Date().toISOString(),- metadata: {+ origin: {agentId: 'agent-1',topicId: 'topic-1',userId: 'user-1',@@ -227,7 +227,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {createdAt: new Date().toISOString(),lastModified: new Date().toISOString(),messages: [{ content: 'hello', role: 'user' }],- metadata: {+ origin: {agentId: 'agent-1',topicId: 'topic-1',userId: 'user-1',@@ -244,7 +244,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {events: [{ result: { content: 'done' }, type: 'llm_result' }],newState: {createdAt: new Date().toISOString(),- metadata: {+ origin: {agentId: 'agent-1',topicId: 'topic-1',userId: 'user-1',@@ -328,6 +328,8 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {messages: [{ content: 'hello', role: 'user' }],metadata: {_hooks: ['serialized-hook'],+ },+ origin: {agentId: 'agent-1',topicId: 'topic-1',userId: 'user-1',@@ -346,6 +348,8 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {createdAt: new Date().toISOString(),metadata: {_hooks: ['serialized-hook'],+ },+ origin: {agentId: 'agent-1',topicId: 'topic-1',userId: 'user-1',diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.tsindex 186d5ba5bc3..a1a10c18028 100644--- a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts@@ -39,7 +39,7 @@ describe('CompletionLifecycle β verify gate scheduling', () => {await lifecycle.dispatchHooks('op-1',- { metadata: { _hooks: [], agentId: 'a' }, status: 'done' },+ { metadata: { _hooks: [] }, origin: { agentId: 'a' }, status: 'done' },'done',);diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.tsindex 63ba306936c..65a202b6d72 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts@@ -93,9 +93,11 @@ describe('AgentRuntimeService intervention continuation dispatch recovery', () =const readyState = (status: 'done' | 'idle' | 'running' = 'idle') => ({initialContext: { phase: 'user_input' },metadata: {- agentInterventionContinuation: provenance,agentInterventionPreparation: preparation,},+ origin: {+ continuation: provenance,+ },operationId,status,});@@ -150,13 +152,13 @@ describe('AgentRuntimeService intervention continuation dispatch recovery', () =const operationModel = (service as any).agentOperationModel;operationModel.findById = vi.fn().mockResolvedValue({metadata: {- agentInterventionContinuation: provenance,agentInterventionDispatch: {deduplicationId,messageId: 'queue-message',resolutionRequestId: provenance.resolutionRequestId,state: 'scheduled',},+ agentInterventionContinuation: provenance,agentInterventionPreparation: preparation,},});@@ -323,6 +325,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>metadata: {agentConfig: {},modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },+ },+ origin: {userId: 'user-1',},operationId: 'op-workspace',@@ -344,7 +348,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>};await (service as any).createAgentRuntime({- metadata: { agentConfig: {}, modelRuntimeConfig, userId: 'user-1' },+ metadata: { agentConfig: {}, modelRuntimeConfig },+ origin: { userId: 'user-1' },operationId: 'op-model-runtime-snapshot',stepIndex: 0,});@@ -365,6 +370,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>metadata: {agentConfig: {},modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },+ },+ origin: {userId: 'user-1',},operationId: 'op-custom-agent',@@ -394,6 +401,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>metadata: {agentConfig: {},modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },+ },+ origin: {userId: 'user-1',},operationId: 'op-graph-agent',@@ -416,6 +425,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>metadata: {agentConfig: {},modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },+ },+ origin: {userId: 'user-1',},operationId: 'op-general-agent',@@ -457,6 +468,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>metadata: {agentConfig: {},modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },+ },+ origin: {userId: 'user-1',},operationId: 'op-entity-edit',@@ -477,6 +490,8 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>metadata: {agentConfig: {},modelRuntimeConfig: { model: 'gpt-test', provider: 'lobehub' },+ },+ origin: {userId: 'user-1',},operationId: 'op-plain-edit',@@ -1356,7 +1371,7 @@ describe('AgentRuntimeService.executeStep - error-path snapshot finalize ()', ()// metadata.coordinator.loadAgentState = vi.fn().mockResolvedValue({lastModified: new Date().toISOString(),- metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },+ origin: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },status: 'running',stepCount: 1,});@@ -1496,7 +1511,7 @@ describe('AgentRuntimeService.executeStep - error-path snapshot finalize ()', ()streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);coordinator.loadAgentState = vi.fn().mockResolvedValue({lastModified: new Date().toISOString(),- metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },+ origin: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },status: 'running',stepCount: 1,});@@ -1577,7 +1592,7 @@ describe('AgentRuntimeService.executeStep - error-path snapshot finalize ()', ()// not skip this attempt β we want the catch path to run.coordinator.loadAgentState = vi.fn().mockResolvedValue({lastModified: new Date().toISOString(),- metadata: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },+ origin: { agentId: 'agt-1', topicId: 'tpc-1', userId: 'user-1' },status: 'running',stepCount: 1,});@@ -1634,7 +1649,7 @@ describe('AgentRuntimeService.executeStep - step_start uiMessages payload', () =status: 'done',stepCount: 3,lastModified: new Date().toISOString(),- metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },});streamManager.publishStreamEvent = vi.fn().mockResolvedValue(undefined);diff --git a/apps/server/src/services/agentRuntime/__tests__/executeSync.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeSync.test.tsindex ae25c235ae2..703d5c57721 100644--- a/apps/server/src/services/agentRuntime/__tests__/executeSync.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/executeSync.test.ts@@ -159,8 +159,8 @@ describe('AgentRuntimeService.executeSync', () => {const state = await stateManager.loadAgentState(operationId);expect(state).not.toBeNull();expect(state?.messages).toHaveLength(2);- expect(state?.metadata?.agentId).toBe('test-agent');- expect(state?.metadata?.topicId).toBe('topic-1');+ expect(state?.origin?.agentId).toBe('test-agent');+ expect(state?.origin?.topicId).toBe('topic-1');});});diff --git a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.tsindex 9a83f13ebb3..b9b5168695a 100644--- a/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/hooksIntegration.test.ts@@ -92,6 +92,8 @@ describe('Hooks integration β afterStep event carries step presentation data',messages: [{ content: 'Hello', role: 'user' }],metadata: {_hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],+ },+ origin: {agentId: 'agent-1',userId: 'user-1',},@@ -114,6 +116,8 @@ describe('Hooks integration β afterStep event carries step presentation data',],metadata: {_hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],+ },+ origin: {agentId: 'agent-1',topicId: 'topic-1',userId: 'user-1',@@ -194,6 +198,8 @@ describe('Hooks integration β afterStep event carries step presentation data',metadata: {_hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],_stepTracking: { lastLLMContent: 'previous content', totalToolCalls: 1 },+ },+ origin: {agentId: 'agent-1',userId: 'user-1',},@@ -211,6 +217,8 @@ describe('Hooks integration β afterStep event carries step presentation data',metadata: {_hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],_stepTracking: { lastLLMContent: 'previous content', totalToolCalls: 1 },+ },+ origin: {agentId: 'agent-1',userId: 'user-1',},@@ -282,7 +290,7 @@ describe('Hooks integration β onComplete event for early-terminal states', (){ content: 'Hello', role: 'user' },{ content: 'I was working on it...', role: 'assistant' },],- metadata: { agentId: 'agent-1', userId: 'user-1' },+ origin: { agentId: 'agent-1', userId: 'user-1' },status: 'interrupted',stepCount: 3,usage: { llm: { apiCalls: 2, tokens: { total: 500 } }, tools: { totalCalls: 1 } },@@ -326,6 +334,8 @@ describe('Hooks integration β afterStep event is compatible with renderStepPromessages: [],metadata: {_hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],+ },+ origin: {agentId: 'agent-1',userId: 'user-1',},@@ -341,6 +351,8 @@ describe('Hooks integration β afterStep event is compatible with renderStepPromessages: [{ content: 'Result', role: 'assistant' }],metadata: {_hooks: [{ id: 'bot-step', type: 'afterStep', webhook: { url: '/test' } }],+ },+ origin: {agentId: 'agent-1',userId: 'user-1',},diff --git a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts b/apps/server/src/services/agentRuntime/agentInterventionNotification.tsindex 6ca535f212e..969a7705dc5 100644--- a/apps/server/src/services/agentRuntime/agentInterventionNotification.ts+++ b/apps/server/src/services/agentRuntime/agentInterventionNotification.ts@@ -224,6 +224,7 @@ export const buildRuntimeInterventionNotification = async ({const batch = state?.pendingApprovalBatch;const toolMessageIds = state?.pendingToolMessageIds;const metadata = state?.metadata ?? {};+ const origin = state?.origin ?? {};if (state?.status !== 'waiting_for_human' ||@@ -358,7 +359,7 @@ export const buildRuntimeInterventionNotification = async ({}return {- agentId: boundedString(metadata.agentId),+ agentId: boundedString(origin.agentId),approvalMode: resolvedApprovalMode,batch: {activityKey: deriveAgentInterventionActivityKey({@@ -374,17 +375,17 @@ export const buildRuntimeInterventionNotification = async ({stepIndex: batch.stepIndex,},context: {- agentId: boundedString(metadata.agentId),+ agentId: boundedString(origin.agentId),assistantMessageId: batch.assistantMessageId,- groupId: boundedString(metadata.groupId),+ groupId: boundedString(origin.groupId),operationId,- pageId: boundedString(metadata.documentId),- scope: messageMapScope(metadata.scope),- sessionId: boundedString(metadata.sessionId),- taskId: boundedString(metadata.taskId),- threadId: boundedString(metadata.threadId),- topicId: boundedString(metadata.topicId),- triggerMessageId: boundedString(metadata.sourceMessageId),+ pageId: boundedString(origin.documentId),+ scope: messageMapScope(origin.scope),+ sessionId: boundedString(origin.sessionId),+ taskId: boundedString(origin.taskId),+ threadId: boundedString(origin.threadId),+ topicId: boundedString(origin.topicId),+ triggerMessageId: boundedString(origin.sourceMessageId),workspaceId,},items,diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 2eb168786e9..4cfc47111b9 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -414,7 +414,7 @@ export interface OperationCreationParams {agentId?: string;/*** Run-scoped Agent Signal marker. Stamped at dispatch for background- * self-iteration / memory runs; lands in `state.metadata.agentSignal` and is+ * self-iteration / memory runs; lands in `state.origin.signal` and is* read on the completion path to project receipts.*/agentSignal?: AgentSignalOperationMarker;@@ -429,7 +429,7 @@ export interface OperationCreationParams {groupId?: string | null;isSubAgent?: boolean;/**- * Group orchestration role, spread onto `state.metadata.orchestrationRole`.+ * Group orchestration role, stored on `state.origin.lineage.orchestrationRole`.* Lets the inactivity-watchdog abandon path tell an isolated group member* (`'member'`, resumed via the group K=N bridge) apart from a genuine* callSubAgent child (which shares `isSubAgent: true`).@@ -441,8 +441,8 @@ export interface OperationCreationParams {/** Source user message ID used for same-turn Agent Signal procedure suppression. */sourceMessageId?: string;/**- * Live-progress anchor for a `callSubAgent` child, spread onto- * `state.metadata.subAgentProgress`.+ * Live-progress anchor for a `callSubAgent` child, stored on+ * `state.origin.lineage.progressAnchor`.** The child runs on its own operationId, but the client only ever subscribes* to the PARENT's gateway channel β which stays open across the sub-agent run@@ -569,7 +569,7 @@ export interface OperationCreationParams {/*** Workspace ID propagated down from the originating chat/task router so* tool executions (createBrief / pinTask / etc.) ownership-filter to the- * caller's workspace. Stored on `state.metadata.workspaceId`.+ * caller's workspace. Stored on `state.origin.workspaceId`.*/workspaceId?: string;}diff --git a/apps/server/src/services/agentSignal/operationMarker.ts b/apps/server/src/services/agentSignal/operationMarker.tsindex 8ac7a7b2ad5..993a531818d 100644--- a/apps/server/src/services/agentSignal/operationMarker.ts+++ b/apps/server/src/services/agentSignal/operationMarker.ts@@ -39,7 +39,14 @@ export const readAgentSignalMarker = (metadata: unknown,): AgentSignalOperationMarker | undefined => {if (!isRecord(metadata)) return undefined;- const marker = metadata.agentSignal;+ return parseAgentSignalMarker(metadata.agentSignal);+};++/**+ * Validates a raw marker value (`operation.metadata.agentSignal` or+ * `state.origin.signal`). Returns `undefined` unless it names a known kind.+ */+export const parseAgentSignalMarker = (marker: unknown): AgentSignalOperationMarker | undefined => {if (!isRecord(marker)) return undefined;const kind = marker.kind;diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.tsindex 5de3725c0c2..0087acaef54 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts@@ -298,7 +298,7 @@ describe('completion skill synthesis end-to-end (emit -> handler, no operation-mmessages,// Operation-level metadata only β no per-turn assistantMessageId, exactly// as a server execAgent turn persists it.- metadata: { agentId: 'agent_1', topicId: TOPIC_ID, userId: 'user_1' },+ origin: { agentId: 'agent_1', topicId: TOPIC_ID, userId: 'user_1' },stepCount: 3,status: 'done',},diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsindex c3ac7808eec..6f3660a9b83 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -317,7 +317,7 @@ export const runMemoryActionAgent = async (};// Async (queued execAgent) path: enqueue the run with the marker stamped onto- // appContext (it lands in state.metadata.agentSignal), then return immediately.+ // appContext (it lands in state.origin.signal), then return immediately.// The durable receipt is projected on the completion path from the run's// finalState β no blocking executeSync.if (dispatch) {diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.tsindex 80926b81ecb..70d7dc8352f 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts@@ -14,15 +14,15 @@ const toolMessage = (apiName: string, kind: string, data: Record<string, unknowntool_call_id: `${apiName}_call`,});-const buildState = (metadata: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({+const buildState = (origin: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({messages: [],- metadata,+ origin,...extra,});const reviewMetadata = {agentId: 'agent_user_1',- agentSignal: { agentId: 'agent_user_1', kind: 'nightly-review', sourceId: 'src_1' },+ signal: { agentId: 'agent_user_1', kind: 'nightly-review', sourceId: 'src_1' },userId: 'user_1',};@@ -36,7 +36,7 @@ describe('extractSelfIterationCompletionPayload', () => {it('returns undefined without a userId', () => {expect(extractSelfIterationCompletionPayload(- buildState({ agentId: 'agent_x', agentSignal: { kind: 'nightly-review' } }),+ buildState({ agentId: 'agent_x', signal: { kind: 'nightly-review' } }),),).toBeUndefined();});@@ -64,7 +64,7 @@ describe('extractSelfIterationCompletionPayload', () => {buildState({agentId: 'agent_user_1',- agentSignal: { kind: 'memory', sourceId: 'mem-src_1' },+ signal: { kind: 'memory', sourceId: 'mem-src_1' },userId: 'user_1',},{@@ -133,7 +133,7 @@ describe('extractSelfIterationCompletionPayload', () => {buildState({agentId: 'agent_user_1',- agentSignal: { kind: 'memory', sourceId: 'mem-src_fallback' },+ signal: { kind: 'memory', sourceId: 'mem-src_fallback' },userId: 'user_1',},{@@ -166,7 +166,7 @@ describe('extractSelfIterationCompletionPayload', () => {buildState({agentId: 'agent_user_1',- agentSignal: { kind: 'memory', sourceId: 'mem-src_2' },+ signal: { kind: 'memory', sourceId: 'mem-src_2' },userId: 'user_1',},{ status: 'finished', usage: { tools: { byTool: [] } } },diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.tsindex efe31a06381..bac5ebb25f5 100644--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts@@ -2,7 +2,7 @@ import type { AgentState } from '@lobechat/agent-runtime';import {type AgentSignalOperationMarker,- readAgentSignalMarker,+ parseAgentSignalMarker,} from '@/server/services/agentSignal/operationMarker';import { resolveMemoryActionResultFromState } from '@/server/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult';@@ -72,13 +72,13 @@ export const extractSelfIterationCompletionPayload = (state: unknown,): SelfIterationCompletionPayload | undefined => {if (!isRecord(state)) return undefined;- const metadata = isRecord(state.metadata) ? state.metadata : undefined;- if (!metadata) return undefined;+ const origin = isRecord(state.origin) ? state.origin : undefined;+ if (!origin) return undefined;- const marker = readAgentSignalMarker(metadata);+ const marker = parseAgentSignalMarker(origin.signal);if (!marker) return undefined;- const userId = typeof metadata.userId === 'string' ? metadata.userId : undefined;+ const userId = typeof origin.userId === 'string' ? origin.userId : undefined;if (!userId) return undefined;const finalState = state as unknown as AgentState;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex f214e88e9f9..e15c2769607 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -539,9 +539,9 @@ describe('AiAgentService.execAgent - resumeApproval', () => {intervention: { operationId: 'op-parked', status: 'pending' },});mockLoadInterventionContinuationState.mockImplementation(async (operationId: string) => ({- metadata: {+ origin: {agentId: 'agent-1',- agentInterventionContinuation: {+ continuation: {resolutionRequestId: approvalResolutionRequestId,sourceOperationId: 'op-parked',sourceToolMessageIds: ['tool-msg-1'],@@ -592,12 +592,14 @@ describe('AiAgentService.execAgent - resumeApproval', () => {});mockLoadInterventionContinuationState.mockResolvedValue({metadata: {- agentId: 'agent-1',- agentInterventionContinuation: provenance,agentInterventionPreparation: {resolutionRequestId: approvalResolutionRequestId,state: 'ready',},+ },+ origin: {+ agentId: 'agent-1',+ continuation: provenance,sourceMessageId: 'tool-msg-1',topicId: 'topic-1',userId: 'user-1',@@ -681,16 +683,16 @@ describe('AiAgentService.execAgent - resumeApproval', () => {mockFindOperationById.mockResolvedValue({id: continuationOperationId,metadata: {- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: 'op-parked',- sourceToolMessageIds: ['tool-msg-1'],- },agentInterventionDispatch: {deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),resolutionRequestId,state: 'scheduled',},+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ },},startedAt: new Date('2026-08-26T00:00:00.000Z'),status: 'running',@@ -730,16 +732,16 @@ describe('AiAgentService.execAgent - resumeApproval', () => {mockFindOperationById.mockResolvedValue({id: continuationOperationId,metadata: {- agentInterventionContinuation: {- resolutionRequestId,- sourceOperationId: 'op-parked',- sourceToolMessageIds: ['tool-msg-1'],- },agentInterventionDispatch: {deduplicationId: deriveAgentInterventionQueueDeduplicationId(continuationOperationId, 0),resolutionRequestId,state: 'scheduled',},+ agentInterventionContinuation: {+ resolutionRequestId,+ sourceOperationId: 'op-parked',+ sourceToolMessageIds: ['tool-msg-1'],+ },},status: 'running',topicId: 'topic-1',diff --git a/apps/server/src/services/aiAgent/pipeline/approvalResume.ts b/apps/server/src/services/aiAgent/pipeline/approvalResume.tsindex 84b358a79f3..10fd9b6a41e 100644--- a/apps/server/src/services/aiAgent/pipeline/approvalResume.ts+++ b/apps/server/src/services/aiAgent/pipeline/approvalResume.ts@@ -484,13 +484,13 @@ export const tryReuseInterventionContinuation = async (expectedProvenance,) &&existingState.operationId === continuationOperationId &&- existingState.metadata?.userId === deps.userId &&- (existingState.metadata?.workspaceId ?? null) === (deps.workspaceId ?? null) &&- existingState.metadata?.agentId === resolvedAgentId &&- existingState.metadata?.topicId === topicId &&- existingState.metadata?.sourceMessageId === parentMessageId &&+ existingState.origin?.userId === deps.userId &&+ (existingState.origin?.workspaceId ?? null) === (deps.workspaceId ?? null) &&+ existingState.origin?.agentId === resolvedAgentId &&+ existingState.origin?.topicId === topicId &&+ existingState.origin?.sourceMessageId === parentMessageId &&matchesAgentInterventionContinuationProvenance(- existingState.metadata?.agentInterventionContinuation,+ existingState.origin?.continuation,expectedProvenance,) &&existingAssistant?.role === 'assistant' &&diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 4b843036454..8aca9e206f8 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -182,7 +182,7 @@ export const startOperation = async (// inherit the builtin agent's tools / systemRole / model), but their// resource tools and receipts must attribute to the *reviewed* user// agent, which rides on the marker. Prefer it so the tool-execution- // context (state.metadata.agentId) targets the reviewed agent; ordinary+ // context (state.origin.agentId) targets the reviewed agent; ordinary// runs (no marker) fall back to the resolved executing agent.agentId: appContext?.agentSignal?.agentId ?? resolvedAgentId,// Propagate the originating request's client IP / user agent into@@ -206,7 +206,7 @@ export const startOperation = async (? { editingGroupId: appContext.editingGroupId }: {}),// Run-scoped Agent Signal marker for background self-iteration / memory- // runs β lands in state.metadata.agentSignal so the completion path can+ // runs β lands in state.origin.signal so the completion path can// project receipts/briefs. Undefined for ordinary chat runs....(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,diff --git a/apps/server/src/services/llmGenerationTracing/hook.ts b/apps/server/src/services/llmGenerationTracing/hook.tsindex 505b0dfc31d..704a2c0f96e 100644--- a/apps/server/src/services/llmGenerationTracing/hook.ts+++ b/apps/server/src/services/llmGenerationTracing/hook.ts@@ -66,7 +66,7 @@ export const createLLMGenerationTracingHook = (const tracing = parseTracingOptions(context.options?.tracing as Record<string, unknown>);// `trigger` is also read by ModelRuntime itself (timing logs) so it// legitimately lives on `metadata`. Honour the explicit `tracing.trigger`- // override but fall back to the cross-cutting `metadata.trigger`.+ // override but fall back to the cross-cutting `origin.trigger`.const metadataTrigger = pickString((context.options?.metadata as Record<string, unknown> | undefined)?.trigger,);diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex a442e3cba7a..d6d34bb16dc 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -332,7 +332,7 @@ export interface ToolExecutionContext {* Workspace ID that scopes ownership for any model/service the runtime* instantiates. When unset the runtime falls back to personal mode* (`workspace_id IS NULL`). Threaded from the chat/task router through- * `state.metadata.workspaceId` so tool side-effects (createBrief, pinTask,+ * `state.origin.workspaceId` so tool side-effects (createBrief, pinTask,* etc.) land in the same workspace the request originated from.*/workspaceId?: string;diff --git a/packages/agent-runtime/src/executors/abortedToolRows.ts b/packages/agent-runtime/src/executors/abortedToolRows.tsindex b353a316716..754075db357 100644--- a/packages/agent-runtime/src/executors/abortedToolRows.ts+++ b/packages/agent-runtime/src/executors/abortedToolRows.ts@@ -86,10 +86,10 @@ export const settleAbortedToolRows = async ({messages: Array<{ content: string; id: string; role: 'tool'; tool_call_id: string }>;}> => {const { operation, transports } = host;- const agentId = operation.agentId ?? state.metadata?.agentId;- const groupId = operation.groupId ?? state.metadata?.groupId;- const threadId = operation.threadId ?? state.metadata?.threadId;- const topicId = operation.topicId ?? state.metadata?.topicId;+ const agentId = operation.agentId ?? state.origin?.agentId;+ const groupId = operation.groupId ?? state.origin?.groupId;+ const threadId = operation.threadId ?? state.origin?.threadId;+ const topicId = operation.topicId ?? state.origin?.topicId;if (!agentId) {throw new Error(diff --git a/packages/agent-runtime/src/executors/callLlm.test.ts b/packages/agent-runtime/src/executors/callLlm.test.tsindex 5af59b47b1a..af825897218 100644--- a/packages/agent-runtime/src/executors/callLlm.test.ts+++ b/packages/agent-runtime/src/executors/callLlm.test.ts@@ -26,7 +26,7 @@ const createState = (): AgentState => ({createdAt: new Date().toISOString(),lastModified: new Date().toISOString(),messages: [],- metadata: {+ origin: {agentId: 'agent-1',threadId: 'thread-1',topicId: 'topic-1',diff --git a/packages/agent-runtime/src/executors/callLlm.ts b/packages/agent-runtime/src/executors/callLlm.tsindex 138d0b8cb53..a39fee25671 100644--- a/packages/agent-runtime/src/executors/callLlm.ts+++ b/packages/agent-runtime/src/executors/callLlm.ts@@ -211,7 +211,7 @@ const assertPreparedCallContext = (if (!messages.some((message) => message.role !== 'system')) {throw new Error(`call_llm produced no non-system messages for ${prepared.provider}/${prepared.model} ` +- `(topic=${prepared.state.metadata?.topicId ?? 'n/a'}, step=${stepIndex}); refusing to dispatch`,+ `(topic=${prepared.state.origin?.topicId ?? 'n/a'}, step=${stepIndex}); refusing to dispatch`,);}};@@ -323,9 +323,9 @@ export const callLlm =? { id: existingAssistantMessageId }: await transports.messages.createAssistantMessage({- agentId: state.metadata!.agentId!,+ agentId: (operation.agentId ?? state.origin?.agentId) as string,content: '',- groupId: state.metadata?.groupId ?? undefined,+ groupId: state.origin?.groupId ?? undefined,// Creation provenance (metadata.operationId): ties the row to the// operation that produced it so the id survives client reloads.metadata: { operationId: operation.operationId },@@ -333,8 +333,8 @@ export const callLlm =parentId,provider,role: 'assistant',- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,+ threadId: state.origin?.threadId,+ topicId: state.origin?.topicId,},{/**@@ -391,7 +391,7 @@ export const callLlm =assertPreparedCallContext(prepared, operation.stepIndex);const trace = llm.createTrace?.({assistantMessageId: assistantMessage.id,- conversationId: state.metadata?.topicId,+ conversationId: state.origin?.topicId,model,provider,});diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.tsindex 0bf6f451c85..34f933fbc78 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts@@ -65,7 +65,7 @@ describe('callLlmFinalizer', () => {it('retains the final assistant id independently of the rehydrated message shape', async () => {const state = AgentRuntime.createInitialState({messages: [{ id: 'group-1', role: 'assistantGroup', children: [] }],- metadata: { sourceMessageId: 'user-1' },+ origin: { sourceMessageId: 'user-1' },operationId: 'operation-1',});const result = await finalizeCallLlmTurn({@@ -79,10 +79,8 @@ describe('callLlmFinalizer', () => {state,});- expect(result.newState.metadata).toMatchObject({- sourceMessageId: 'user-1',- workAssistantMessageId: 'final-assistant',- });+ expect(result.newState.origin).toMatchObject({ sourceMessageId: 'user-1' });+ expect(result.newState.metadata).toMatchObject({ workAssistantMessageId: 'final-assistant' });// This key belongs to error recovery; a completed tool turn must not// redirect a subsequent LLM failure to the previous assistant message.expect(result.newState.metadata).not.toHaveProperty('assistantMessageId');@@ -223,7 +221,7 @@ describe('callLlmFinalizer', () => {const host = createHost(messages, stream);const state = AgentRuntime.createInitialState({messages: [{ content: 'Question', role: 'user' }],- metadata: { topicId: 'topic-1' },+ origin: { topicId: 'topic-1' },operationId: 'operation-1',});const usage = {@@ -423,7 +421,7 @@ describe('callLlmFinalizer', () => {},{ content: 'created', id: 'tool-1', role: 'tool' },],- metadata: { sourceMessageId: 'user-1' },+ origin: { sourceMessageId: 'user-1' },operationId: 'operation-1',});@@ -459,7 +457,7 @@ describe('callLlmFinalizer', () => {shouldReplayAssistantReasoning: false,state: AgentRuntime.createInitialState({messages: [{ content: 'Hi', id: 'user-2', role: 'user' }],- metadata: { sourceMessageId: 'user-2' },+ origin: { sourceMessageId: 'user-2' },operationId: 'operation-1',}),});diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.tsindex 2a7eb2b9858..a5fd6751353 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts@@ -148,7 +148,7 @@ const buildWorkAnchor = ({}): MessageMetadata['work'] => {if (output.toolsCalling.length > 0 || output.toolCalls.length > 0) return undefined;- const sourceMessageId = state.metadata?.sourceMessageId;+ const sourceMessageId = state.origin?.sourceMessageId;const sourceMessageIndex =typeof sourceMessageId === 'string'? state.messages.findIndex((message) => message.id === sourceMessageId)diff --git a/packages/agent-runtime/src/executors/compressContext.test.ts b/packages/agent-runtime/src/executors/compressContext.test.tsindex fcd37f626f5..00a5a1c795a 100644--- a/packages/agent-runtime/src/executors/compressContext.test.ts+++ b/packages/agent-runtime/src/executors/compressContext.test.ts@@ -46,7 +46,7 @@ const createState = (overrides?: Partial<AgentState>): AgentState => ({lastModified: new Date().toISOString(),maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-123',threadId: 'thread-123',topicId: 'topic-123',@@ -283,7 +283,7 @@ describe('compressContext executor', () => {it('skips without compression side effects when topic context is missing', async () => {const state = createState({- metadata: { agentId: 'agent-123' },+ origin: { agentId: 'agent-123' },messages: [{ content: 'history', role: 'user' }],});const missingContextHost: AgentRuntimeHost = {diff --git a/packages/agent-runtime/src/executors/compressContext.ts b/packages/agent-runtime/src/executors/compressContext.tsindex 8ad7ab48538..a7491bc21ec 100644--- a/packages/agent-runtime/src/executors/compressContext.ts+++ b/packages/agent-runtime/src/executors/compressContext.ts@@ -47,11 +47,11 @@ export const compressContext =const { operationId, stepIndex, userId } = operation;const events: AgentEvent[] = [];const newState = structuredClone(state);- const topicId = state.metadata?.topicId ?? operation.topicId;- const workspaceId = state.metadata?.workspaceId ?? operation.workspaceId;- const agentId = operation.agentId ?? state.metadata?.agentId;- const groupId = operation.groupId ?? state.metadata?.groupId;- const threadId = operation.threadId ?? state.metadata?.threadId;+ const topicId = state.origin?.topicId ?? operation.topicId;+ const workspaceId = state.origin?.workspaceId ?? operation.workspaceId;+ const agentId = operation.agentId ?? state.origin?.agentId;+ const groupId = operation.groupId ?? state.origin?.groupId;+ const threadId = operation.threadId ?? state.origin?.threadId;const compression = transports.compression;const llm = transports.llm;// The latest user turn is the active contract even after assistant/tool steps have followed it.diff --git a/packages/agent-runtime/src/executors/humanApprove.ts b/packages/agent-runtime/src/executors/humanApprove.tsindex 3ff01bd759a..2cbaba30dec 100644--- a/packages/agent-runtime/src/executors/humanApprove.ts+++ b/packages/agent-runtime/src/executors/humanApprove.ts@@ -22,10 +22,10 @@ export const requestHumanApprove =} = instruction as Extract<AgentInstruction, { type: 'request_human_approve' }>;const { operation, transports, lifecycle } = host;const { operationId, stepIndex, userId } = operation;- const agentId = operation.agentId ?? state.metadata?.agentId;- const groupId = operation.groupId ?? state.metadata?.groupId;- const threadId = operation.threadId ?? state.metadata?.threadId;- const topicId = operation.topicId ?? state.metadata?.topicId;+ const agentId = operation.agentId ?? state.origin?.agentId;+ const groupId = operation.groupId ?? state.origin?.groupId;+ const threadId = operation.threadId ?? state.origin?.threadId;+ const topicId = operation.topicId ?? state.origin?.topicId;// Publish human approval request eventawait transports.stream.publishEvent({diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.tsindex cdfa09d4327..a36ba674fd8 100644--- a/packages/agent-runtime/src/executors/resolveTools.test.ts+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts@@ -16,7 +16,7 @@ const createState = (overrides?: Partial<AgentState>): AgentState => ({lastModified: '2026-07-07T00:00:00.000Z',maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-1',threadId: 'thread-1',topicId: 'topic-1',diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.tsindex 9ef119436ad..a755763d423 100644--- a/packages/agent-runtime/src/executors/resolveTools.ts+++ b/packages/agent-runtime/src/executors/resolveTools.ts@@ -33,10 +33,10 @@ export const resolveBlockedTools =async (instruction, state) => {const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_blocked_tools' }>;const { operation, transports } = host;- const agentId = operation.agentId ?? state.metadata?.agentId;- const groupId = operation.groupId ?? state.metadata?.groupId;- const threadId = operation.threadId ?? state.metadata?.threadId;- const topicId = operation.topicId ?? state.metadata?.topicId;+ const agentId = operation.agentId ?? state.origin?.agentId;+ const groupId = operation.groupId ?? state.origin?.groupId;+ const threadId = operation.threadId ?? state.origin?.threadId;+ const topicId = operation.topicId ?? state.origin?.topicId;const events: AgentEvent[] = [];const newState = structuredClone(state);const blockedContent = payload.blockedContent ?? BLOCKED_TOOL_CONTENT;diff --git a/packages/agent-runtime/src/executors/subAgent.test.ts b/packages/agent-runtime/src/executors/subAgent.test.tsindex edb9ae07237..7019c6a7e46 100644--- a/packages/agent-runtime/src/executors/subAgent.test.ts+++ b/packages/agent-runtime/src/executors/subAgent.test.ts@@ -16,7 +16,7 @@ const createState = (overrides?: Partial<AgentState>): AgentState => ({lastModified: '2026-07-09T00:00:00.000Z',maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'parent-agent',threadId: 'thread-1',topicId: 'topic-1',@@ -175,7 +175,9 @@ describe('sub-agent executors', () => {const result = await execSubAgent(host)(instruction,- createState({ metadata: { agentId: 'parent-agent', isSubAgent: true, topicId: 'topic-1' } }),+ createState({+ origin: { agentId: 'parent-agent', topicId: 'topic-1', lineage: { isSubAgent: true } },+ }),);expect(execSubAgentTransport).not.toHaveBeenCalled();diff --git a/packages/agent-runtime/src/executors/subAgent.ts b/packages/agent-runtime/src/executors/subAgent.tsindex 4690343a84f..102f542c0ca 100644--- a/packages/agent-runtime/src/executors/subAgent.ts+++ b/packages/agent-runtime/src/executors/subAgent.ts@@ -74,9 +74,9 @@ const executeTask = async (parentMessageId: string,task: SubAgentTask,): Promise<TaskExecutionResult> => {- const agentId = host.operation.agentId ?? state.metadata?.agentId;+ const agentId = host.operation.agentId ?? state.origin?.agentId;const targetAgentId = task.targetAgentId ?? agentId;- const topicId = host.operation.topicId ?? state.metadata?.topicId;+ const topicId = host.operation.topicId ?? state.origin?.topicId;if (!agentId || !targetAgentId || !topicId) {return {@@ -97,7 +97,7 @@ const executeTask = async (try {const execution = await host.transports.subAgent.execSubAgent({agentId: targetAgentId,- groupId: host.operation.groupId ?? state.metadata?.groupId ?? undefined,+ groupId: host.operation.groupId ?? state.origin?.groupId ?? undefined,instruction: task.instruction,parentMessageId,parentOperationId: host.operation.operationId,@@ -160,10 +160,10 @@ const formatBatchResultContent = (const queryMessages = (host: AgentRuntimeHost, state: AgentState) =>host.transports.messages.query({- agentId: host.operation.agentId ?? state.metadata?.agentId,- groupId: host.operation.groupId ?? state.metadata?.groupId ?? undefined,- threadId: host.operation.threadId ?? state.metadata?.threadId,- topicId: host.operation.topicId ?? state.metadata?.topicId,+ agentId: host.operation.agentId ?? state.origin?.agentId,+ groupId: host.operation.groupId ?? state.origin?.groupId ?? undefined,+ threadId: host.operation.threadId ?? state.origin?.threadId,+ topicId: host.operation.topicId ?? state.origin?.topicId,});export const execSubAgent =@@ -174,7 +174,7 @@ export const execSubAgent =const events: AgentEvent[] = [];const { operationId } = host.operation;- if (state.metadata?.isSubAgent === true) {+ if (state.origin?.lineage?.isSubAgent === true) {return {events,newState: state,@@ -215,7 +215,7 @@ export const execSubAgents =const events: AgentEvent[] = [];const { operationId } = host.operation;- if (state.metadata?.isSubAgent === true) {+ if (state.origin?.lineage?.isSubAgent === true) {return {events,newState: state,diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex b23da0aabf3..ea06ed018cf 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -30,7 +30,7 @@ const createState = (overrides?: Partial<AgentState>): AgentState => ({lastModified: '2026-07-09T00:00:00.000Z',maxSteps: 100,messages: [],- metadata: {+ origin: {agentId: 'agent-1',threadId: 'thread-1',topicId: 'topic-1',diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex be79853df3c..10dea5ca552 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -184,7 +184,7 @@ const createRunContext = ({return {abortSignal: host.operation.abortSignal,activatedSkills: extractActivatedSkillsFromMessages(state.messages),- agentId: host.operation.agentId ?? state.metadata?.agentId,+ agentId: host.operation.agentId ?? state.origin?.agentId,assistantMessageId: parentMessageId,callIndex: resolveCallIndex(state, toolName),// Todo state is reconstructed from message history for the same reason the@@ -193,8 +193,8 @@ const createRunContext = ({// tool-execution side must not treat it as the source of truth.currentTodos: extractTodosFromMessages(state.messages)?.items,effectiveManifestMap: buildEffectiveManifestMap(state),- groupId: host.operation.groupId ?? state.metadata?.groupId,- messageId: state.metadata?.sourceMessageId,+ groupId: host.operation.groupId ?? state.origin?.groupId,+ messageId: state.origin?.sourceMessageId,mode,operationId: host.operation.operationId,parentMessageId,@@ -203,13 +203,13 @@ const createRunContext = ({state,stepIndex: host.operation.stepIndex,stepContext,- threadId: host.operation.threadId ?? state.metadata?.threadId,+ threadId: host.operation.threadId ?? state.origin?.threadId,toolMessageId,toolName,toolResultMaxLength: agentConfig?.chatConfig?.toolResultMaxLength,toolSource,- topicId: host.operation.topicId ?? state.metadata?.topicId,- workspaceId: state.metadata?.workspaceId ?? host.operation.workspaceId,+ topicId: host.operation.topicId ?? state.origin?.topicId,+ workspaceId: state.origin?.workspaceId ?? host.operation.workspaceId,};};@@ -428,7 +428,7 @@ const createToolMessage = async ({tool: ChatToolPayload;}) => {try {- const agentId = host.operation.agentId ?? state.metadata?.agentId;+ const agentId = host.operation.agentId ?? state.origin?.agentId;if (!agentId) {throw new Error(`[call_tool] Missing agentId for tool message (op=${host.operation.operationId})`,@@ -438,16 +438,16 @@ const createToolMessage = async ({return await host.transports.messages.createToolMessage({agentId,content: result.content,- groupId: host.operation.groupId ?? state.metadata?.groupId ?? undefined,+ groupId: host.operation.groupId ?? state.origin?.groupId ?? undefined,metadata: { toolExecutionTimeMs: result.executionTime ?? 0 },parentId: parentMessageId,plugin: tool as any,pluginError: result.error,pluginState: result.state,role: 'tool',- threadId: host.operation.threadId ?? state.metadata?.threadId,+ threadId: host.operation.threadId ?? state.origin?.threadId,tool_call_id: tool.id,- topicId: host.operation.topicId ?? state.metadata?.topicId,+ topicId: host.operation.topicId ?? state.origin?.topicId,});} catch (error) {await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);@@ -1076,10 +1076,10 @@ export const callToolsBatch =newState.messages = await host.transports.messages.query({- agentId: state.metadata?.agentId,- groupId: state.metadata?.groupId,- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,+ agentId: state.origin?.agentId,+ groupId: state.origin?.groupId,+ threadId: state.origin?.threadId,+ topicId: state.origin?.topicId,},{ flatten: true, resolveAssetUrls: true },);diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex 3d0dc1512ab..8191ea0cb19 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -12,6 +12,7 @@ import type {UserMemoryConfig,} from '@lobechat/context-engine';import type {+ AgentSignalOperationMarker,ChatToolPayload,ExpertiseContextSnapshot,LobeAgentChatConfig,@@ -22,6 +23,79 @@ import type {import type { Cost, CostLimit, Usage } from './usage';+/**+ * The run's position in the run tree.+ */+export interface AgentRunLineage {+ /** True for any child run (callSubAgent child or isolated group member). */+ isSubAgent?: boolean;+ /**+ * Group orchestration role. Tells an isolated group member (`'member'`,+ * resumed via the group K=N bridge) apart from a genuine callSubAgent child,+ * which also carries `isSubAgent: true`.+ */+ orchestrationRole?: 'supervisor' | 'member';+ /** Operation that spawned this run, when it is a child. */+ parentOperationId?: string;+ /**+ * Live-progress anchor for a callSubAgent child. The child runs on its own+ * operation, but the client only subscribes to the parent's channel, so the+ * child's step loop publishes its running totals there, addressed at the+ * placeholder tool message.+ */+ progressAnchor?: { parentOperationId: string; toolMessageId: string };+}++/**+ * Server-authored provenance for a continuation created from a durable human+ * intervention claim. Lets a retry tell this exact continuation apart from an+ * unrelated operation that happens to reuse an id.+ */+export interface InterventionContinuation {+ resolutionRequestId: string;+ sourceOperationId: string;+ sourceToolMessageIds: string[];+}++/**+ * Where this run came from: who asked for it, on which conversation node,+ * and where it sits in the run tree.+ *+ * Written by the caller and the orchestrator when the run is requested and+ * frozen from then on. Mirrors the durable operation row (which stays the+ * authority) so the runtime can hang its output on the right conversation+ * node without a lookup.+ */+export interface AgentRunOrigin {+ // --- Conversation node ---+ /** Effective message owner for this run (the group member when applicable). */+ agentId?: string;+ /** Set when this run continues a durable human-intervention claim. */+ continuation?: InterventionContinuation;+ // --- Trigger ---+ /** Default assignee for tasks the run creates. */+ defaultTaskAssigneeAgentId?: string;+ documentId?: string;+ groupId?: string;+ // --- Run tree ---+ lineage?: AgentRunLineage;+ scope?: string;+ sessionId?: string;+ /** Run-scoped Agent Signal marker for background self-iteration / memory runs. */+ signal?: AgentSignalOperationMarker;+ /** Source user message that started the turn. */+ sourceMessageId?: string;++ taskId?: string;+ threadId?: string;+ topicId?: string;+ /** Request trigger (chat, eval, bot, β¦). */+ trigger?: string;+ userId?: string;++ workspaceId?: string;+}+/*** Search route resolved once before the run starts. Declared here rather than* imported so the runtime package does not depend on the model catalog;@@ -177,7 +251,7 @@ export interface AgentState {/*** Un-converged run context. Keys that have a business home live in the- * typed slots (`world`, `binding`, β¦); anything left here is either host+ * typed slots (`origin`, `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.*/@@ -208,10 +282,17 @@ export interface AgentState {provider: string;};};- operationId: string;+ operationId: string;/** Operation-level tool set snapshot (immutable after creation) */operationToolSet?: OperationToolSet;++ // --- Origin ---+ /**+ * Where this run came from and where it sits in the run tree. Frozen when+ * the operation is created.+ */+ origin?: AgentRunOrigin;pendingApprovalBatch?: {assistantMessageId: string;id: string;diff --git a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts b/packages/agent-runtime/src/utils/normalizeAgentState.test.tsindex c7f30d50fd6..41813eea0ba 100644--- a/packages/agent-runtime/src/utils/normalizeAgentState.test.ts+++ b/packages/agent-runtime/src/utils/normalizeAgentState.test.ts@@ -18,7 +18,7 @@ const baseState = (): AgentState =>describe('normalizeAgentState', () => {it('returns the same object when metadata carries no legacy keys', () => {- const state = { ...baseState(), metadata: { userId: 'u1', _hooks: [] } };+ const state = { ...baseState(), metadata: { _hooks: [], queueRetries: 2 } };expect(normalizeAgentState(state)).toBe(state);});@@ -62,7 +62,8 @@ describe('normalizeAgentState', () => {expect(normalized.binding).toEqual({device: { id: 'dev_1', platform: 'darwin', systemInfo: { workingDirectory: '/tmp' } },});- expect(normalized.metadata).toEqual({ userId: 'u1' });+ expect(normalized.origin).toEqual({ userId: 'u1' });+ expect(normalized.metadata).toEqual({});// Input is not mutated.expect(state.metadata.agentConfig).toEqual({ systemRole: 'hi' });});@@ -82,6 +83,71 @@ describe('normalizeAgentState', () => {expect(normalized.metadata).toEqual({});});+ it('lifts identity, trigger and lineage keys into origin', () => {+ const state = {+ ...baseState(),+ metadata: {+ _hooks: [],+ agentId: 'agent-1',+ agentInterventionContinuation: {+ resolutionRequestId: 'r1',+ sourceOperationId: 'op-0',+ sourceToolMessageIds: ['t1'],+ },+ agentSignal: { kind: 'memory' },+ groupId: null,+ isSubAgent: true,+ orchestrationRole: 'member',+ sourceMessageId: 'msg-1',+ subAgentProgress: { parentOperationId: 'op-0', toolMessageId: 't1' },+ threadId: undefined,+ topicId: 'topic-1',+ trigger: 'chat',+ userId: 'u1',+ workspaceId: 'ws-1',+ },+ };++ const normalized = normalizeAgentState(state);++ expect(normalized.origin).toEqual({+ agentId: 'agent-1',+ continuation: {+ resolutionRequestId: 'r1',+ sourceOperationId: 'op-0',+ sourceToolMessageIds: ['t1'],+ },+ lineage: {+ isSubAgent: true,+ orchestrationRole: 'member',+ progressAnchor: { parentOperationId: 'op-0', toolMessageId: 't1' },+ },+ signal: { kind: 'memory' },+ sourceMessageId: 'msg-1',+ topicId: 'topic-1',+ trigger: 'chat',+ userId: 'u1',+ workspaceId: 'ws-1',+ });+ // `null` / `undefined` legacy values are absent, not carried as null.+ expect('groupId' in normalized.origin!).toBe(false);+ expect('threadId' in normalized.origin!).toBe(false);+ expect(normalized.metadata).toEqual({ _hooks: [] });+ });++ it('merges lifted origin keys into an existing origin without overriding it', () => {+ const state = {+ ...baseState(),+ metadata: { agentId: 'agent-old', topicId: 'topic-1' },+ origin: { agentId: 'agent-new' },+ };++ const normalized = normalizeAgentState(state);++ expect(normalized.origin).toEqual({ agentId: 'agent-new', topicId: 'topic-1' });+ expect(normalized.metadata).toEqual({});+ });+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 50f405fbcfb..73eac0223de 100644--- a/packages/agent-runtime/src/utils/normalizeAgentState.ts+++ b/packages/agent-runtime/src/utils/normalizeAgentState.ts@@ -1,88 +1,98 @@-import type { AgentRunBinding, AgentState, AgentWorldSnapshot } from '../types';+import type { AgentState } 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.+ * the slot path each one moves to. 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 LEGACY_KEY_PATHS: Record<string, readonly string[]> = {+ // --- origin: conversation node ---+ agentId: ['origin', 'agentId'],+ documentId: ['origin', 'documentId'],+ groupId: ['origin', 'groupId'],+ scope: ['origin', 'scope'],+ sessionId: ['origin', 'sessionId'],+ taskId: ['origin', 'taskId'],+ threadId: ['origin', 'threadId'],+ topicId: ['origin', 'topicId'],+ userId: ['origin', 'userId'],+ workspaceId: ['origin', 'workspaceId'],+ // --- origin: trigger ---+ agentInterventionContinuation: ['origin', 'continuation'],+ agentSignal: ['origin', 'signal'],+ defaultTaskAssigneeAgentId: ['origin', 'defaultTaskAssigneeAgentId'],+ sourceMessageId: ['origin', 'sourceMessageId'],+ trigger: ['origin', 'trigger'],+ // --- origin: run tree ---+ isSubAgent: ['origin', 'lineage', 'isSubAgent'],+ orchestrationRole: ['origin', 'lineage', 'orchestrationRole'],+ subAgentProgress: ['origin', 'lineage', 'progressAnchor'],+ // --- world ---+ agentConfig: ['world', 'agent'],+ agentGroup: ['world', 'group'],+ botPlatformContext: ['world', 'channel', 'botPlatform'],+ connectorOwnershipNote: ['world', 'connectorOwnershipNote'],+ discordContext: ['world', 'channel', 'discord'],+ evalContext: ['world', 'eval'],+ projectInstructions: ['world', 'projectInstructions'],+ searchDecision: ['world', 'searchDecision'],+ userMemory: ['world', 'userMemory'],+ userTimezone: ['world', 'userTimezone'],+ // --- binding ---+ activeDeviceId: ['binding', 'device', 'id'],+ devicePlatform: ['binding', 'device', 'platform'],+ deviceSystemInfo: ['binding', 'device', 'systemInfo'],+};-const DEVICE_KEYS = {- activeDeviceId: 'id',- devicePlatform: 'platform',- deviceSystemInfo: 'systemInfo',-} as const satisfies Record<string, keyof NonNullable<AgentRunBinding['device']>>;+const LEGACY_KEYS = Object.keys(LEGACY_KEY_PATHS);-const LEGACY_KEYS = [- ...Object.keys(WORLD_KEYS),- ...Object.keys(CHANNEL_KEYS),- ...Object.keys(DEVICE_KEYS),-];+const isPresent = (record: Record<string, unknown>, key: string) =>+ Object.prototype.hasOwnProperty.call(record, key) &&+ record[key] !== undefined &&+ record[key] !== null;-const hasOwn = (record: Record<string, unknown>, key: string) =>- Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined;+/**+ * Write `value` at `path` unless something is already there. Clones every+ * object along the path so the input state is never mutated.+ */+const setIfAbsent = (root: Record<string, unknown>, path: readonly string[], value: unknown) => {+ let node = root;+ for (const key of path.slice(0, -1)) {+ const next = node[key];+ const clone = next && typeof next === 'object' ? { ...(next as object) } : {};+ node[key] = clone;+ node = clone as Record<string, unknown>;+ }+ const leaf = path.at(-1)!;+ if (node[leaf] === undefined) node[leaf] = value;+};/**- * Lift legacy `metadata.*` run context into the typed `world` / `binding`- * slots so every reader can rely on the slots alone.+ * Lift legacy `metadata.*` run context into the typed `origin` / `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.+ * (the in-flight state blob has a hard 10MB ceiling). `null` legacy values+ * are treated as absent: the slots use `undefined` only. 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;+ if (!metadata || !LEGACY_KEYS.some((key) => Object.prototype.hasOwnProperty.call(metadata, key)))+ return state;- 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 next = { ...state } as Record<string, unknown>;+ for (const [legacyKey, path] of Object.entries(LEGACY_KEY_PATHS)) {+ if (isPresent(metadata, legacyKey)) setIfAbsent(next, path, 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;}+ next.metadata = strippedMetadata;- return {- ...state,- ...(binding && { binding }),- metadata: strippedMetadata,- ...(Object.keys(world).length > 0 && { world }),- };+ return next as T;};