🤯 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): add client runtime host adapters (#17099)
Arvin Xu759ec8fd74da
diff --git a/packages/agent-runtime/src/executors/humanApprove.ts b/packages/agent-runtime/src/executors/humanApprove.tsindex ab1add2465c..1157ef79cb9 100644--- a/packages/agent-runtime/src/executors/humanApprove.ts+++ b/packages/agent-runtime/src/executors/humanApprove.ts@@ -20,6 +20,10 @@ export const requestHumanApprove =>;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;// Publish human approval request eventawait transports.stream.publishEvent({@@ -63,12 +67,12 @@ export const requestHumanApprove =// tool_call_id so we can still ship the mapping to the client.try {const dbMessages = await transports.messages.query({- agentId: state.metadata?.agentId,+ agentId,// Group runs need groupId or the query returns no group messages, so// the existing tool-message lookup on resume would find nothing.- groupId: state.metadata?.groupId,- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,+ groupId,+ threadId,+ topicId,});for (const toolPayload of pendingToolsCalling) {const existing = dbMessages.find(@@ -85,48 +89,55 @@ export const requestHumanApprove =// Find parent assistant message. Prefer state.messages (already in// memory from call_llm); fall back to a query if the runtime has been// rehydrated without recent messages.- let parentAssistantId: string | undefined = (state.messages ?? [])+ let parentAssistant = (state.messages ?? []).slice().reverse()- .find((m: any) => m.role === 'assistant' && m.id)?.id;+ .find((m: any) => m.role === 'assistant' && m.id) as+ { groupId?: string | null; id: string } | undefined;- if (!parentAssistantId) {+ if (!parentAssistant) {try {const dbMessages = await transports.messages.query({- agentId: state.metadata?.agentId,+ agentId,// Group runs need groupId or the query returns no group messages, so// the parent-assistant fallback lookup would find nothing.- groupId: state.metadata?.groupId,- threadId: state.metadata?.threadId,- topicId: state.metadata?.topicId,+ groupId,+ threadId,+ topicId,});- parentAssistantId = dbMessages+ parentAssistant = dbMessages.slice().reverse()- .find((m: any) => m.role === 'assistant')?.id;+ .find((m: any) => m.role === 'assistant');} catch {// fall through to the missing-parent guard below}}- if (!parentAssistantId) {+ if (!parentAssistant) {throw new Error(- `[request_human_approve] No assistant message found as parent for pending tool messages (op=${operationId})`,+ `[request_human_approve] No assistant message found for intervention (op=${operationId})`,+ );+ }++ if (!agentId) {+ throw new Error(+ `[request_human_approve] Missing agentId for pending tool messages (op=${operationId})`,);}for (const toolPayload of pendingToolsCalling) {const toolMessage = await transports.messages.createToolMessage({- agentId: state.metadata!.agentId!,+ agentId,content: '',- groupId: state.metadata?.groupId ?? undefined,- parentId: parentAssistantId,+ groupId: groupId ?? parentAssistant.groupId ?? undefined,+ parentId: parentAssistant.id,plugin: toolPayload as any,pluginIntervention: { status: 'pending' },role: 'tool',- threadId: state.metadata?.threadId,+ threadId,tool_call_id: toolPayload.id,- topicId: state.metadata?.topicId,+ topicId,});toolMessageIds[toolPayload.id] = toolMessage.id;diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.tsindex 39bf6d35d6a..2b6f3c11302 100644--- a/packages/agent-runtime/src/executors/resolveTools.ts+++ b/packages/agent-runtime/src/executors/resolveTools.ts@@ -80,11 +80,21 @@ 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 events: AgentEvent[] = [];const newState = structuredClone(state);const toolResults: Array<{ data: ToolRunResult; toolCallId: string }> = [];const toolMessageIds: string[] = [];+ if (!agentId) {+ throw new Error(+ `[resolve_blocked_tools] Missing agentId for tool messages (op=${operation.operationId})`,+ );+ }+for (const toolPayload of payload.toolsCalling) {const result: ToolRunResult = {content: BLOCKED_TOOL_CONTENT,@@ -110,9 +120,9 @@ export const resolveBlockedTools =try {const toolMessage = await transports.messages.createToolMessage({- agentId: state.metadata!.agentId!,+ agentId,content: result.content,- groupId: state.metadata?.groupId ?? undefined,+ groupId,metadata: { toolExecutionTimeMs: 0 },parentId: payload.parentMessageId,plugin: toolPayload as any,@@ -123,9 +133,9 @@ export const resolveBlockedTools =},pluginState: result.state,role: 'tool',- threadId: state.metadata?.threadId,+ threadId,tool_call_id: toolPayload.id,- topicId: state.metadata?.topicId,+ topicId,});toolMessageIds.push(toolMessage.id);} catch (error) {@@ -171,8 +181,18 @@ export const resolveAbortedTools =async (instruction, state) => {const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_aborted_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 events: AgentEvent[] = [];+ if (!agentId) {+ throw new Error(+ `[resolve_aborted_tools] Missing agentId for tool messages (op=${operation.operationId})`,+ );+ }+await transports.stream.publishEvent({data: {parentMessageId: payload.parentMessageId,@@ -188,16 +208,16 @@ export const resolveAbortedTools =for (const toolPayload of payload.toolsCalling) {try {await transports.messages.createToolMessage({- agentId: state.metadata!.agentId!,+ agentId,content: ABORTED_TOOL_CONTENT,- groupId: state.metadata?.groupId ?? undefined,+ groupId,parentId: payload.parentMessageId,plugin: toolPayload as any,pluginIntervention: { status: 'aborted' },role: 'tool',- threadId: state.metadata?.threadId,+ threadId,tool_call_id: toolPayload.id,- topicId: state.metadata?.topicId,+ topicId,});} catch (error) {await publishPersistError(host, error);diff --git a/packages/agent-runtime/src/transport/operation.ts b/packages/agent-runtime/src/transport/operation.tsindex eb9136c2e92..ad153ca1b91 100644--- a/packages/agent-runtime/src/transport/operation.ts+++ b/packages/agent-runtime/src/transport/operation.ts@@ -7,9 +7,13 @@ import type { AgentState } from '../types';* request; `stepIndex` advances per step.*/export interface RuntimeOperationContext {+ /** Effective message owner for this operation (group member when applicable). */+ agentId?: string;allowEarlyFinalAnswerVisibleOutputEnd?: boolean;+ groupId?: string;operationId: string;stepIndex: number;+ threadId?: string;topicId?: string;userId?: string;workspaceId?: string;diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.tsindex 18d0938532e..dafb1cadb99 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.ts@@ -31,7 +31,7 @@ describe('request_human_approve executor', () => {const state = createInitialState();// When- const result = await executeWithMockContext({+ await executeWithMockContext({executor: 'request_human_approve',instruction,state,@@ -150,12 +150,13 @@ describe('request_human_approve executor', () => {});// Then- expect(result.events).toHaveLength(1);- expect(result.events[0]).toMatchObject({- type: 'human_approve_required',- pendingToolsCalling: toolCalls,- operationId: 'test-session',- });+ expect(result.events).toContainEqual(+ expect.objectContaining({+ type: 'human_approve_required',+ pendingToolsCalling: toolCalls,+ operationId: context.operationId,+ }),+ );});});@@ -280,7 +281,9 @@ describe('request_human_approve executor', () => {// Thenexpect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();expect(result.newState.status).toBe('waiting_for_human');- expect(result.events).toHaveLength(1);+ expect(result.events).toContainEqual(+ expect.objectContaining({ type: 'human_approve_required' }),+ );});});@@ -443,7 +446,7 @@ describe('request_human_approve executor', () => {const context = createTestContext();const instruction = createRequestHumanApproveInstruction();const state = createInitialState({ status: 'running' });- const originalState = JSON.parse(JSON.stringify(state));+ const originalState = structuredClone(state);// Whenconst result = await executeWithMockContext({diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.tsindex be9826b311d..145846b2bfa 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.ts@@ -31,7 +31,7 @@ describe('resolve_aborted_tools executor', () => {const state = createInitialState({ operationId: 'test-session' });// When- const result = await executeWithMockContext({+ await executeWithMockContext({executor: 'resolve_aborted_tools',instruction,state,@@ -91,7 +91,7 @@ describe('resolve_aborted_tools executor', () => {const state = createInitialState();// When- const result = await executeWithMockContext({+ await executeWithMockContext({executor: 'resolve_aborted_tools',instruction,state,@@ -357,7 +357,13 @@ describe('resolve_aborted_tools executor', () => {// Thenexpect(result.newState.operationId).toBe(state.operationId);expect(result.newState.stepCount).toBe(state.stepCount);- expect(result.newState.messages).toEqual(state.messages);+ expect(result.newState.messages).toEqual([+ ...state.messages,+ expect.objectContaining({+ content: 'Tool execution was aborted by user.',+ role: 'tool',+ }),+ ]);expect(result.newState.usage).toEqual(state.usage);});@@ -367,7 +373,7 @@ describe('resolve_aborted_tools executor', () => {const context = createTestContext();const instruction = createResolveAbortedToolsInstruction();const state = createInitialState({ status: 'waiting_for_human' });- const originalState = JSON.parse(JSON.stringify(state));+ const originalState = structuredClone(state);// Whenconst result = await executeWithMockContext({@@ -480,7 +486,7 @@ describe('resolve_aborted_tools executor', () => {const state = createInitialState();// When- const result = await executeWithMockContext({+ await executeWithMockContext({executor: 'resolve_aborted_tools',instruction,state,@@ -529,7 +535,7 @@ describe('resolve_aborted_tools executor', () => {expect(result.newState.status).toBe('done');});- it('should handle failed message creation gracefully', async () => {+ it('should surface failed message creation', async () => {// Givenconst mockStore = createMockStore({optimisticCreateMessage: vi.fn().mockResolvedValue(null),@@ -538,18 +544,15 @@ describe('resolve_aborted_tools executor', () => {const instruction = createResolveAbortedToolsInstruction();const state = createInitialState();- // When- const result = await executeWithMockContext({- executor: 'resolve_aborted_tools',- instruction,- state,- mockStore,- context,- });-- // Then - should complete despite message creation failure- expect(result.newState.status).toBe('done');- expect(result.events).toHaveLength(1);+ await expect(+ executeWithMockContext({+ executor: 'resolve_aborted_tools',+ instruction,+ state,+ mockStore,+ context,+ }),+ ).rejects.toThrow('Failed to create tool message');});});diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex 1fc664adaa8..81071948d3a 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -7,6 +7,7 @@ import type {AgentInstructionExecSubAgent,AgentInstructionExecSubAgents,AgentRuntimeContext,+ AgentRuntimeHost,GeneralAgentCallingToolInstructionPayload,GeneralAgentCallLLMInstructionPayload,GeneralAgentCallLLMResultPayload,@@ -17,7 +18,12 @@ import type {SubAgentsBatchResultPayload,SubAgentTask,} from '@lobechat/agent-runtime';-import { UsageCounter } from '@lobechat/agent-runtime';+import {+ finish as createFinishExecutor,+ requestHumanApprove as createRequestHumanApproveExecutor,+ resolveAbortedTools as createResolveAbortedToolsExecutor,+ UsageCounter,+} from '@lobechat/agent-runtime';import { countContextTokens, type ToolsEngine } from '@lobechat/context-engine';import { chainCompressContext } from '@lobechat/prompts';import {@@ -45,6 +51,7 @@ import { getFileStoreState } from '@/store/file/store';import { sleep } from '@/utils/sleep';import { StreamingHandler } from './StreamingHandler';+import { buildClientRuntimeHost } from './transports/buildClientRuntimeHost';import { type StreamChunk } from './types/streaming';const log = debug('lobe-store:agent-executors');@@ -211,6 +218,18 @@ export const createAgentExecutors = (context: {return null;};+ const usePackageExecutor =+ (factory: (host: AgentRuntimeHost) => InstructionExecutor): InstructionExecutor =>+ (instruction, state, runtimeContext) =>+ factory(+ buildClientRuntimeHost({+ get: context.get,+ messageKey: context.messageKey,+ operationId: context.operationId,+ stepIndex: state.stepCount,+ }),+ )(instruction, state, runtimeContext);+const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {/*** Custom call_llm executor@@ -1115,207 +1134,11 @@ export const createAgentExecutors = (context: {}},- /** Create human approve executor */- request_human_approve: async (instruction, state) => {- const { pendingToolsCalling, reason, skipCreateToolMessage } = instruction as Extract<- AgentInstruction,- { type: 'request_human_approve' }- >;- const newState = structuredClone(state);- const events: AgentEvent[] = [];- const sessionLogId = `${state.operationId}:${state.stepCount}`;-- log(- '[%s][request_human_approve] Executor start, pending tools count: %d, reason: %s',- sessionLogId,- pendingToolsCalling.length,- reason || 'human_intervention_required',- );-- // Update state to waiting_for_human- newState.lastModified = new Date().toISOString();- newState.status = 'waiting_for_human';- newState.pendingToolsCalling = pendingToolsCalling;-- // Get assistant message to extract groupId and parentId- const latestMessages = context.get().dbMessagesMap[context.messageKey] || [];- const assistantMessage = latestMessages.findLast((m) => m.role === 'assistant');-- if (!assistantMessage) {- log('[%s][request_human_approve] ERROR: No assistant message found', sessionLogId);- throw new Error('No assistant message found for intervention');- }-- log(- '[%s][request_human_approve] Found assistant message: %s',- sessionLogId,- assistantMessage.id,- );-- if (skipCreateToolMessage) {- // Resumption mode: Tool messages already exist, just verify them- log('[%s][request_human_approve] Resuming with existing tool messages', sessionLogId);- } else {- // Get context from operation- const opContext = getOperationContext();- // Get effective agentId (subAgentId for group orchestration)- const effectiveAgentId = getEffectiveAgentId();-- // Create tool messages for each pending tool call with intervention status- await pMap(pendingToolsCalling, async (toolPayload) => {- const toolName = `${toolPayload.identifier}/${toolPayload.apiName}`;- log(- '[%s][request_human_approve] Creating tool message for %s with tool_call_id: %s',- sessionLogId,- toolName,- toolPayload.id,- );-- const toolMessageParams: CreateMessageParams = {- content: '',- groupId: assistantMessage.groupId,- parentId: assistantMessage.id,- plugin: {- ...toolPayload,- },- pluginIntervention: { status: 'pending' },- role: 'tool',- agentId: effectiveAgentId!,- threadId: opContext.threadId,- tool_call_id: toolPayload.id,- topicId: opContext.topicId ?? undefined,- };+ finish: usePackageExecutor(createFinishExecutor),- const createResult = await context- .get()- .optimisticCreateMessage(toolMessageParams, { operationId: context.operationId });+ request_human_approve: usePackageExecutor(createRequestHumanApproveExecutor),- if (!createResult) {- log(- '[%s][request_human_approve] ERROR: Failed to create tool message for %s',- sessionLogId,- toolName,- );- throw new Error(`Failed to create tool message for ${toolName}`);- }-- log(- '[%s][request_human_approve] Created tool message: %s for %s',- sessionLogId,- createResult.id,- toolName,- );- });- }-- log(- '[%s][request_human_approve] All tool messages created, emitting human_approve_required event',- sessionLogId,- );-- events.push({- operationId: newState.operationId,- pendingToolsCalling,- type: 'human_approve_required',- });-- return { events, newState };- },-- /**- * Resolve aborted tools executor- * Creates tool messages with 'aborted' intervention status for cancelled tools- */- resolve_aborted_tools: async (instruction, state) => {- const { parentMessageId, toolsCalling } = (- instruction as Extract<AgentInstruction, { type: 'resolve_aborted_tools' }>- ).payload;-- const events: AgentEvent[] = [];- const sessionLogId = `${state.operationId}:${state.stepCount}`;- const newState = structuredClone(state);-- log(- '[%s][resolve_aborted_tools] Resolving %d aborted tools',- sessionLogId,- toolsCalling.length,- );-- // Get context from operation- const opContext = getOperationContext();- // Get effective agentId (subAgentId for group orchestration)- const effectiveAgentId = getEffectiveAgentId();-- // Create tool messages for each aborted tool- await pMap(toolsCalling, async (toolPayload) => {- const toolName = `${toolPayload.identifier}/${toolPayload.apiName}`;- log(- '[%s][resolve_aborted_tools] Creating aborted tool message for %s',- sessionLogId,- toolName,- );-- const toolMessageParams: CreateMessageParams = {- content: 'Tool execution was aborted by user.',- groupId: opContext.groupId,- parentId: parentMessageId,- plugin: toolPayload,- pluginIntervention: { status: 'aborted' },- role: 'tool',- agentId: effectiveAgentId!,- threadId: opContext.threadId,- tool_call_id: toolPayload.id,- topicId: opContext.topicId ?? undefined,- };-- const createResult = await context- .get()- .optimisticCreateMessage(toolMessageParams, { operationId: context.operationId });-- if (createResult) {- log(- '[%s][resolve_aborted_tools] Created aborted tool message: %s for %s',- sessionLogId,- createResult.id,- toolName,- );- }- });-- log('[%s][resolve_aborted_tools] All aborted tool messages created', sessionLogId);-- // Mark state as done since we're finishing after abort- newState.lastModified = new Date().toISOString();- newState.status = 'done';-- events.push({- finalState: newState,- reason: 'user_aborted',- reasonDetail: 'User aborted operation with pending tool calls',- type: 'done',- });-- return { events, newState };- },-- /**- * Finish executor- * Completes the runtime execution- */- finish: async (instruction, state) => {- const { reason, reasonDetail } = instruction as Extract<AgentInstruction, { type: 'finish' }>;- const sessionLogId = `${state.operationId}:${state.stepCount}`;-- log(`[${sessionLogId}] Finishing execution: (%s)`, reason);-- const newState = structuredClone(state);- newState.lastModified = new Date().toISOString();- newState.status = 'done';-- const events: AgentEvent[] = [{ finalState: newState, reason, reasonDetail, type: 'done' }];-- return { events, newState };- },+ resolve_aborted_tools: usePackageExecutor(createResolveAbortedToolsExecutor),/*** exec_sub_agent executordiff --git a/src/store/chat/agents/transports/ClientMessageTransport.ts b/src/store/chat/agents/transports/ClientMessageTransport.tsnew file mode 100644index 00000000000..38307b7aa52--- /dev/null+++ b/src/store/chat/agents/transports/ClientMessageTransport.ts@@ -0,0 +1,93 @@+import type {+ MessageTransport,+ QueryMessagesInput,+ QueryMessagesOptions,+ RuntimeMessageRef,+ UpdateToolMessageInput,+} from '@lobechat/agent-runtime';+import type {+ ChatMessagePluginError,+ CreateMessageParams,+ UIChatMessage,+ UpdateMessageParams,+} from '@lobechat/types';++import { messageService } from '@/services/message';+import type { ChatStore } from '@/store/chat/store';++/** Client message adapter backed by the optimistic chat store. */+export class ClientMessageTransport implements MessageTransport {+ constructor(+ private readonly get: () => ChatStore,+ private readonly messageKey: string,+ private readonly operationId: string,+ ) {}++ createAssistantMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {+ return this.createMessage(params);+ }++ createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {+ return this.createMessage(params);+ }++ async deleteMessage(id: string): Promise<void> {+ await this.get().optimisticDeleteMessage(id, { operationId: this.operationId });+ }++ async findById(id: string): Promise<RuntimeMessageRef | undefined> {+ return this.getMessages().find((message) => message.id === id);+ }++ async query(+ _params?: QueryMessagesInput,+ _options?: QueryMessagesOptions,+ ): Promise<UIChatMessage[]> {+ return this.getMessages();+ }++ async update(id: string, params: Partial<UpdateMessageParams>): Promise<void> {+ const store = this.get();+ const optimisticContext = { operationId: this.operationId };++ store.internal_dispatchMessage(+ { id, type: 'updateMessage', value: params as Partial<UIChatMessage> },+ optimisticContext,+ );++ const conversationContext = store.internal_getConversationContext(optimisticContext);+ const result = await messageService.updateMessage(id, params, conversationContext);+ if (result?.success && result.messages) {+ store.replaceMessages(result.messages, { context: conversationContext });+ }+ }++ async updatePluginState(id: string, state: Record<string, any>): Promise<void> {+ await this.get().optimisticUpdatePluginState(id, state, { operationId: this.operationId });+ }++ async updateToolMessage(id: string, params: UpdateToolMessageInput): Promise<void> {+ await this.get().optimisticUpdateToolMessage(+ id,+ {+ ...params,+ pluginError: params.pluginError as ChatMessagePluginError | null | undefined,+ },+ { operationId: this.operationId },+ );+ }++ private async createMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {+ const result = await this.get().optimisticCreateMessage(params, {+ operationId: this.operationId,+ });++ if (!result) throw new Error(`Failed to create ${params.role} message`);++ return { ...params, id: result.id };+ }++ private getMessages(): UIChatMessage[] {+ return this.get().dbMessagesMap[this.messageKey] ?? [];+ }+}diff --git a/src/store/chat/agents/transports/buildClientRuntimeHost.ts b/src/store/chat/agents/transports/buildClientRuntimeHost.tsnew file mode 100644index 00000000000..61c6d28ff3e--- /dev/null+++ b/src/store/chat/agents/transports/buildClientRuntimeHost.ts@@ -0,0 +1,45 @@+import type { AgentRuntimeHost, OperationStore, StreamSink } from '@lobechat/agent-runtime';++import type { ChatStore } from '@/store/chat/store';++import { ClientMessageTransport } from './ClientMessageTransport';++const localOperationStore: OperationStore = {+ clearRunningMark: async () => {},+};++// Client runs consume returned AgentEvents directly. Transport stream output is+// only needed by remote server runs, where it is forwarded through Redis/SSE.+const localStreamSink: StreamSink = {+ publishChunk: async () => {},+ publishEvent: async () => {},+};++export const buildClientRuntimeHost = (context: {+ get: () => ChatStore;+ messageKey: string;+ operationId: string;+ stepIndex: number;+}): AgentRuntimeHost => {+ const runtimeOperation = context.get().operations[context.operationId];+ if (!runtimeOperation) throw new Error(`Operation not found: ${context.operationId}`);++ const { agentId, groupId, scope, subAgentId, threadId, topicId } = runtimeOperation.context;+ const effectiveAgentId = subAgentId && scope !== 'sub_agent' ? subAgentId : agentId;++ return {+ operation: {+ agentId: effectiveAgentId ?? undefined,+ groupId: groupId ?? undefined,+ operationId: context.operationId,+ stepIndex: context.stepIndex,+ threadId: threadId ?? undefined,+ topicId: topicId ?? undefined,+ },+ transports: {+ messages: new ClientMessageTransport(context.get, context.messageKey, context.operationId),+ operationStore: localOperationStore,+ stream: localStreamSink,+ },+ };+};