π€― 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
π fix(openapi): continue the run parked on the caller's function tools (#21010)
LiJiane973debcc3de
diff --git a/packages/openapi/src/services/__tests__/client-tool-resume.responses.test.ts b/packages/openapi/src/services/__tests__/client-tool-resume.responses.test.tsnew file mode 100644index 00000000000..763acf1a02c--- /dev/null+++ b/packages/openapi/src/services/__tests__/client-tool-resume.responses.test.ts@@ -0,0 +1,377 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ ClientToolResumeError,+ executeResponseRun,+ parkedOnToolsReason,+ pendingFunctionCallItems,+ resumeParkedClientTools,+} from '../client-tool-resume.responses';++const db = vi.hoisted(() => ({+ createMessage: vi.fn(),+ findOperation: vi.fn(),+ findTopic: vi.fn(),+ findToolMessageId: vi.fn(),+ releaseClaim: vi.fn(),+ tryResume: vi.fn(),+ updateToolMessage: vi.fn(),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: class {+ findById = db.findTopic;+ },+}));+vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: class {+ findById = db.findOperation;+ tryResumeFromAsyncTool = db.tryResume;+ },+}));+vi.mock('@/database/models/message', () => ({+ MessageModel: class {+ create = db.createMessage;+ findToolMessageIdByToolCallId = db.findToolMessageId;+ updateToolMessage = db.updateToolMessage;+ },+}));++const weatherCall = {+ apiName: 'get_weather',+ arguments: '{}',+ id: 'call_1',+ identifier: 'lobe-client-fn',+};+const subAgentCall = {+ apiName: 'callSubAgent',+ arguments: '{}',+ id: 'call_sub',+ identifier: 'lobe-agent',+};++const parkedState = () => ({+ messages: [+ { content: 'weather?', id: 'msg_user', role: 'user' },+ { content: '', id: 'msg_assistant', role: 'assistant', tool_calls: [{ id: 'call_1' }] },+ ],+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ pendingToolsCalling: [weatherCall],+ status: 'waiting_for_async_tool',+ stepCount: 2,+});++const runtime = (state: unknown = parkedState()) => {+ const executeStep = vi.fn();+ const executeSync = vi.fn();+ const tryResumeParentFromAsyncTool = vi.fn();+ return {+ executeStep,+ executeSync,+ tryResumeParentFromAsyncTool,+ getCoordinator: () => ({ loadAgentState: vi.fn().mockResolvedValue(state) }),+ };+};++const resume = (agentRuntimeService: unknown, outputs = [{ call_id: 'call_1', output: 'sunny' }]) =>+ resumeParkedClientTools({+ agentRuntimeService: agentRuntimeService as any,+ // Only the claim release writes through the db directly.+ db: { update: () => ({ set: () => ({ where: db.releaseClaim }) }) } as any,+ outputs: outputs.map((item) => ({ ...item, type: 'function_call_output' as const })),+ topicId: 'tpc_1',+ userId: 'user_1',+ });++describe('resumeParkedClientTools', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ db.findTopic.mockResolvedValue({+ metadata: { runningOperation: { operationId: 'op_parked' } },+ });+ db.findOperation.mockResolvedValue({+ agentId: 'agt_1',+ interruption: { reason: 'client_tool_execution' },+ status: 'waiting_for_async_tool',+ });+ db.findToolMessageId.mockResolvedValue(null);+ db.tryResume.mockResolvedValue(true);+ });++ it('answers the parked call with its output and claims the run', async () => {+ await expect(resume(runtime())).resolves.toEqual({+ callIds: ['call_1'],+ operationId: 'op_parked',+ });++ expect(db.createMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agt_1',+ content: 'sunny',+ parentId: 'msg_assistant',+ plugin: weatherCall,+ role: 'tool',+ tool_call_id: 'call_1',+ topicId: 'tpc_1',+ }),+ );+ expect(db.tryResume).toHaveBeenCalledWith('op_parked');+ // Claimed before anything is written, and kept: this request runs the resume.+ expect(db.tryResume.mock.invocationCallOrder[0]).toBeLessThan(+ db.createMessage.mock.invocationCallOrder[0],+ );+ expect(db.releaseClaim).not.toHaveBeenCalled();+ });++ // A parked state is saved without its messages.+ it('hangs the result off the last model call when the state has no messages', async () => {+ await resume(+ runtime({ ...parkedState(), messages: [], metadata: { workAssistantMessageId: 'msg_work' } }),+ );++ expect(db.createMessage).toHaveBeenCalledWith(+ expect.objectContaining({ parentId: 'msg_work' }),+ );+ });++ it('fills a result row that already exists instead of adding another', async () => {+ db.findToolMessageId.mockResolvedValue('msg_tool');++ await resume(runtime());++ expect(db.findToolMessageId).toHaveBeenCalledWith('call_1', 'msg_assistant');+ expect(db.updateToolMessage).toHaveBeenCalledWith('msg_tool', { content: 'sunny' });+ expect(db.createMessage).not.toHaveBeenCalled();+ });++ it('leaves topics without a run waiting on the caller to a new run', async () => {+ await expect(+ resume(runtime({ ...parkedState(), pendingToolsCalling: [subAgentCall] })),+ ).resolves.toBeUndefined();++ db.findOperation.mockResolvedValueOnce({ status: 'done' });+ await expect(resume(runtime())).resolves.toBeUndefined();++ db.findTopic.mockResolvedValueOnce({ metadata: {} });+ await expect(resume(runtime())).resolves.toBeUndefined();++ expect(db.createMessage).not.toHaveBeenCalled();+ expect(db.tryResume).not.toHaveBeenCalled();+ });++ it('rejects outputs that do not match the parked calls, before writing anything', async () => {+ await expect(resume(runtime(), [])).rejects.toThrow(+ new ClientToolResumeError('No tool output found for function call call_1.'),+ );+ await expect(+ resume(runtime(), [+ { call_id: 'call_1', output: 'sunny' },+ { call_id: 'call_x', output: '?' },+ ]),+ ).rejects.toThrow('No tool call found for function call output with call_id call_x.');++ expect(db.createMessage).not.toHaveBeenCalled();+ expect(db.tryResume).not.toHaveBeenCalled();+ });++ // Regression (review): a losing delivery wrote, or replaced, result rows+ // before it learned another one had already resumed the run.+ it('refuses a second delivery without writing anything', async () => {+ db.tryResume.mockResolvedValue(false);++ await expect(resume(runtime())).rejects.toThrow(ClientToolResumeError);+ expect(db.createMessage).not.toHaveBeenCalled();+ expect(db.updateToolMessage).not.toHaveBeenCalled();+ });++ it('hands the park back when writing a result fails', async () => {+ db.createMessage.mockRejectedValueOnce(new Error('db down'));++ await expect(resume(runtime())).rejects.toThrow('db down');+ expect(db.releaseClaim).toHaveBeenCalledTimes(1);+ });++ describe('a batch that also waits on server-side tools', () => {+ const mixed = () =>+ runtime({ ...parkedState(), pendingToolsCalling: [weatherCall, subAgentCall] });++ // Regression (review): such a park ("async_tool") was ignored, so the+ // outputs started a new run on the busy topic.+ it('saves the caller output and resumes once the other tools are done', async () => {+ const service = mixed();+ service.tryResumeParentFromAsyncTool.mockResolvedValue(true);++ await expect(resume(service)).resolves.toEqual({+ callIds: ['call_1'],+ operationId: 'op_parked',+ });+ expect(db.createMessage).toHaveBeenCalledTimes(1);+ expect(db.createMessage).toHaveBeenCalledWith(+ expect.objectContaining({ tool_call_id: 'call_1' }),+ );+ // Released to the runtime's barrier, which claimed it again for this request.+ expect(db.releaseClaim).toHaveBeenCalledTimes(1);+ expect(service.tryResumeParentFromAsyncTool).toHaveBeenCalledWith({+ parentOperationId: 'op_parked',+ });+ });++ it('holds the run for the other tools when they are still out', async () => {+ const service = mixed();+ service.tryResumeParentFromAsyncTool.mockResolvedValue(false);++ await expect(resume(service)).resolves.toEqual({+ callIds: ['call_1'],+ held: true,+ operationId: 'op_parked',+ });+ });++ it('does not take outputs for the server-side calls', async () => {+ await expect(+ resume(mixed(), [+ { call_id: 'call_1', output: 'sunny' },+ { call_id: 'call_sub', output: 'done' },+ ]),+ ).rejects.toThrow('No tool call found for function call output with call_id call_sub.');+ });+ });+});++describe('executeResponseRun', () => {+ it('takes the first step of a resumed run as the async-tool resume', async () => {+ const service = runtime();+ const nextContext = { phase: 'llm_result' };+ service.executeStep.mockResolvedValue({+ state: { status: 'running' },+ stepResult: { nextContext },+ });+ service.executeSync.mockResolvedValue({ status: 'done' });++ await expect(+ executeResponseRun(service as any, { operationId: 'op_parked', resumed: true }),+ ).resolves.toEqual({ status: 'done' });++ expect(service.executeStep).toHaveBeenCalledWith({+ operationId: 'op_parked',+ resumeAsyncTool: true,+ stepIndex: 2,+ });+ expect(service.executeSync).toHaveBeenCalledWith('op_parked', { initialContext: nextContext });+ });++ // Regression: the resumed non-streaming response came back with no output.+ it('returns the step state when the resume step already finished the run', async () => {+ const service = runtime();+ const answered = { messages: [{ content: 'sunny', role: 'assistant' }], status: 'done' };+ service.executeStep.mockResolvedValue({+ state: answered,+ stepResult: { nextContext: { phase: 'done' } },+ });++ await expect(+ executeResponseRun(service as any, { operationId: 'op_parked', resumed: true }),+ ).resolves.toBe(answered);+ expect(service.executeSync).not.toHaveBeenCalled();+ });++ // Regression: a resume reloads the conversation as display groups, which+ // produced no output at all; returning the whole group would also repeat the+ // answered call and make the caller run its tool again.+ it('returns only the turn after the answered calls', async () => {+ const service = runtime();+ service.executeStep.mockResolvedValue({+ state: {+ messages: [+ { content: 'weather?', id: 'msg_user', role: 'user' },+ {+ children: [+ { content: '', id: 'msg_call', tools: [{ apiName: 'get_weather', id: 'call_1' }] },+ { content: 'It is sunny.', id: 'msg_answer' },+ ],+ id: 'msg_call',+ role: 'assistantGroup',+ },+ ],+ status: 'done',+ },+ stepResult: {},+ });++ const state = await executeResponseRun(service as any, {+ callIds: ['call_1'],+ operationId: 'op_parked',+ resumed: true,+ });++ expect(state.messages).toEqual([+ { content: 'It is sunny.', id: 'msg_answer', role: 'assistant' },+ ]);+ });++ it('reports a held run as still waiting, without the calls it just answered', async () => {+ const service = runtime({ ...parkedState(), pendingToolsCalling: [weatherCall, subAgentCall] });++ const state = await executeResponseRun(service as any, {+ callIds: ['call_1'],+ held: true,+ operationId: 'op_parked',+ resumed: true,+ });++ expect(service.executeStep).not.toHaveBeenCalled();+ expect(state).toMatchObject({ messages: [], pendingToolsCalling: [subAgentCall] });+ });++ it('runs a new operation as before', async () => {+ const service = runtime();+ service.executeSync.mockResolvedValue({ status: 'done' });++ await executeResponseRun(service as any, { operationId: 'op_new' });++ expect(service.executeStep).not.toHaveBeenCalled();+ expect(service.executeSync).toHaveBeenCalledWith('op_new');+ });+});++describe('pendingFunctionCallItems', () => {+ // Regression: a non-streaming response parked on a client tool had no+ // function_call item, so the caller had no call_id to answer.+ it('lists the parked calls the output does not already carry', () => {+ // A server-side call of the same batch is not the caller's to answer.+ const state = { messages: [], pendingToolsCalling: [weatherCall, subAgentCall] } as any;++ expect(pendingFunctionCallItems(state, [], 'tpc_1')).toEqual([+ {+ arguments: '{}',+ call_id: 'call_1',+ id: 'fc_tpc_1_pending_0',+ name: 'get_weather',+ status: 'completed',+ type: 'function_call',+ },+ ]);+ expect(+ pendingFunctionCallItems(+ state,+ [{ call_id: 'call_1', type: 'function_call' } as any],+ 'tpc_1',+ ),+ ).toEqual([]);+ });+});++describe('parkedOnToolsReason', () => {+ it('names what a parked run waits on', () => {+ expect(parkedOnToolsReason({ status: 'waiting_for_async_tool' } as any)).toBe(+ 'client_tool_execution',+ );+ expect(+ parkedOnToolsReason({+ interruption: { reason: 'async_tool' },+ status: 'waiting_for_async_tool',+ } as any),+ ).toBe('async_tool');+ expect(parkedOnToolsReason({ status: 'done' } as any)).toBeUndefined();+ });+});diff --git a/packages/openapi/src/services/__tests__/responses.streaming.test.ts b/packages/openapi/src/services/__tests__/responses.streaming.test.tsindex 66ed3ab47ee..de119299d06 100644--- a/packages/openapi/src/services/__tests__/responses.streaming.test.ts+++ b/packages/openapi/src/services/__tests__/responses.streaming.test.ts@@ -1,13 +1,25 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-const { createStreamEventManagerMock, drainPushesMock, executeSyncMock, execAgentMock } = vi.hoisted(- () => ({- createStreamEventManagerMock: vi.fn(),- drainPushesMock: vi.fn(),- executeSyncMock: vi.fn(),- execAgentMock: vi.fn(),- }),-);+import { InMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';++import type * as ResumeModule from '../client-tool-resume.responses';+import { ResponsesService } from '../responses.service';++const {+ createStreamEventManagerMock,+ drainPushesMock,+ executeResponseRunMock,+ executeSyncMock,+ execAgentMock,+ resumeParkedClientToolsMock,+} = vi.hoisted(() => ({+ createStreamEventManagerMock: vi.fn(),+ drainPushesMock: vi.fn(),+ executeResponseRunMock: vi.fn(),+ executeSyncMock: vi.fn(),+ execAgentMock: vi.fn(),+ resumeParkedClientToolsMock: vi.fn(),+}));vi.mock('@/server/modules/AgentRuntime/factory', () => ({createStreamEventManager: createStreamEventManagerMock,@@ -22,6 +34,15 @@ vi.mock('@/server/services/aiAgent', () => ({execAgent = execAgentMock;},}));+vi.mock('../client-tool-resume.responses', async (importOriginal) => {+ const actual = await importOriginal<typeof ResumeModule>();+ executeResponseRunMock.mockImplementation(actual.executeResponseRun);+ return {+ ...actual,+ executeResponseRun: executeResponseRunMock,+ resumeParkedClientTools: resumeParkedClientToolsMock,+ };+});vi.mock('../../common/base.service', () => ({BaseService: class {db: any = null;@@ -32,10 +53,6 @@ vi.mock('../../common/base.service', () => ({},}));-import { InMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';--import { ResponsesService } from '../responses.service';-const buildService = () => new (ResponsesService as any)(null, 'user_1', { workspaceId: 'ws_1' });/** The private in-memory manager the service took from the factory. */@@ -127,3 +144,91 @@ describe('ResponsesService.createStreamingResponse', () => {expect(remainingSubscribers(subscribedManager(), 'op_1')).toBe(0);});});++describe('ResponsesService function call outputs', () => {+ const toolOutputRequest = {+ input: [{ call_id: 'call_1', output: 'sunny', type: 'function_call_output' as const }],+ model: 'agt_1',+ previous_response_id: 'tpc_1',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ createStreamEventManagerMock.mockReturnValue({ drainPushes: drainPushesMock });+ resumeParkedClientToolsMock.mockResolvedValue({ operationId: 'op_parked' });+ executeResponseRunMock.mockResolvedValue({ messages: [], status: 'done', stepCount: 3 });+ });++ // Regression: the outputs started a second run on the topic, which the parked+ // run still held, so every resume failed as "Topic β¦ remained busy".+ it('continues the run parked on the caller tools instead of starting another', async () => {+ const response = await buildService().createResponse(toolOutputRequest);++ expect(resumeParkedClientToolsMock).toHaveBeenCalledWith(+ expect.objectContaining({+ outputs: toolOutputRequest.input,+ topicId: 'tpc_1',+ userId: 'user_1',+ }),+ );+ expect(execAgentMock).not.toHaveBeenCalled();+ expect(executeResponseRunMock).toHaveBeenCalledWith(expect.anything(), {+ operationId: 'op_parked',+ resumed: true,+ topicId: 'tpc_1',+ });+ expect(response).toMatchObject({ id: 'tpc_1', status: 'completed' });+ });++ it('streams the resumed run on the same response id', async () => {+ const events: any[] = [];+ for await (const event of buildService().createStreamingResponse(toolOutputRequest)) {+ events.push(event);+ }++ expect(execAgentMock).not.toHaveBeenCalled();+ expect(events[0]).toMatchObject({ response: { id: 'tpc_1' }, type: 'response.created' });+ expect(events.at(-1)?.type).toBe('response.completed');+ expect(drainPushesMock).toHaveBeenCalledWith('op_parked');+ });++ it('returns the parked call to a non-streaming caller', async () => {+ resumeParkedClientToolsMock.mockResolvedValue(undefined);+ execAgentMock.mockResolvedValue({ operationId: 'op_new', success: true, topicId: 'tpc_2' });+ executeResponseRunMock.mockResolvedValue({+ interruption: { reason: 'client_tool_execution' },+ messages: [],+ pendingToolsCalling: [+ {+ apiName: 'get_weather',+ arguments: '{"city":"Hangzhou"}',+ id: 'call_9',+ identifier: 'lobe-client-fn',+ },+ ],+ status: 'waiting_for_async_tool',+ });++ const response = await buildService().createResponse({ input: 'weather?', model: 'agt_1' });++ expect(response).toMatchObject({+ incomplete_details: { reason: 'client_tool_execution' },+ output: [{ call_id: 'call_9', name: 'get_weather', type: 'function_call' }],+ status: 'incomplete',+ });+ });++ it('falls back to a new turn when nothing is parked on the topic', async () => {+ resumeParkedClientToolsMock.mockResolvedValue(undefined);+ execAgentMock.mockResolvedValue({ operationId: 'op_new', success: true, topicId: 'tpc_1' });++ await buildService().createResponse(toolOutputRequest);++ expect(execAgentMock).toHaveBeenCalledWith(+ expect.objectContaining({+ appContext: { topicId: 'tpc_1' },+ prompt: 'Tool call call_1 returned: sunny',+ }),+ );+ });+});diff --git a/packages/openapi/src/services/client-tool-resume.responses.ts b/packages/openapi/src/services/client-tool-resume.responses.tsnew file mode 100644index 00000000000..be959acf6b0--- /dev/null+++ b/packages/openapi/src/services/client-tool-resume.responses.ts@@ -0,0 +1,289 @@+import type { AgentState } from '@lobechat/agent-runtime';+import type { ChatToolPayload } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { MessageModel } from '@/database/models/message';+import { TopicModel } from '@/database/models/topic';+import { agentOperations } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import type { AgentRuntimeService } from '@/server/services/agentRuntime';++import type { FunctionCallOutputItem, OutputItem } from '../types/responses.type';++/**+ * A request the caller sent wrong: an output for a call nobody made, or a call+ * left without one. Surfaces as a failed response rather than a silent re-run.+ */+export class ClientToolResumeError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ClientToolResumeError';+ }+}++/**+ * The assistant message that issued `callId`, which its result row hangs off.+ * A parked state is usually saved without its messages; the last model call's+ * assistant (`workAssistantMessageId`) is then the one that made the calls.+ */+const findCallingAssistantId = (state: AgentState, callId: string): string | undefined => {+ for (const message of [...(state.messages ?? [])].reverse()) {+ if (message?.role !== 'assistant') continue;+ const calls = [...(message.tool_calls ?? []), ...(message.tools ?? [])];+ if (calls.some((call: { id?: string }) => call?.id === callId)) return message.id;+ }+ return state.metadata?.workAssistantMessageId;+};++interface ResumeParams {+ agentRuntimeService: AgentRuntimeService;+ db: LobeChatDatabase;+ outputs: FunctionCallOutputItem[];+ topicId: string;+ userId: string;+ workspaceId?: string;+}++/** Function tools the API caller supplied and runs itself (`lobe-client-fn____<name>`). */+const CALLER_TOOL_IDENTIFIER = 'lobe-client-fn';+const isCallerTool = (tool: ChatToolPayload) => tool.identifier === CALLER_TOOL_IDENTIFIER;++/** Hand a claimed park back, so whatever delivers the remaining results can resume it. */+const releaseClaim = (db: LobeChatDatabase, userId: string, operationId: string) =>+ db+ .update(agentOperations)+ .set({ status: 'waiting_for_async_tool' })+ .where(+ and(+ eq(agentOperations.id, operationId),+ eq(agentOperations.userId, userId),+ eq(agentOperations.status, 'running'),+ ),+ );++export interface ParkedClientToolsResume {+ /** The caller's calls these outputs answered. */+ callIds: string[];+ /**+ * The outputs are saved, but server-side tools from the same batch are still+ * running; their completion resumes the run, not this request.+ */+ held?: boolean;+ operationId: string;+}++/**+ * Hand the caller's `function_call_output` items to the run parked on this+ * topic and continue that same run, the way an OpenResponses client expects+ * `previous_response_id` + tool outputs to behave.+ *+ * The run parked itself (`waiting_for_async_tool`) when the model called one+ * of the caller's function tools, possibly in the same batch as server-side+ * deferred tools such as a sub-agent. Nothing else will ever deliver the+ * caller's results, and the run keeps the topic's `runningOperation` marker: a+ * new run on the topic is refused as busy, and the gateway's inactivity+ * watchdog eventually writes the parked turn off as abandoned.+ *+ * Claims the park, writes each output as the tool result of its call, and+ * returns the operation to resume β or `held` when other tools of the batch are+ * still out. Returns `undefined` when nothing on the topic waits on the+ * caller, so the caller can start a new run instead.+ */+export const resumeParkedClientTools = async ({+ agentRuntimeService,+ db,+ outputs,+ topicId,+ userId,+ workspaceId,+}: ResumeParams): Promise<ParkedClientToolsResume | undefined> => {+ const topic = await new TopicModel(db, userId, workspaceId).findById(topicId);+ const operationId = topic?.metadata?.runningOperation?.operationId;+ if (!operationId) return;++ const operationModel = new AgentOperationModel(db, userId, workspaceId);+ const operation = await operationModel.findById(operationId);+ if (operation?.status !== 'waiting_for_async_tool') return;++ const state = await agentRuntimeService.getCoordinator().loadAgentState(operationId);+ if (state?.status !== 'waiting_for_async_tool') return;++ const pending = (state.pendingToolsCalling ?? []) as ChatToolPayload[];+ const callerCalls = pending.filter(isCallerTool);+ if (callerCalls.length === 0) return;++ const outputByCallId = new Map(outputs.map((item) => [item.call_id, item.output]));+ for (const item of outputs) {+ if (!callerCalls.some((tool) => tool.id === item.call_id))+ throw new ClientToolResumeError(+ `No tool call found for function call output with call_id ${item.call_id}.`,+ );+ }+ for (const tool of callerCalls) {+ if (!outputByCallId.has(tool.id))+ throw new ClientToolResumeError(`No tool output found for function call ${tool.id}.`);+ }++ // Claim before writing: only one delivery may record results, so a racing+ // retry cannot add duplicate rows or replace the outputs the run resumes on.+ if (!(await operationModel.tryResumeFromAsyncTool(operationId)))+ throw new ClientToolResumeError('These function call outputs were already submitted.');++ const callIds = callerCalls.map((tool) => tool.id);+ try {+ const messageModel = new MessageModel(db, userId, workspaceId);+ const agentId = state.origin?.agentId ?? operation.agentId ?? undefined;+ for (const tool of callerCalls) {+ const content = outputByCallId.get(tool.id)!;+ const parentId = findCallingAssistantId(state, tool.id);+ const existingId = await messageModel.findToolMessageIdByToolCallId(tool.id, parentId);+ if (existingId) {+ await messageModel.updateToolMessage(existingId, { content });+ continue;+ }+ await messageModel.create({+ agentId,+ content,+ groupId: state.origin?.groupId ?? undefined,+ parentId,+ plugin: tool as any,+ role: 'tool',+ threadId: state.origin?.threadId ?? undefined,+ tool_call_id: tool.id,+ topicId,+ });+ }+ } catch (error) {+ await releaseClaim(db, userId, operationId);+ throw error;+ }++ if (callerCalls.length === pending.length) return { callIds, operationId };++ // Mixed batch: hand the park back to the runtime's completion barrier, which+ // resumes it once every tool of the batch has a result. If the other tools+ // already finished, the barrier passes now and this request runs the resume.+ await releaseClaim(db, userId, operationId);+ const resumed = await agentRuntimeService.tryResumeParentFromAsyncTool({+ parentOperationId: operationId,+ });+ return resumed ? { callIds, operationId } : { callIds, held: true, operationId };+};++/**+ * Narrow a resumed run's messages to the turn this response produced, in the+ * raw shape output items are built from. The resume reloads the conversation+ * from the database as display groups (`assistantGroup` with `children`), and+ * everything up to the answered calls was already returned by the response+ * that asked for them; returning those calls again would ask the caller to run+ * its tools a second time.+ */+const withResumedTurn = (state: AgentState, callIds: string[] = []): AgentState => {+ if (!state?.messages?.length) return state;++ const answered = new Set(callIds);+ const flat = state.messages.flatMap((message: any) =>+ message.role === 'assistantGroup'+ ? (message.children ?? []).map((child: any) => ({ ...child, role: 'assistant' }))+ : [message],+ );+ const callsOf = (message: any): { id?: string }[] => message.tool_calls ?? message.tools ?? [];+ const resumeIndex = flat.findLastIndex((message: any) =>+ callsOf(message).some((call) => !!call.id && answered.has(call.id)),+ );+ if (resumeIndex === -1) return state;++ const messages = flat.slice(resumeIndex + 1).map((message: any) =>+ message.tools+ ? {+ content: message.content,+ id: message.id,+ role: message.role,+ tool_calls: message.tools.map((tool: any) => ({+ function: { arguments: tool.arguments, name: `${tool.identifier}____${tool.apiName}` },+ id: tool.id,+ type: 'function',+ })),+ }+ : message,+ );+ return { ...state, messages };+};++/**+ * Run an operation to its next stop. A resumed park takes its first step as+ * the async-tool resume (refresh the tool results, re-enter the model); the+ * rest is the ordinary synchronous loop.+ */+export const executeResponseRun = async (+ agentRuntimeService: AgentRuntimeService,+ run: { callIds?: string[]; held?: boolean; operationId: string; resumed?: boolean },+): Promise<AgentState> => {+ if (!run.resumed) return agentRuntimeService.executeSync(run.operationId);++ const state = await agentRuntimeService.getCoordinator().loadAgentState(run.operationId);+ // Still parked on the batch's other tools: report the wait, without the calls+ // this request just answered.+ if (run.held && state) {+ const answered = new Set(run.callIds);+ return {+ ...state,+ messages: [],+ pendingToolsCalling: (state.pendingToolsCalling ?? []).filter(+ (tool: ChatToolPayload) => !answered.has(tool.id),+ ),+ };+ }++ const first = await agentRuntimeService.executeStep({+ operationId: run.operationId,+ resumeAsyncTool: true,+ stepIndex: state?.stepCount ?? 0,+ });+ // Stopped already (answered, or parked again): nothing is left to run, and+ // executeSync would hand back the saved state rather than this step's.+ const nextContext = first.stepResult?.nextContext;+ if (!nextContext || first.state?.status !== 'running')+ return withResumedTurn(first.state as AgentState, run.callIds);++ const final = await agentRuntimeService.executeSync(run.operationId, {+ initialContext: nextContext,+ });+ return withResumedTurn(final, run.callIds);+};++/**+ * The caller's function calls a run parked on, as output items it can answer.+ * A parked state is saved without its messages, so the calls cannot be read+ * back from them; without these items a non-streaming caller gets an+ * `incomplete` response with no `call_id` to send outputs for.+ */+export const pendingFunctionCallItems = (+ state: AgentState,+ output: OutputItem[],+ responseId: string,+): OutputItem[] => {+ const listed = new Set(output.map((item) => (item as { call_id?: string }).call_id));+ return ((state.pendingToolsCalling ?? []) as ChatToolPayload[])+ .filter((tool) => isCallerTool(tool) && !listed.has(tool.id))+ .map((tool, index) => ({+ arguments: tool.arguments || '{}',+ call_id: tool.id,+ id: `fc_${responseId}_pending_${index}`,+ name: tool.apiName,+ status: 'completed' as const,+ type: 'function_call' as const,+ }));+};++/**+ * Why the run stopped short of an answer, when it is parked on tools: the+ * caller's (`client_tool_execution`), or a batch that also waits on+ * server-side tools (`async_tool`). Such a response is `incomplete`, never+ * `completed`.+ */+export const parkedOnToolsReason = (state?: AgentState): string | undefined =>+ state?.status === 'waiting_for_async_tool'+ ? (state.interruption?.reason ?? 'client_tool_execution')+ : undefined;diff --git a/packages/openapi/src/services/responses.service.ts b/packages/openapi/src/services/responses.service.tsindex a836fb02297..19a7c46f992 100644--- a/packages/openapi/src/services/responses.service.ts+++ b/packages/openapi/src/services/responses.service.ts@@ -20,6 +20,12 @@ import type {ResponseUsage,Tool,} from '../types/responses.type';+import {+ executeResponseRun,+ parkedOnToolsReason,+ pendingFunctionCallItems,+ resumeParkedClientTools,+} from './client-tool-resume.responses';/*** Response API Service@@ -256,6 +262,72 @@ export class ResponsesService extends BaseService {};}+ /**+ * Start the run a request asks for. Function call outputs for a run parked on+ * the caller's tools resume that same run; anything else creates a new+ * operation (model field = agent id) without auto-start.+ */+ private async startRun(+ params: CreateResponseRequest,+ options: { agentRuntimeService: AgentRuntimeService; stream: boolean },+ ): Promise<{ operationId: string; resumed?: boolean; topicId?: string }> {+ // Resolve topicId from previous_response_id for multi-turn+ const previousTopicId = params.previous_response_id+ ? this.extractTopicIdFromResponseId(params.previous_response_id)+ : null;+ const functionCallOutputs = this.extractFunctionCallOutputs(params.input);+ const isResumeFlow = functionCallOutputs.length > 0 && !!previousTopicId;++ if (isResumeFlow) {+ const resumed = await resumeParkedClientTools({+ agentRuntimeService: options.agentRuntimeService,+ db: this.db,+ outputs: functionCallOutputs,+ topicId: previousTopicId,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ if (resumed) return { ...resumed, resumed: true, topicId: previousTopicId };+ }++ const instructions = this.buildInstructions(params);+ // No parked run to hand the outputs to: they become the next turn's prompt.+ const prompt = isResumeFlow+ ? this.buildToolResultPrompt(functionCallOutputs)+ : this.extractPrompt(params.input);++ this.log('info', 'Creating response via execAgent', {+ hasInstructions: !!instructions,+ isResumeFlow,+ model: params.model,+ previousTopicId,+ prompt: prompt.slice(0, 50),+ });++ const additionalPluginIds = this.extractHostedToolIds(params.tools);+ const functionTools = this.extractFunctionTools(params.tools);+ const aiAgentService = new AiAgentService(this.db, this.userId, {+ workspaceId: this.workspaceId,+ });+ const execResult = await aiAgentService.execAgent({+ additionalPluginIds: additionalPluginIds.length > 0 ? additionalPluginIds : undefined,+ agentId: params.model,+ appContext: previousTopicId ? { topicId: previousTopicId } : undefined,+ autoStart: false,+ functionTools: functionTools.length > 0 ? functionTools : undefined,+ instructions,+ prompt,+ stream: options.stream,+ trigger: 'openapi',+ });++ if (!execResult.success) {+ throw new Error(execResult.error || 'Failed to create agent operation');+ }++ return { operationId: execResult.operationId, topicId: execResult.topicId };+ }+/*** Create a response (non-streaming)* Calls execAgent with autoStart: false, then executeSync to wait for completion@@ -264,76 +336,32 @@ export class ResponsesService extends BaseService {const createdAt = Math.floor(Date.now() / 1000);try {- const model = params.model;- const instructions = this.buildInstructions(params);-- // Resolve topicId from previous_response_id for multi-turn- const previousTopicId = params.previous_response_id- ? this.extractTopicIdFromResponseId(params.previous_response_id)- : null;-- // Check for function_call_output resume flow- const functionCallOutputs = this.extractFunctionCallOutputs(params.input);- const isResumeFlow = functionCallOutputs.length > 0 && previousTopicId;-- const prompt = isResumeFlow- ? this.buildToolResultPrompt(functionCallOutputs)- : this.extractPrompt(params.input);-- this.log('info', 'Creating response via execAgent', {- hasInstructions: !!instructions,- isResumeFlow,- model,- previousTopicId,- prompt: prompt.slice(0, 50),- });-- // 1. Create agent operation without auto-start- // model field is used as agentId- const additionalPluginIds = this.extractHostedToolIds(params.tools);- const functionTools = this.extractFunctionTools(params.tools);- const aiAgentService = new AiAgentService(this.db, this.userId, {+ const agentRuntimeService = new AgentRuntimeService(this.db, this.userId, {+ queueService: null,workspaceId: this.workspaceId,});- const execResult = await aiAgentService.execAgent({- additionalPluginIds: additionalPluginIds.length > 0 ? additionalPluginIds : undefined,- agentId: model,- appContext: previousTopicId ? { topicId: previousTopicId } : undefined,- autoStart: false,- functionTools: functionTools.length > 0 ? functionTools : undefined,- instructions,- prompt,- stream: false,- trigger: 'openapi',- });-- if (!execResult.success) {- throw new Error(execResult.error || 'Failed to create agent operation');- }+ const run = await this.startRun(params, { agentRuntimeService, stream: false });// Generate response ID encoding topicId for multi-turn support- const responseId = this.generateResponseId(execResult.topicId);+ const responseId = this.generateResponseId(run.topicId);// 2. Execute synchronously to completion- const agentRuntimeService = new AgentRuntimeService(this.db, this.userId, {- queueService: null,- workspaceId: this.workspaceId,- });- const finalState = await agentRuntimeService.executeSync(execResult.operationId);+ const finalState = await executeResponseRun(agentRuntimeService, run);// 3. Extract results from final stateconst { output, outputText } = this.extractOutputItems(finalState, responseId);const usage = this.extractUsage(finalState);- const isClientToolInterrupt =- finalState.status === 'waiting_for_async_tool' &&- finalState.interruption?.reason === 'client_tool_execution';+ const parkedReason = parkedOnToolsReason(finalState);+ const isClientToolInterrupt = !!parkedReason;+ if (isClientToolInterrupt)+ output.push(...pendingFunctionCallItems(finalState, output, responseId));return this.buildResponseObject({completedAt: isClientToolInterrupt ? null : Math.floor(Date.now() / 1000),createdAt,id: responseId,- incompleteDetails: isClientToolInterrupt ? { reason: 'client_tool_execution' } : undefined,+ incompleteDetails: parkedReason ? { reason: parkedReason } : undefined,output,outputText,params,@@ -377,73 +405,13 @@ export class ResponsesService extends BaseService {let releaseStream: (() => Promise<void>) | undefined;try {- const model = params.model;- const instructions = this.buildInstructions(params);-- // Resolve topicId from previous_response_id for multi-turn- const previousTopicId = params.previous_response_id- ? this.extractTopicIdFromResponseId(params.previous_response_id)- : null;-- // Check for function_call_output resume flow- const functionCallOutputs = this.extractFunctionCallOutputs(params.input);- const isResumeFlow = functionCallOutputs.length > 0 && previousTopicId;-- const prompt = isResumeFlow- ? this.buildToolResultPrompt(functionCallOutputs)- : this.extractPrompt(params.input);-- // 1. Create agent operation (before generating responseId so we have topicId)- // model field is used as agentId- const additionalPluginIds = this.extractHostedToolIds(params.tools);- const functionTools = this.extractFunctionTools(params.tools);- const aiAgentService = new AiAgentService(this.db, this.userId, {- workspaceId: this.workspaceId,- });- const execResult = await aiAgentService.execAgent({- additionalPluginIds: additionalPluginIds.length > 0 ? additionalPluginIds : undefined,- agentId: model,- appContext: previousTopicId ? { topicId: previousTopicId } : undefined,- autoStart: false,- functionTools: functionTools.length > 0 ? functionTools : undefined,- instructions,- prompt,- stream: true,- trigger: 'openapi',- });-- if (!execResult.success) {- throw new Error(execResult.error || 'Failed to create agent operation');- }-- const operationId = execResult.operationId;-- // Generate response ID encoding topicId for multi-turn support- const responseId = this.generateResponseId(execResult.topicId);-- const response = this.buildResponseObject({- createdAt,- id: responseId,- output: [],- outputText: '',- params,- status: 'in_progress',- });-- // Emit response.created + response.in_progress- yield { response, sequence_number: sequenceNumber++, type: 'response.created' as const };- yield {- response,- sequence_number: sequenceNumber++,- type: 'response.in_progress' as const,- };-- // 2. Run the operation on the gateway-aware stream pipeline, with this+ // 1. Run the operation on the gateway-aware stream pipeline, with this// generator's own subscription on a private in-memory manager.//- // `execAgent` above already registered this operation with the- // agent-gateway Durable Object (`publishAgentRuntimeInit`), and that DO- // only closes the session on an `agent_runtime_end`. Executing on a+ // `execAgent` registers a new operation with the agent-gateway Durable+ // Object (`publishAgentRuntimeInit`), and a run parked on client tools is+ // still registered there; that DO only closes the session on an+ // `agent_runtime_end`. Executing on a// manager nothing mirrors leaves the DO holding a run that finished long// ago as `running`, so its inactivity watchdog abandons the operation// ~10 minutes later β writing an `Operation abandoned: inactivity_watchdog`@@ -472,6 +440,30 @@ export class ResponsesService extends BaseService {workspaceId: this.workspaceId,});+ // 2. Start the run (before generating responseId so we have topicId)+ const run = await this.startRun(params, { agentRuntimeService, stream: true });+ const operationId = run.operationId;++ // Generate response ID encoding topicId for multi-turn support+ const responseId = this.generateResponseId(run.topicId);++ const response = this.buildResponseObject({+ createdAt,+ id: responseId,+ output: [],+ outputText: '',+ params,+ status: 'in_progress',+ });++ // Emit response.created + response.in_progress+ yield { response, sequence_number: sequenceNumber++, type: 'response.created' as const };+ yield {+ response,+ sequence_number: sequenceNumber++,+ type: 'response.in_progress' as const,+ };+// 3. Setup async event queue to bridge push events β pull-based generatorconst eventQueue: StreamEvent[] = [];let resolveWaiting: (() => void) | null = null;@@ -508,8 +500,7 @@ export class ResponsesService extends BaseService {// 4. Start execution in backgroundlet finalState: AgentState | undefined;- const executionPromise = agentRuntimeService- .executeSync(operationId)+ const executionPromise = executeResponseRun(agentRuntimeService, run).then((state) => {finalState = state;})@@ -797,17 +788,16 @@ export class ResponsesService extends BaseService {? this.extractOutputItems(finalState, responseId): { output: [], outputText: accumulatedText };- // Determine if agent was interrupted for client tool execution- const isClientToolInterrupt =- finalState?.status === 'waiting_for_async_tool' &&- finalState?.interruption?.reason === 'client_tool_execution';+ // Determine if the agent stopped to wait on tools (the caller's, or a mixed batch)+ const parkedReason = parkedOnToolsReason(finalState);+ const isClientToolInterrupt = !!parkedReason;if (isClientToolInterrupt) {yield {response: {...response,completed_at: null,- incomplete_details: { reason: 'client_tool_execution' },+ incomplete_details: { reason: parkedReason },output: fullOutput.output,output_text: fullOutput.outputText || accumulatedText,status: 'incomplete' as any,