🤯 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): split AgentRuntimeService and its tests into files under 800 lines (#21100)
Arvin Xu8c894209ff28
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.mdindex 42d6ac4ad70..797f6b153b0 100644--- a/.agents/skills/agent-runtime-hooks/SKILL.md+++ b/.agents/skills/agent-runtime-hooks/SKILL.md@@ -50,18 +50,18 @@ execAgent({ hooks })## Key Files-| File | Role |-| ---------------------------------------------------------------------- | --------------------------------------------------------- |-| `packages/agent-runtime/src/types/hooks.ts` | Event types and required/optional fields |-| `apps/server/src/services/agentRuntime/hooks/types.ts` | Registration and webhook types |-| `apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts` | Registration, dispatch, local mocks, HTTP/QStash delivery |-| `apps/server/src/services/agentRuntime/hooks/webhookPayload.ts` | Event projection and email enrichment |-| `apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.ts` | Shared tool-event context builder |-| `apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts` | Tool notifications and execution results |-| `apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts` | Tool, compression and human-intervention execution |-| `apps/server/src/services/agentRuntime/AgentRuntimeService.ts` | Step events and human-intervention continuation |-| `apps/server/src/services/agentRuntime/CompletionLifecycle.ts` | Terminal events |-| `apps/server/src/services/aiAgent/subAgentRuns.ts` | Sub-agent events |+| File | Role |+| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------- |+| `packages/agent-runtime/src/types/hooks.ts` | Event types and required/optional fields |+| `apps/server/src/services/agentRuntime/hooks/types.ts` | Registration and webhook types |+| `apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts` | Registration, dispatch, local mocks, HTTP/QStash delivery |+| `apps/server/src/services/agentRuntime/hooks/webhookPayload.ts` | Event projection and email enrichment |+| `apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.ts` | Shared tool-event context builder |+| `apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts` | Tool notifications and execution results |+| `apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts` | Tool, compression and human-intervention execution |+| `apps/server/src/services/agentRuntime/AgentRuntimeService/` (`executeStep/`, `intervention.ts`) | Step events and human-intervention continuation |+| `apps/server/src/services/agentRuntime/CompletionLifecycle.ts` | Terminal events |+| `apps/server/src/services/aiAgent/subAgentRuns.ts` | Sub-agent events |## Registrationdiff --git a/.agents/skills/agent-tracing/SKILL.md b/.agents/skills/agent-tracing/SKILL.mdindex f4c3a8ef4f7..9b4d343943f 100644--- a/.agents/skills/agent-tracing/SKILL.md+++ b/.agents/skills/agent-tracing/SKILL.md@@ -272,7 +272,7 @@ says which basis is in use. Analysis lives in `analysis/contextMap.ts` and is ex| `--step <n>` | `-s` | Target a specific step | — || `--messages` | `-m` | Messages context (CE input → params → LLM payload) | — || `--tools` | `-t` | Tool calls & results (what agent invoked) | — |-| `--events` | `-e` | Raw events (llm\_start, llm\_result, etc.) | — |+| `--events` | `-e` | Raw events (llm_start, llm_result, etc.) | — || `--context` | `-c` | Runtime context & payload (raw) | — || `--system-role` | `-r` | Full system role content | 0 || `--env` | | Environment context | 0 |@@ -372,6 +372,6 @@ When using `--messages`, the output shows three sections (if context engine data## Integration Points-- **Recording**: `apps/server/src/services/agentRuntime/AgentRuntimeService.ts` — in the `executeStep()` method, after building `stepPresentationData`, writes partial snapshot in dev mode+- **Recording**: `apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts` — in `executeStep()`, after `saveAndPublishStep` builds `stepPresentationData`, writes partial snapshot in dev mode- **Context engine capture**: `apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts` — in `call_llm` executor, after `serverMessagesEngine()` returns, calls `ctx.tracingContextEngine(input, output, metadata)`. `AgentRuntimeService.executeStep` buffers it per step and passes it to `traceRecorder.appendStep` as the typed `contextEngine` field (kept off the `events` array to stay out of Redis state).- **Store**: `FileSnapshotStore` reads/writes to `.agent-tracing/` relative to `process.cwd()`diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsdeleted file mode 100644index f4de15b5849..00000000000--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ /dev/null@@ -1,4579 +0,0 @@-/**- * @vitest-environment node- */-import { getModelPropertyWithFallback } from '@lobechat/model-runtime';-import type { UIChatMessage } from '@lobechat/types';-import type * as ModelBankModule from 'model-bank';-import type { MockInstance } from 'vitest';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { AgentOperationModel } from '@/database/models/agentOperation';--import { AgentRuntimeService, createEvalToolForwardingHook } from './AgentRuntimeService';-import { hookDispatcher } from './hooks';-import {- type AgentExecutionParams,- type OperationCreationParams,- type StartExecutionParams,-} from './types';--vi.mock('@lobechat/model-runtime', () => ({- // RuntimeExecutors (loaded transitively) resolves extend params via this- // helper; an empty result keeps the runtime payload unchanged.- applyModelExtendParams: vi.fn(function () {- return {};- }),- getModelPropertyWithFallback: vi.fn(),- // `llmErrorClassification.ts` reads these at module-load time; an empty- // spec map is fine here because this suite never exercises the runtime- // retry classifier path.- ERROR_CODE_SPECS: {},- getErrorCodeSpec: () => undefined,- refineErrorCode: () => undefined,-}));--const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));-vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));--// Mock trusted client to avoid server-side env access-vi.mock('@/libs/trusted-client', () => ({- generateTrustedClientToken: vi.fn().mockReturnValue(undefined),- getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),- isTrustedClientEnabled: vi.fn().mockReturnValue(false),-}));--// Mock database and models-vi.mock('@/server/services/file', () => ({- FileService: vi.fn().mockImplementation(function () {- return {- getFullFileUrl: vi.fn(async (path: string) => `model:${path}`),- getFileAccessUrl: vi.fn(async (file: { id: string }) => `ui:${file.id}`),- };- }),-}));--vi.mock('@/database/models/message', () => ({- MessageModel: vi.fn().mockImplementation(function () {- return {- findById: vi.fn().mockResolvedValue(undefined),- findMessagePlugin: vi.fn().mockResolvedValue(undefined),- query: vi.fn().mockResolvedValue([]),- };- }),-}));--vi.mock('@/database/models/agent', () => ({- AgentModel: vi.fn().mockImplementation(function () {- return {- getAgentConfigById: vi.fn(),- };- }),-}));--vi.mock('@/database/models/plugin', () => ({- PluginModel: vi.fn().mockImplementation(function () {- return {- query: vi.fn().mockResolvedValue([]),- };- }),-}));--// Mock ModelRuntime to avoid server-side env access-vi.mock('@/server/modules/ModelRuntime', () => ({- initializeRuntimeOptions: vi.fn(),- ApiKeyManager: vi.fn().mockImplementation(function () {- return {- getApiKey: vi.fn(),- getAllApiKeys: vi.fn(),- };- }),-}));--// Mock search service to avoid server-side env access-vi.mock('@/server/services/search', () => ({- SearchService: vi.fn().mockImplementation(function () {- return {- search: vi.fn(),- };- }),- searchService: {- search: vi.fn(),- },-}));--// Mock factory and redis dependencies to break env import chains,-// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends-vi.mock('@/server/modules/AgentRuntime/factory', async () => {- const { InMemoryAgentStateManager } =- await import('@/server/modules/AgentRuntime/InMemoryAgentStateManager');- const { InMemoryStreamEventManager } =- await import('@/server/modules/AgentRuntime/InMemoryStreamEventManager');- return {- createAgentStateManager: () => new InMemoryAgentStateManager(),- createStreamEventManager: () => new InMemoryStreamEventManager(),- isRedisAvailable: () => false,- };-});--vi.mock('@/server/modules/AgentRuntime/redis', () => ({- createAgentRuntimeRedisClient: vi.fn().mockReturnValue(null),- getAgentRuntimeRedisClient: vi.fn().mockReturnValue(null),-}));--// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports-vi.mock('@/server/modules/AgentRuntime', async (importOriginal) => {- const actual = await importOriginal<Record<string, unknown>>();- return {- ...actual,- createRuntimeExecutors: vi.fn(),- };-});--// Spread the real module and override only `AgentRuntime` (to stub `.step()`).-// Keeps the real status predicates + package-hosted executors (e.g. `finish`),-// so this mock survives future executor migrations without edits.-vi.mock('@lobechat/agent-runtime', async (importOriginal) => ({- ...((await importOriginal()) as Record<string, unknown>),- AgentRuntime: vi.fn().mockImplementation(function (_agent, _options) {- return {- step: vi.fn(),- };- }),-}));--vi.mock('@/server/services/queue', () => ({- QueueService: vi.fn().mockImplementation(function () {- return {- getImpl: vi.fn().mockReturnValue(null),- scheduleMessage: vi.fn(),- };- }),-}));--// Mock Mecha module-vi.mock('@/server/modules/Mecha', () => ({- createServerAgentToolsEngine: vi.fn().mockReturnValue({- generateToolsDetailed: vi.fn().mockReturnValue({- tools: [],- enabledToolIds: [],- filteredTools: [],- }),- getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),- }),- serverMessagesEngine: vi.fn().mockResolvedValue([]),-}));--// Mock model-bank-vi.mock('model-bank', async (importOriginal) => {- const actual = await importOriginal<typeof ModelBankModule>();- return {- ...actual,- LOBE_DEFAULT_MODEL_LIST: [- {- id: 'gpt-4o-mini',- providerId: 'openai',- abilities: {- functionCall: true,- vision: true,- video: false,- },- },- ],- };-});--describe('AgentRuntimeService', () => {- let service: AgentRuntimeService;- let mockCoordinator: any;- let mockStreamManager: any;- let mockQueueService: any;- let mockDb: any;- const mockUserId = 'test-user-id';-- const buildPersistedToolChain = (- finalContent: string,- finalMetadata?: Record<string, unknown>,- ): UIChatMessage[] => [- {- content: 'question',- createdAt: 1,- id: 'user-1',- role: 'user',- updatedAt: 1,- },- {- content: '',- createdAt: 2,- id: 'assistant-tools',- parentId: 'user-1',- role: 'assistant',- tools: [- {- apiName: 'command_execution',- arguments: '{}',- id: 'tool-call-1',- identifier: 'codex',- result_msg_id: 'tool-result-1',- type: 'default',- },- ],- updatedAt: 2,- },- {- content: 'tool result',- createdAt: 3,- id: 'tool-result-1',- parentId: 'assistant-tools',- role: 'tool',- tool_call_id: 'tool-call-1',- updatedAt: 3,- },- {- content: finalContent,- createdAt: 4,- id: 'assistant-final',- metadata: finalMetadata,- parentId: 'tool-result-1',- role: 'assistant',- updatedAt: 4,- },- ];-- beforeEach(() => {- vi.clearAllMocks();- process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';-- // Mock database- mockDb = {- select: vi.fn(),- insert: vi.fn(),- update: vi.fn(),- delete: vi.fn(),- };-- service = new AgentRuntimeService(mockDb, mockUserId);-- // Get real instances (backed by InMemory implementations)- mockCoordinator = (service as any).coordinator;- mockStreamManager = (service as any).streamManager;- mockQueueService = (service as any).queueService;-- // Auto-spy all coordinator methods so tests can use .mockResolvedValue() / .toHaveBeenCalledWith()- for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(mockCoordinator))) {- if (key !== 'constructor' && typeof mockCoordinator[key] === 'function') {- vi.spyOn(mockCoordinator, key);- }- }- // Auto-spy all streamManager methods- for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(mockStreamManager))) {- if (key !== 'constructor' && typeof mockStreamManager[key] === 'function') {- vi.spyOn(mockStreamManager, key);- }- }- });-- afterEach(() => {- vi.unstubAllEnvs();- delete process.env.AGENT_RUNTIME_BASE_URL;- hookDispatcher.unregister('test-operation-1');- });-- describe('eval tool forwarding hook', () => {- const event = {- apiName: 'search_tweets',- args: { query: 'test' },- callIndex: 2,- identifier: 'twitter',- mock: vi.fn(),- operationId: 'op-forwarding',- stepIndex: 3,- };-- beforeEach(() => {- event.mock.mockReset();- mockSsrfSafeFetch.mockReset();- });-- it('forwards the beforeToolCall payload and preserves the returned tool result', async () => {- const timeoutSpy = vi.spyOn(global, 'setTimeout');- const result = { content: 'fixture result', state: { source: 'mock' }, success: true };- mockSsrfSafeFetch.mockResolvedValue(- new Response(JSON.stringify({ data: result, success: true })),- );- const hook = createEvalToolForwardingHook({- twitter: { endpoint: 'https://mock.test/tool-calls' },- });-- await hook.handler!(event as any);-- expect(mockSsrfSafeFetch).toHaveBeenCalledWith(- 'https://mock.test/tool-calls',- expect.objectContaining({ method: 'POST' }),- );- expect(JSON.parse(mockSsrfSafeFetch.mock.calls[0][1].body)).toEqual({- data: { apiName: 'search_tweets', args: { query: 'test' }, identifier: 'twitter' },- metadata: { callIndex: 2, operationId: 'op-forwarding', stepIndex: 3 },- type: 'toolCall',- });- expect(timeoutSpy).toHaveBeenCalledWith(expect.any(Function), 15_000);- expect(event.mock).toHaveBeenCalledWith(result);- timeoutSpy.mockRestore();- });-- it('includes the dataset case id in forwarding metadata', async () => {- const result = { content: 'fixture result', success: true };- mockSsrfSafeFetch.mockResolvedValue(- new Response(JSON.stringify({ data: result, success: true })),- );- const hook = createEvalToolForwardingHook(- { twitter: { endpoint: 'https://mock.test/tool-calls' } },- 'case-42',- );-- await hook.handler!(event as any);-- expect(JSON.parse(mockSsrfSafeFetch.mock.calls[0][1].body)).toMatchObject({- metadata: { caseId: 'case-42' },- });- });-- it('mocks a failed result without executing the real tool', async () => {- mockSsrfSafeFetch.mockResolvedValue(- new Response(JSON.stringify({ error: 'fixture unavailable', success: false })),- );- const hook = createEvalToolForwardingHook({- twitter: { endpoint: 'https://mock.test/tool-calls' },- });-- await hook.handler!(event as any);-- expect(event.mock).toHaveBeenCalledWith({- content: 'fixture unavailable',- error: 'fixture unavailable',- success: false,- });- });-- it('mocks a placeholder when a successful response has no tool result', async () => {- mockSsrfSafeFetch.mockResolvedValue(new Response(JSON.stringify({ success: true })));- const hook = createEvalToolForwardingHook({- twitter: { endpoint: 'https://mock.test/tool-calls' },- });-- await hook.handler!(event as any);-- expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });- });-- it('mocks a placeholder when a successful response has an invalid tool result', async () => {- mockSsrfSafeFetch.mockResolvedValue(- new Response(JSON.stringify({ data: { content: 1, success: true }, success: true })),- );- const hook = createEvalToolForwardingHook({- twitter: { endpoint: 'https://mock.test/tool-calls' },- });-- await hook.handler!(event as any);-- expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });- });-- it('mocks a failed result when the forwarding response is not JSON', async () => {- mockSsrfSafeFetch.mockResolvedValue(new Response('not-json'));- const hook = createEvalToolForwardingHook({- twitter: { endpoint: 'https://mock.test/tool-calls' },- });-- await hook.handler!(event as any);-- expect(event.mock).toHaveBeenCalledWith({- content: expect.stringContaining('SyntaxError'),- error: expect.any(SyntaxError),- success: false,- });- });-- it('mocks transport failures', async () => {- mockSsrfSafeFetch.mockRejectedValue('SSRF blocked');- const hook = createEvalToolForwardingHook({- twitter: { endpoint: 'https://mock.test/tool-calls' },- });-- await hook.handler!(event as any);-- expect(event.mock).toHaveBeenCalledWith({- content: 'SSRF blocked',- error: 'SSRF blocked',- success: false,- });- });- });-- describe('constructor', () => {- it('should initialize with default base URL', () => {- delete process.env.AGENT_RUNTIME_BASE_URL;- const newService = new AgentRuntimeService(mockDb, mockUserId);- expect((newService as any).baseURL).toBe('http://localhost:3210/api/agent');- });-- it('should initialize with custom base URL from environment', () => {- process.env.AGENT_RUNTIME_BASE_URL = 'http://custom:3000';- const newService = new AgentRuntimeService(mockDb, mockUserId);- expect((newService as any).baseURL).toBe('http://custom:3000/api/agent');- });- });-- describe('determineCompletionReason', () => {- const reasonFor = (state: Record<string, any>) =>- (service as any).determineCompletionReason(state);-- it('should report a plain completion as done', () => {- expect(reasonFor({ status: 'done', stepCount: 3 })).toBe('done');- });-- // The guard finalizes the turn without tool calls, which is indistinguishable- // from a real answer by status alone — so these runs were all filed as 'done'- // and could not be counted.- it('should name a run the tool-call repeat guard cut short', () => {- expect(- reasonFor({- status: 'done',- stepCount: 250,- toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },- }),- ).toBe('tool_call_repeat_limit');- });-- it('should let a real failure outrank the repeat-guard marker', () => {- expect(- reasonFor({- status: 'error',- stepCount: 250,- toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },- }),- ).toBe('error');- expect(- reasonFor({- status: 'interrupted',- stepCount: 250,- toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },- }),- ).toBe('interrupted');- });-- it('should ignore a guard that counted repeats without ever stopping', () => {- expect(- reasonFor({ status: 'done', stepCount: 3, toolCallRepeatGuard: { counts: { sig: 4 } } }),- ).toBe('done');- });-- it('should still report the step and cost caps', () => {- expect(reasonFor({ status: 'running', maxSteps: 10, stepCount: 10 })).toBe('max_steps');- expect(- reasonFor({- status: 'running',- stepCount: 3,- cost: { total: 5 },- costLimit: { maxTotalCost: 5 },- }),- ).toBe('cost_limit');- });- });-- describe('createOperation', () => {- const mockParams: OperationCreationParams = {- operationId: 'test-operation-1',- initialContext: {- phase: 'user_input',- payload: {- message: { content: 'test' },- sessionId: 'test-operation-1',- isFirstMessage: true,- },- session: { sessionId: 'test-operation-1', status: 'idle', stepCount: 0, messageCount: 0 },- },- appContext: {},- agentConfig: { name: 'test-agent' },- modelRuntimeConfig: { model: 'gpt-4' },- toolSet: { manifestMap: {} },- userId: 'user-123',- autoStart: true,- initialMessages: [],- };-- it.each([undefined, 'parent-operation'])(- 'persists only caller hooks for a run with parent %s',- async (parentOperationId) => {- vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'http://webhook-service/ingress');- vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-env-secret');- vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall, afterToolCall, beforeToolCall');- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');- vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');- const hooks = [- {- id: 'internal-callback',- type: 'afterToolCall' as const,- webhook: { url: 'http://webhook-service/internal' },- },- ];- await service.createOperation({- ...mockParams,- autoStart: false,- parentOperationId,- hooks,- });- const state = await mockCoordinator.loadAgentState(mockParams.operationId);- expect(state.host.hooks).toEqual(hooks);- expect(JSON.stringify(state.host.hooks)).not.toContain('synthetic-env-secret');- expect(hookDispatcher.hasHooks(mockParams.operationId)).toBe(true);- },- );-- it.each([undefined, false, true])(- 'persists the snapshot opt-in for resumed steps (%s)',- async (includeFinalState) => {- await service.createOperation({ ...mockParams, autoStart: false, includeFinalState });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host.includeFinalState === true).toBe(includeFinalState === true);- },- );-- describe('file Works declaration (host.acceptsFileWorks)', () => {- it('stores the declaration the client made', async () => {- await service.createOperation({ ...mockParams, acceptsFileWorks: true, autoStart: false });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host.acceptsFileWorks).toBe(true);- });-- it("lets a group member inherit its supervisor's declaration", async () => {- await mockCoordinator.saveAgentState('parent-op', { host: { acceptsFileWorks: true } });- mockCoordinator.saveAgentState.mockClear();-- await service.createOperation({- ...mockParams,- appContext: { ...mockParams.appContext, orchestrationRole: 'member' },- autoStart: false,- parentOperationId: 'parent-op',- });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host.acceptsFileWorks).toBe(true);- });-- it.each([undefined, false])('carries no declaration for %s', async (acceptsFileWorks) => {- await service.createOperation({ ...mockParams, acceptsFileWorks, autoStart: false });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host).not.toHaveProperty('acceptsFileWorks');- });- });-- describe('relay executor (host.llmExecutor)', () => {- const executor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', providers: ['ollama'] };- // A parent run of the caller's own.- const ownParent = (host: Record<string, unknown>) => ({- host,- origin: { userId: mockUserId },- });-- it('stores the executor the client declared', async () => {- await service.createOperation({ ...mockParams, autoStart: false, llmExecutor: executor });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host.llmExecutor).toEqual(executor);- });-- it("lets a group member, mirrored onto its parent's channel, inherit the parent's executor", async () => {- await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));- mockCoordinator.saveAgentState.mockClear();-- await service.createOperation({- ...mockParams,- appContext: { ...mockParams.appContext, orchestrationRole: 'member' },- autoStart: false,- parentOperationId: 'parent-op',- });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host.llmExecutor).toEqual({- ...executor,- channelOperationId: 'parent-op',- });- });-- it("lets an independent sub-agent inherit the parent's executor, relaying on the parent's channel", async () => {- await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));- mockCoordinator.saveAgentState.mockClear();-- await service.createOperation({- ...mockParams,- appContext: { ...mockParams.appContext, isSubAgent: true },- autoStart: false,- parentOperationId: 'parent-op',- });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- // The tab only subscribes to the parked parent's channel, so the- // child's `llm_execute` has to ride that one.- expect(savedState.host.llmExecutor).toEqual({- ...executor,- channelOperationId: 'parent-op',- });- });-- it("keeps a nested child on the channel the executor's tab subscribed to", async () => {- await mockCoordinator.saveAgentState(- 'parent-op',- ownParent({ llmExecutor: { ...executor, channelOperationId: 'root-op' } }),- );- mockCoordinator.saveAgentState.mockClear();-- await service.createOperation({- ...mockParams,- appContext: { ...mockParams.appContext, isSubAgent: true },- autoStart: false,- parentOperationId: 'parent-op',- });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host.llmExecutor).toEqual({- ...executor,- channelOperationId: 'root-op',- });- });-- it('relays on its own channel when the client declared the executor itself', async () => {- await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));- mockCoordinator.saveAgentState.mockClear();-- const own = { ...executor, clientId: 'tab-b' };- await service.createOperation({- ...mockParams,- appContext: { ...mockParams.appContext, isSubAgent: true },- autoStart: false,- llmExecutor: own,- parentOperationId: 'parent-op',- });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host.llmExecutor).toEqual(own);- });-- it("does not inherit the executor of another user's run", async () => {- // A client names `parentOperationId`; a foreign run's executor would- // hand this child's LLM payload to that user's tab.- await mockCoordinator.saveAgentState('foreign-op', {- host: { llmExecutor: executor },- origin: { userId: 'someone-else' },- });- mockCoordinator.saveAgentState.mockClear();-- await service.createOperation({- ...mockParams,- appContext: { ...mockParams.appContext, isSubAgent: true },- autoStart: false,- parentOperationId: 'foreign-op',- });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host).not.toHaveProperty('llmExecutor');- });-- it("does not inherit the executor of the user's run in another workspace", async () => {- // The same user's run elsewhere relays with that workspace's providers.- await mockCoordinator.saveAgentState('other-workspace-op', {- host: { llmExecutor: executor },- origin: { userId: mockUserId, workspaceId: 'ws-other' },- });- mockCoordinator.saveAgentState.mockClear();-- await service.createOperation({- ...mockParams,- appContext: { ...mockParams.appContext, isSubAgent: true },- autoStart: false,- parentOperationId: 'other-workspace-op',- });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host).not.toHaveProperty('llmExecutor');- });-- it('carries no executor for a run nobody declared one for', async () => {- await service.createOperation({ ...mockParams, autoStart: false });- const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];- expect(savedState.host).not.toHaveProperty('llmExecutor');- });- });-- it('should create operation successfully with autoStart=true', async () => {- mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');-- const result = await service.createOperation(mockParams);-- expect(result).toEqual({- success: true,- operationId: 'test-operation-1',- autoStarted: true,- messageId: 'message-123',- });-- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- operationId: 'test-operation-1',- status: 'idle',- stepCount: 0,- messages: [],- modelRuntimeConfig: mockParams.modelRuntimeConfig,- operationToolSet: expect.objectContaining({ manifestMap: {} }),- origin: expect.objectContaining({ userId: mockParams.userId }),- world: expect.objectContaining({ agent: mockParams.agentConfig }),- }),- );-- expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith('test-operation-1', {- agentConfig: mockParams.agentConfig,- modelRuntimeConfig: mockParams.modelRuntimeConfig,- userId: mockParams.userId,- });-- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({- operationId: 'test-operation-1',- stepIndex: 0,- context: mockParams.initialContext,- endpoint: 'http://localhost:3010/api/agent/run',- priority: 'high',- delay: 50,- });- });-- it('freezes the builder editing target on the run origin', async () => {- await service.createOperation({- ...mockParams,- appContext: {- editingAgentId: 'agt_target',- editingGroupId: 'grp_target',- scope: 'agent_builder',- },- });-- const [, state] = mockCoordinator.saveAgentState.mock.calls[0];- expect(state.origin).toMatchObject({- editingAgentId: 'agt_target',- editingGroupId: 'grp_target',- });- });-- it('records the approval mode as a run policy', async () => {- await service.createOperation({- ...mockParams,- userInterventionConfig: { approvalMode: 'headless' },- });-- const [, state] = mockCoordinator.saveAgentState.mock.calls[0];- expect(state.principal.policy.userIntervention).toEqual({ approvalMode: 'headless' });- // Mirrored at the top level for the rolling-deploy window: a worker on the- // pre-slot build reads only that, and would park this headless run.- expect(state.userInterventionConfig).toEqual({ approvalMode: 'headless' });- });-- it('stores the run tool set once, on the operation slot', async () => {- const manifestMap = { 'lobe-web-browsing': { identifier: 'lobe-web-browsing' } };-- await service.createOperation({- ...mockParams,- toolSet: {- enabledToolIds: ['lobe-web-browsing'],- executorMap: {},- manifestMap,- sourceMap: { 'lobe-web-browsing': 'builtin' },- tools: [{ function: { name: 'search' }, type: 'function' }],- } as unknown as OperationCreationParams['toolSet'],- });-- const [, state] = mockCoordinator.saveAgentState.mock.calls[0];- expect(state.operationToolSet.manifestMap).toEqual(manifestMap);- // Manifests are the heaviest thing on the state and it is re-serialized at- // every step, so the legacy top-level mirrors are not written any more.- for (const mirror of ['toolExecutorMap', 'toolManifestMap', 'toolSourceMap', 'tools']) {- expect(mirror in state).toBe(false);- }- });-- it('does not require durable storage for an environment-only result hook', async () => {- vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');- vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');- vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');- vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(- new Error('db down'),- );-- await expect(service.createOperation(mockParams)).resolves.toBeDefined();- });-- it('requires durable storage for a caller result hook', async () => {- vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(- new Error('db down'),- );-- await expect(- service.createOperation({- ...mockParams,- hooks: [- {- id: 'caller',- type: 'afterToolCall',- webhook: {- url: 'https://hooks.example/caller',- responseHandling: 'toolCall',- },- },- ],- }),- ).rejects.toThrow('Failed to durably persist afterToolCall');- });-- // Codex P1 on #20093: the member bridge lived only in the 2h runtime- // snapshot, so a late approval continued the supervisor instead.- it("keeps a durable copy of a group member's completion bridge on the row", async () => {- const recordStart = vi- .spyOn(AgentOperationModel.prototype, 'recordStart')- .mockResolvedValue(undefined);- const bridge = {- anchorMessageId: 'msg-speak',- expectedMembers: 1,- groupToolMessageId: 'msg-speak',- mode: 'in_group',- onComplete: 'resume',- parentOperationId: 'op-supervisor',- };-- await service.createOperation({- ...mockParams,- hooks: [- {- handler: vi.fn(),- id: 'group-member-bridge',- type: 'onComplete',- webhook: { body: bridge, url: '/api/agent/webhooks/group-member-callback' },- },- ],- } as any);-- expect(recordStart.mock.calls[0][0].metadata).toMatchObject({ groupMemberBridge: bridge });- });-- // Codex P2 on #20093: a transient start-row failure used to be swallowed,- // so the member ran without the durable bridge its Stop / late approval need.- it('refuses to start a group member whose bridge row could not be persisted', async () => {- vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(- new Error('db down'),- );-- await expect(- service.createOperation({- ...mockParams,- hooks: [- {- handler: vi.fn(),- id: 'group-member-bridge',- type: 'onComplete',- webhook: {- body: {- anchorMessageId: 'msg-speak',- expectedMembers: 1,- groupToolMessageId: 'msg-speak',- mode: 'in_group',- onComplete: 'resume',- parentOperationId: 'op-supervisor',- },- url: '/api/agent/webhooks/group-member-callback',- },- },- ],- } as any),- ).rejects.toThrow('Failed to durably persist group member');- });-- it('keeps the frozen model facts on the run state but out of durable storage', async () => {- const recordStart = vi- .spyOn(AgentOperationModel.prototype, 'recordStart')- .mockResolvedValue(undefined);- const modelFacts = {- cards: [{ abilities: { vision: true }, id: 'gpt-4', providerId: 'openai' }],- model: 'gpt-4',- provider: 'openai',- };-- await service.createOperation({- ...mockParams,- modelRuntimeConfig: { ...mockParams.modelRuntimeConfig, modelFacts },- });-- // The steps read the snapshot back off the state.- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- modelRuntimeConfig: expect.objectContaining({ modelFacts }),- }),- );- // The row that outlives the run, and the metadata copy, stay as small as- // they were: both only ever surface model / provider.- expect(recordStart.mock.calls[0][0].modelRuntimeConfig).toEqual({ model: 'gpt-4' });- expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({ modelRuntimeConfig: { model: 'gpt-4' } }),- );- });-- it('waits for dependent records before dispatch without losing the prepared context', async () => {- let release!: () => void;- const prepared = new Promise<void>((resolve) => {- release = resolve;- });- const onOperationCreated = vi.fn<(operationId: string) => Promise<void>>(- async () => prepared,- );- const initialContext = {- ...mockParams.initialContext,- payload: {- assistantMessageId: 'repair-assistant',- parentMessageId: 'verify-card',- },- } as OperationCreationParams['initialContext'];- const creation = service.createOperation({- ...mockParams,- initialContext,- onOperationCreated,- });- try {- await vi.waitFor(() =>- expect(onOperationCreated).toHaveBeenCalledWith(mockParams.operationId),- );- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- } finally {- release();- }- await creation;- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({ context: initialContext }),- );- });-- it('does not dispatch when dependent record preparation fails', async () => {- await expect(- service.createOperation({- ...mockParams,- onOperationCreated: async () => {- throw new Error('Plan unavailable');- },- }),- ).rejects.toThrow('Plan unavailable');- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('should create operation successfully with autoStart=false', async () => {- const params = { ...mockParams, autoStart: false };-- const result = await service.createOperation(params);-- expect(result).toEqual({- success: true,- operationId: 'test-operation-1',- autoStarted: false,- messageId: undefined,- });-- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('should handle errors during operation creation', async () => {- mockCoordinator.saveAgentState.mockRejectedValueOnce(new Error('Database error'));-- await expect(service.createOperation(mockParams)).rejects.toThrow('Database error');- });-- it('should pass maxSteps to initial state when provided', async () => {- mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');-- await service.createOperation({ ...mockParams, maxSteps: 25 });-- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- maxSteps: 25,- }),- );- });-- it('should place evalContext on the world snapshot when provided', async () => {- mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');-- const evalContext = { envPrompt: 'You are in a test environment' };- await service.createOperation({ ...mockParams, evalContext });-- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- world: expect.objectContaining({ eval: evalContext }),- }),- );- });-- it('should persist the system-message context on the world snapshot', async () => {- mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');-- const projectInstructions = [{ content: 'Use bun.', source: 'AGENTS.md' }];- const connectorOwnershipNote = 'Gmail runs on Alice’s account.';- await service.createOperation({- ...mockParams,- connectorOwnershipNote,- projectInstructions,- });-- // Steps can be claimed by another worker, so anything the context engine- // needs has to survive on the persisted operation state — in the typed- // `world` slot, which is the only place the engine reads it from.- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- world: expect.objectContaining({ connectorOwnershipNote, projectInstructions }),- }),- );- });-- it('should persist the operation expertise snapshot in runtime state', async () => {- mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');- const expertise = {- contentHash: 'stable-hash',- domains: [{ id: 'domain-1', lessonIds: ['lesson-1'] }],- renderedContext: '<expertise>stable</expertise>',- schemaVersion: 1,- };-- await service.createOperation({- ...mockParams,- enableExpertise: true,- expertise,- });-- // What the model is told about the run lives on the world slot, with the- // top-level mirror kept for pre-slot workers during a rolling deploy.- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- enableExpertise: true,- expertise,- world: expect.objectContaining({ enableExpertise: true, expertise }),- }),- );- });-- it('should restore tools activated in a previous operation into initial state', async () => {- const taskManifest = { identifier: 'lobe-task' } as any;- const initialMessages = [- {- content: 'Successfully activated tools: lobe-task',- id: 'tool-message-1',- plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },- pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },- role: 'tool',- },- ] as any;-- await service.createOperation({- ...mockParams,- autoStart: false,- initialMessages,- initialStepCount: 3,- toolSet: {- ...mockParams.toolSet,- activatableToolIds: ['lobe-task'],- manifestMap: { 'lobe-task': taskManifest },- },- });-- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- activatedStepTools: [- {- activatedAtStep: 3,- id: 'lobe-task',- manifest: taskManifest,- source: 'discovery',- },- ],- }),- );- });-- it('should not restore historical tools that current run gates reject', async () => {- await service.createOperation({- ...mockParams,- autoStart: false,- initialMessages: [- {- content: 'Successfully activated tools: lobe-task',- id: 'tool-message-1',- plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },- pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },- role: 'tool',- },- ] as any,- toolSet: {- ...mockParams.toolSet,- // The broad discovery map may still contain the manifest in chat/custom- // mode or for a model without function calling support.- activatableToolIds: [],- manifestMap: { 'lobe-task': { identifier: 'lobe-task' } as any },- },- });-- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({ activatedStepTools: undefined }),- );- });-- it('should abort before creating operation when signal is already aborted', async () => {- const controller = new AbortController();- controller.abort(new Error('startup aborted'));-- await expect(- service.createOperation({- ...mockParams,- signal: controller.signal,- }),- ).rejects.toMatchObject({- message: 'startup aborted',- name: 'AbortError',- });-- expect(mockCoordinator.createAgentOperation).not.toHaveBeenCalled();- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('should cleanup partially created operation when aborted before scheduling', async () => {- const controller = new AbortController();- const originalCreateAgentOperation =- mockCoordinator.createAgentOperation.getMockImplementation();-- mockCoordinator.createAgentOperation.mockImplementationOnce(async (...args: any[]) => {- await originalCreateAgentOperation?.(...args);- controller.abort(new Error('startup aborted'));- });-- await expect(- service.createOperation({- ...mockParams,- hooks: [{ handler: vi.fn(), id: 'hook-1', type: 'onComplete' }],- signal: controller.signal,- }),- ).rejects.toMatchObject({- message: 'startup aborted',- name: 'AbortError',- });-- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- expect(mockCoordinator.deleteAgentOperation).toHaveBeenCalledWith('test-operation-1');- expect(hookDispatcher.hasHooks('test-operation-1')).toBe(false);- });- });-- describe('executeStep', () => {- const mockParams: AgentExecutionParams = {- operationId: 'test-operation-1',- stepIndex: 1,- context: {- phase: 'user_input',- payload: {- message: { content: 'test' },- sessionId: 'test-operation-1',- isFirstMessage: false,- },- session: {- sessionId: 'test-operation-1',- status: 'running',- stepCount: 1,- messageCount: 1,- },- },- };-- const mockState = {- operationId: 'test-operation-1',- status: 'running',- stepCount: 1,- messages: [],- events: [],- lastModified: new Date().toISOString(),- };-- const mockMetadata = {- userId: 'user-123',- agentConfig: { name: 'test-agent' },- modelRuntimeConfig: { model: 'gpt-4' },- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- status: 'running',- totalCost: 0,- totalSteps: 1,- };-- beforeEach(() => {- mockCoordinator.loadAgentState.mockResolvedValue(mockState);- mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);- });-- it('acks a delayed delivery after the durable operation was abandoned', async () => {- vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({- id: mockParams.operationId,- status: 'abandoned',- });-- const result = await service.executeStep(mockParams);-- expect(result).toEqual({- nextStepScheduled: false,- state: { status: 'interrupted' },- stepResult: null,- success: true,- });- expect(mockCoordinator.tryClaimStep).not.toHaveBeenCalled();- });-- it('should pass resolved contextWindowTokens into compressionConfig', async () => {- vi.mocked(getModelPropertyWithFallback).mockResolvedValueOnce(200_000);-- let capturedConfig: any;- const serviceWithFactory = new AgentRuntimeService(mockDb, mockUserId, {- agentFactory: (config) => {- capturedConfig = config;- return { runner: vi.fn() } as any;- },- });-- await (serviceWithFactory as any).createAgentRuntime({- agentState: {- world: { agent: { chatConfig: { enableContextCompression: true } } as any },- modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },- },- operationId: 'test-operation-1',- stepIndex: 1,- });-- expect(getModelPropertyWithFallback).toHaveBeenCalledWith(- 'gpt-4o-mini',- 'contextWindowTokens',- 'openai',- );- expect(capturedConfig).toEqual(- expect.objectContaining({- compressionConfig: expect.objectContaining({- enabled: true,- maxWindowToken: 200_000,- }),- }),- );- });-- it('should fall back to undefined maxWindowToken when model lookup misses', async () => {- vi.mocked(getModelPropertyWithFallback).mockResolvedValueOnce(undefined);-- let capturedConfig: any;- const serviceWithFactory = new AgentRuntimeService(mockDb, mockUserId, {- agentFactory: (config) => {- capturedConfig = config;- return { runner: vi.fn() } as any;- },- });-- await (serviceWithFactory as any).createAgentRuntime({- agentState: {- world: { agent: { chatConfig: { enableContextCompression: true } } as any },- modelRuntimeConfig: { model: 'unknown-model', provider: 'openai' },- },- operationId: 'test-operation-1',- stepIndex: 1,- });-- expect(capturedConfig).toEqual(- expect.objectContaining({- compressionConfig: expect.objectContaining({- enabled: true,- maxWindowToken: undefined,- }),- }),- );- });-- it.each([false, true])(- 'reuses the entry read for device discovery (device=%s)',- async (withDevice) => {- const state = {- ...mockState,- messages: [],- origin: { agentId: 'agent-1', topicId: 'topic-1' },- };- mockCoordinator.loadAgentState.mockResolvedValue(state);- const dbMessages = buildPersistedToolChain('full model answer');- dbMessages[0].imageList = [{ id: 'file-1', url: 'raw/image', alt: 'image' }];- if (withDevice) {- dbMessages[0] = {- ...dbMessages[0],- role: 'tool',- pluginState: { metadata: { activeDeviceId: 'device-1', devicePlatform: 'darwin' } },- };- }- const query = (service as any).messageModel.query.mockResolvedValue(dbMessages);- vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue([]);- const step = vi.fn().mockImplementation(async (input) => ({- events: [],- newState: { ...input, stepCount: 2 },- nextContext: mockParams.context,- }));- vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });-- const result = await service.executeStep(mockParams);-- expect(result.success).toBe(true);- expect(query).toHaveBeenCalledTimes(1);- expect(JSON.stringify(step.mock.calls[0][0].messages)).toContain('full model answer');- expect(JSON.stringify(step.mock.calls[0][0].messages)).toContain('model:raw/image');- expect(dbMessages[0].imageList?.[0].url).toBe('raw/image');- expect(step.mock.calls[0][0].binding?.device?.id).toBe(withDevice ? 'device-1' : undefined);- },- );-- // The executors read the device id through the same gate, so binding one for- // a run that may not touch a device buys nothing — and its working directory- // and system info would ride into the prompt variables.- it.each([- { policy: { deviceAccess: { canUseDevice: false, reason: 'external-bot' } }, why: 'policy' },- { plan: { execution: { kind: 'sandbox', target: 'sandbox' } }, why: 'plan' },- ])('does not adopt a device the run may not use ($why)', async ({ plan, policy }) => {- const state = {- ...mockState,- messages: [],- origin: { agentId: 'agent-1', topicId: 'topic-1' },- ...(plan && { plan }),- ...(policy && { principal: { policy } }),- };- mockCoordinator.loadAgentState.mockResolvedValue(state);- const dbMessages = buildPersistedToolChain('answer');- dbMessages[0] = {- ...dbMessages[0],- pluginState: {- metadata: {- activeDeviceId: 'device-1',- devicePlatform: 'darwin',- deviceSystemInfo: { workingDirectory: '/Users/someone/secret' },- },- },- role: 'tool',- };- (service as any).messageModel.query.mockResolvedValue(dbMessages);- vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue([]);- const step = vi.fn().mockImplementation(async (input) => ({- events: [],- newState: { ...input, stepCount: 2 },- nextContext: mockParams.context,- }));- vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });-- const result = await service.executeStep(mockParams);-- expect(result.success).toBe(true);- expect(step.mock.calls[0][0].binding?.device).toBeUndefined();- });-- describe('activateDevice after a device is already bound', () => {- const activation = (id: string, deviceId: string): UIChatMessage =>- ({- content: `Device "${deviceId}" activated successfully.`,- createdAt: 3,- id,- pluginState: { metadata: { activeDeviceId: deviceId } },- role: 'tool',- updatedAt: 3,- }) as UIChatMessage;-- const runStep = async (execution: Record<string, unknown>) => {- const state = {- ...mockState,- binding: { device: { id: 'device-a' } },- messages: [],- origin: { agentId: 'agent-1', topicId: 'topic-1' },- plan: { execution },- };- mockCoordinator.loadAgentState.mockResolvedValue(state);- // The model activated device-a first, then device-b.- (service as any).messageModel.query.mockResolvedValue([- ...buildPersistedToolChain('answer'),- activation('activate-a', 'device-a'),- activation('activate-b', 'device-b'),- ]);- vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue([]);- const step = vi.fn().mockImplementation(async (input) => ({- events: [],- newState: { ...input, stepCount: 2 },- nextContext: mockParams.context,- }));- vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });-- const result = await service.executeStep(mockParams);- expect(result.success).toBe(true);- return step.mock.calls[0][0].binding?.device?.id;- };-- it('follows the latest activation while the plan leaves the device open', async () => {- const deviceId = await runStep({- kind: 'device-unrouted',- reason: 'ambiguous-online-devices',- target: 'auto',- });-- expect(deviceId).toBe('device-b');- });-- it('keeps a locked run on its device even if history names another one', async () => {- const deviceId = await runStep({ deviceId: 'device-a', kind: 'device', target: 'device' });-- expect(deviceId).toBe('device-a');- });- });-- it('shares one DB read while UI preparation is still pending', async () => {- const state = {- ...mockState,- messages: [],- origin: { agentId: 'agent-1', topicId: 'topic-1' },- };- mockCoordinator.loadAgentState.mockResolvedValue(state);- const query = (service as any).messageModel.query.mockResolvedValue([]);- let resolveUi!: (messages: []) => void;- const uiRead = vi.spyOn((service as any).messageService, 'prepareUiMessages').mockReturnValue(- new Promise((resolve) => {- resolveUi = resolve;- }),- );- const step = vi.fn().mockResolvedValue({- events: [],- newState: { ...state, stepCount: 2 },- nextContext: mockParams.context,- });- vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });- const running = service.executeStep(mockParams);- let startedBeforeUiResolved: boolean;- try {- await vi.waitFor(() => expect(uiRead).toHaveBeenCalled());- startedBeforeUiResolved = query.mock.calls.length > 0;- expect(step).not.toHaveBeenCalled();- } finally {- resolveUi([]);- await running;- }- expect(startedBeforeUiResolved).toBe(true);- expect(query).toHaveBeenCalledTimes(1);- });-- it('keeps ephemeral input while preparing the persisted UI snapshot', async () => {- const messages = [{ role: 'user', content: 'transient prompt' }];- const state = { ...mockState, messages, origin: { agentId: 'agent', topicId: 'topic' } };- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain('stored answer'),- );- const ui = [{ id: 'ui', role: 'assistant', content: 'UI answer' }];- vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue(ui);-- const result = await (service as any).queryStepEntryMessages(state);-- expect(state.messages).toBe(messages);- expect(result.uiMessages).toEqual(ui);- expect(result.messages).toHaveLength(4);- });-- it('hydrates the model even when UI preparation fails', async () => {- const state = { ...mockState, messages: [], origin: { agentId: 'agent', topicId: 'topic' } };- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain('stored answer'),- );- vi.spyOn((service as any).messageService, 'prepareUiMessages').mockRejectedValue(- new Error('UI failed'),- );- vi.spyOn(console, 'error').mockImplementation(() => {});-- const result = await (service as any).queryStepEntryMessages(state);-- expect(JSON.stringify(state.messages)).toContain('stored answer');- expect(result.uiMessages).toBeUndefined();- expect(result.messages).toHaveLength(4);- });-- it('should execute step successfully', async () => {- const mockStepResult = {- newState: { ...mockState, stepCount: 2, status: 'running' },- nextContext: mockParams.context,- events: [],- };-- // Mock runtime.step- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- const result = await service.executeStep(mockParams);-- expect(result).toEqual({- success: true,- state: mockStepResult.newState,- stepResult: expect.objectContaining(mockStepResult),- nextStepScheduled: true,- });-- expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {- type: 'step_start',- stepIndex: 1,- data: {},- });-- expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {- type: 'step_complete',- stepIndex: 1,- data: {- stepIndex: 1,- nextStepScheduled: false, // Published before nextStepScheduled is updated- },- });-- expect(mockCoordinator.saveStepResult).toHaveBeenCalled();- expect(mockQueueService.scheduleMessage).toHaveBeenCalled();- });-- describe('frozen credential snapshot', () => {- const frozen = {- credentials: [{ key: 'OPENAI', name: 'OpenAI', type: 'apiKey' }],- workspaceId: undefined,- };-- /**- * Snapshot the state AT the save, not the object afterwards: the runtime- * keeps mutating `newState`, so a later clear would otherwise read back as- * if it had been persisted.- */- const runStepWithToolCall = async (apiName: string) => {- const stateWithSnapshot = { ...mockState, operationCredentials: frozen };- mockCoordinator.loadAgentState.mockResolvedValue(stateWithSnapshot);-- let persisted: string | undefined;- mockCoordinator.saveStepResult.mockImplementationOnce(async (_id: string, result: any) => {- persisted = JSON.stringify(result.newState);- });-- const mockRuntime = {- step: vi.fn().mockResolvedValue({- events: [],- newState: { ...stateWithSnapshot, status: 'running', stepCount: 2 },- nextContext: {- payload: { toolCall: { apiName, identifier: 'lobe-creds' } },- phase: 'tool_result',- },- }),- };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- await service.executeStep(mockParams);-- expect(persisted).toBeDefined();- return JSON.parse(persisted!);- };-- it('drops the snapshot in the state it persists after the run saves a credential', async () => {- const persistedState = await runStepWithToolCall('requestCredsInput');-- expect(persistedState.operationCredentials).toBeUndefined();- });-- it('keeps the snapshot when the creds call only read', async () => {- const persistedState = await runStepWithToolCall('injectCredsToSandbox');-- expect(persistedState.operationCredentials).toEqual({- credentials: frozen.credentials,- });- });- });-- it('should resume async tools with the last pending tool result as parentMessageId', async () => {- const pendingTools = [- {- apiName: 'callSubAgent',- arguments: '{}',- id: 'tool-call-1',- identifier: 'agent-management',- type: 'default',- },- {- apiName: 'callSubAgent',- arguments: '{}',- id: 'tool-call-2',- identifier: 'agent-management',- type: 'default',- },- ];- const parkedState = {- ...mockState,- interruption: {- canResume: true,- interruptedAt: new Date().toISOString(),- reason: 'async_tool',- },- pendingToolsCalling: pendingTools,- status: 'waiting_for_async_tool',- };- const refreshedMessages = [- { content: 'use tools', id: 'user-msg-1', role: 'user' },- {- children: [- {- id: 'assistant-msg-1',- role: 'assistant',- tools: [- { ...pendingTools[0], result_msg_id: 'tool-msg-1' },- { ...pendingTools[1], result_msg_id: 'tool-msg-2' },- ],- },- ],- id: 'assistant-group-1',- role: 'assistantGroup',- },- ];- const mockStepResult = {- events: [],- newState: { ...parkedState, pendingToolsCalling: [], status: 'done', stepCount: 2 },- nextContext: null,- };- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };-- mockCoordinator.loadAgentState.mockResolvedValue(parkedState);- vi.spyOn(service as any, 'refreshMessagesFromDB').mockResolvedValue(refreshedMessages);- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- await service.executeStep({ ...mockParams, resumeAsyncTool: true });-- expect(mockRuntime.step).toHaveBeenCalledWith(- expect.objectContaining({- messages: refreshedMessages,- pendingToolsCalling: [],- status: 'running',- }),- expect.objectContaining({- payload: { parentMessageId: 'tool-msg-2' },- phase: 'user_input',- }),- );- });-- // Approving a callSubAgent starts a resume op that seeds its assistant- // placeholder, runs the tool, then parks on the deferred sub-agent. The- // resumed turn must fill that seed; a second assistant left the seed as an- // empty "…" branch that hid the real answer.- it('fills the seeded assistant placeholder when resuming from an async tool', async () => {- const parkedState = {- ...mockState,- interruption: {- canResume: true,- interruptedAt: new Date().toISOString(),- reason: 'async_tool',- },- pendingAssistantMessageId: 'seeded-assistant-1',- pendingToolsCalling: [- {- apiName: 'callSubAgent',- arguments: '{}',- id: 'tool-call-1',- identifier: 'lobe-agent',- type: 'builtin',- },- ],- status: 'waiting_for_async_tool',- };- const refreshedMessages = [- { content: 'research', id: 'user-msg-1', role: 'user' },- {- id: 'assistant-msg-1',- role: 'assistant',- tools: [{ id: 'tool-call-1', result_msg_id: 'tool-msg-1' }],- },- ];- const mockRuntime = {- step: vi.fn().mockResolvedValue({- events: [],- newState: { ...parkedState, pendingToolsCalling: [], status: 'done', stepCount: 2 },- nextContext: null,- }),- };-- mockCoordinator.loadAgentState.mockResolvedValue(parkedState);- vi.spyOn(service as any, 'refreshMessagesFromDB').mockResolvedValue(refreshedMessages);- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- await service.executeStep({ ...mockParams, resumeAsyncTool: true });-- expect(mockRuntime.step).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- payload: { assistantMessageId: 'seeded-assistant-1', parentMessageId: 'tool-msg-1' },- phase: 'user_input',- }),- );- });-- it('should handle missing agent state', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);-- await expect(service.executeStep(mockParams)).rejects.toThrow(- 'Agent state not found for operation test-operation-1',- );- });-- it('should handle execution errors', async () => {- const error = new Error('Runtime error');- const mockRuntime = { step: vi.fn().mockRejectedValue(error) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- await expect(service.executeStep(mockParams)).rejects.toThrow('Runtime error');-- expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {- type: 'error',- stepIndex: 1,- data: {- stepIndex: 1,- phase: 'step_execution',- error: 'Runtime error',- errorType: '500',- },- });- });-- it('should dispatch onComplete hook with error in finalState when execution fails', async () => {- const error = new Error('Runtime error');- const mockRuntime = { step: vi.fn().mockRejectedValue(error) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);-- await expect(service.executeStep(mockParams)).rejects.toThrow('Runtime error');-- // Verify onComplete hooks dispatched with error in finalState as ChatMessageError- expect(dispatchSpy).toHaveBeenCalledWith(- 'test-operation-1',- 'onComplete',- expect.objectContaining({- operationId: 'test-operation-1',- reason: 'error',- finalState: expect.objectContaining({- error: expect.objectContaining({- type: 500, // ChatErrorType.InternalServerError- message: 'Runtime error',- body: expect.objectContaining({ name: 'Error' }),- }),- }),- }),- undefined,- );-- dispatchSpy.mockRestore();- });-- it('should dispatch onComplete hook with ChatCompletionErrorPayload in finalState', async () => {- // Simulate LLM error format: { errorType: 'InvalidProviderAPIKey', error: { ... } }- const llmError = {- errorType: 'InvalidProviderAPIKey',- error: { status: 401 },- provider: 'openai',- };- const mockRuntime = { step: vi.fn().mockRejectedValue(llmError) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);-- await expect(service.executeStep(mockParams)).rejects.toEqual(llmError);-- // Verify error is formatted correctly with type from errorType- expect(dispatchSpy).toHaveBeenCalledWith(- 'test-operation-1',- 'onComplete',- expect.objectContaining({- operationId: 'test-operation-1',- reason: 'error',- finalState: expect.objectContaining({- error: expect.objectContaining({- type: 'InvalidProviderAPIKey',- message: 'InvalidProviderAPIKey',- body: expect.objectContaining({ status: 401 }),- }),- }),- }),- undefined,- );-- dispatchSpy.mockRestore();- });-- it('should save error state to coordinator for later retrieval (inMemory mode fix)', async () => {- const error = new Error('Test error for inMemory mode');- const mockRuntime = { step: vi.fn().mockRejectedValue(error) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- // Spy on coordinator.saveAgentState to verify it's called with error state- const saveStateSpy = vi.spyOn((service as any).coordinator, 'saveAgentState');-- await expect(service.executeStep(mockParams)).rejects.toThrow('Test error for inMemory mode');-- // Verify saveAgentState is called with error state before onComplete- expect(saveStateSpy).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- error: expect.objectContaining({- type: 500, // ChatErrorType.InternalServerError- message: 'Test error for inMemory mode',- }),- status: 'error',- }),- );- });-- it('should handle human intervention', async () => {- const paramsWithIntervention = {- ...mockParams,- humanInput: { type: 'text', content: 'user input' },- approvedToolCall: { toolName: 'calculator', args: {} },- rejectionReason: 'Not safe',- };-- const mockStepResult = {- newState: { ...mockState, stepCount: 2, status: 'done' },- nextContext: null,- events: [],- };-- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });- const processSpy = vi.spyOn((service as any).humanIntervention, 'process').mockResolvedValue({- newState: mockState,- nextContext: mockParams.context,- });-- const result = await service.executeStep(paramsWithIntervention);-- expect(processSpy).toHaveBeenCalledWith(mockState, {- approvedToolCall: paramsWithIntervention.approvedToolCall,- humanInput: paramsWithIntervention.humanInput,- rejectAndContinue: undefined,- rejectionReason: paramsWithIntervention.rejectionReason,- toolMessageId: undefined,- });-- expect(result.success).toBe(true);- expect(result.nextStepScheduled).toBe(false); // Should not schedule next step when status is 'done'- });-- it('should detect interruption that occurred during step execution', async () => {- const mockStepResult = {- newState: { ...mockState, stepCount: 2, status: 'running' },- nextContext: mockParams.context,- events: [],- };-- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- // Initial load returns running state; the post-step interrupt check- // reads the sentinel instead of the state blob- mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);- mockCoordinator.isInterrupted.mockResolvedValueOnce(true);-- const result = await service.executeStep(mockParams);-- // The step result should reflect the interrupted status- expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));- expect(result.nextStepScheduled).toBe(false);- // saveStepResult should be called with interrupted state- expect(mockCoordinator.saveStepResult).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- newState: expect.objectContaining({ status: 'interrupted' }),- }),- );- });-- it('should detect an interruption written by an old worker without a sentinel', async () => {- const mockStepResult = {- events: [],- newState: { ...mockState, status: 'running', stepCount: 2 },- nextContext: mockParams.context,- };-- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });- mockCoordinator.loadAgentState- .mockResolvedValueOnce(mockState)- .mockResolvedValueOnce({ ...mockState, status: 'interrupted' });- mockCoordinator.isInterrupted.mockResolvedValueOnce(false);-- const result = await service.executeStep(mockParams);-- expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));- expect(result.nextStepScheduled).toBe(false);- expect(mockCoordinator.loadAgentState).toHaveBeenCalledTimes(2);- expect(mockCoordinator.saveStepResult).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- newState: expect.objectContaining({ status: 'interrupted' }),- }),- );- });-- it('should abort a long step when an old worker writes only interrupted state', async () => {- vi.useFakeTimers();- const mockStepResult = {- events: [],- newState: { ...mockState, status: 'running', stepCount: 2 },- nextContext: mockParams.context,- };-- try {- vi.spyOn(service as any, 'createAgentRuntime').mockImplementation(function (- ...args: unknown[]- ) {- const { abortSignal } = args[0] as { abortSignal: AbortSignal };- return {- runtime: {- step: vi.fn(function () {- return new Promise((resolve) => {- abortSignal.addEventListener('abort', () => resolve(mockStepResult), {- once: true,- });- });- }),- },- };- });- mockCoordinator.loadAgentState- .mockResolvedValueOnce(mockState)- .mockResolvedValue({ ...mockState, status: 'interrupted' });- mockCoordinator.isInterrupted.mockResolvedValue(false);-- const execution = service.executeStep(mockParams);- await vi.advanceTimersByTimeAsync(0);- await vi.advanceTimersByTimeAsync(30_000);- const result = await execution;-- expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));- expect(result.nextStepScheduled).toBe(false);- } finally {- vi.useRealTimers();- }- });-- it('should resolve pending client tools when interruption races the parked result', async () => {- const completedTool = {- apiName: 'calculate',- arguments: '{}',- id: 'completed-server-tool-call',- identifier: 'server-tool',- type: 'default' as const,- };- const pendingTool = {- apiName: 'search',- arguments: '{}',- id: 'client-tool-call',- identifier: 'client-tool',- type: 'default' as const,- };- const parkedResult = {- events: [{ type: 'interrupted' as const }],- newState: {- ...mockState,- messages: [- {- content: 'Completed server result',- role: 'tool' as const,- tool_call_id: completedTool.id,- },- ],- pendingToolsCalling: [pendingTool],- status: 'waiting_for_async_tool' as const,- stepCount: 2,- },- nextContext: undefined,- };- const resolvedResult = {- events: [{ type: 'done' as const }],- newState: {- ...parkedResult.newState,- messages: [- ...parkedResult.newState.messages,- {- content: 'Tool execution was aborted by user.',- role: 'tool' as const,- tool_call_id: pendingTool.id,- },- ],- status: 'done' as const,- },- };- const mockRuntime = {- step: vi.fn().mockResolvedValueOnce(parkedResult).mockResolvedValueOnce(resolvedResult),- };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });- mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);- mockCoordinator.isInterrupted.mockResolvedValueOnce(true);-- const mixedBatchContext = {- ...mockParams.context!,- payload: {- ...(mockParams.context!.payload as Record<string, unknown>),- hasToolsCalling: true,- toolsCalling: [completedTool, pendingTool],- },- phase: 'llm_result' as const,- };- const result = await service.executeStep({ ...mockParams, context: mixedBatchContext });-- expect(result.state).toEqual(- expect.objectContaining({- messages: expect.arrayContaining([- expect.objectContaining({- content: 'Completed server result',- tool_call_id: completedTool.id,- }),- expect.objectContaining({ tool_call_id: pendingTool.id }),- ]),- status: 'interrupted',- }),- );- expect(mockRuntime.step).toHaveBeenCalledTimes(2);- expect(mockRuntime.step).toHaveBeenLastCalledWith(- expect.objectContaining({ status: 'interrupted' }),- expect.objectContaining({- payload: expect.objectContaining({ toolsCalling: [pendingTool] }),- phase: 'llm_result',- }),- );- });- });-- describe('executeStep - tool result extraction', () => {- const mockParams: AgentExecutionParams = {- operationId: 'test-operation-1',- stepIndex: 1,- context: {- phase: 'user_input',- payload: {- message: { content: 'test' },- sessionId: 'test-operation-1',- isFirstMessage: false,- },- session: {- sessionId: 'test-operation-1',- status: 'running',- stepCount: 1,- messageCount: 1,- },- },- };-- const mockState = {- operationId: 'test-operation-1',- status: 'running',- stepCount: 1,- messages: [],- events: [],- lastModified: new Date().toISOString(),- };-- const mockMetadata = {- userId: 'user-123',- agentConfig: { name: 'test-agent' },- modelRuntimeConfig: { model: 'gpt-4' },- createdAt: new Date().toISOString(),- lastActiveAt: new Date().toISOString(),- status: 'running',- totalCost: 0,- totalSteps: 1,- };-- beforeEach(() => {- mockCoordinator.loadAgentState.mockResolvedValue(mockState);- mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);- });-- it('should extract tool output from data field for single tool_result', async () => {- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);-- const mockStepResult = {- newState: { ...mockState, stepCount: 2, status: 'running' },- nextContext: {- phase: 'tool_result',- payload: {- data: 'Search found 3 results for "weather"',- executionTime: 120,- isSuccess: true,- toolCall: { identifier: 'lobe-web-browsing', apiName: 'search', id: 'tc-1' },- toolCallId: 'tc-1',- },- session: {- sessionId: 'test-operation-1',- status: 'running',- stepCount: 2,- messageCount: 2,- },- },- events: [],- };-- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- await service.executeStep(mockParams);-- expect(dispatchSpy).toHaveBeenCalledWith(- 'test-operation-1',- 'afterStep',- expect.objectContaining({- toolsResult: [- expect.objectContaining({- apiName: 'search',- identifier: 'lobe-web-browsing',- output: 'Search found 3 results for "weather"',- }),- ],- }),- undefined,- );-- dispatchSpy.mockRestore();- });-- it('should extract tool output from data field for tools_batch_result', async () => {- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);-- const mockStepResult = {- newState: { ...mockState, stepCount: 2, status: 'running' },- nextContext: {- phase: 'tools_batch_result',- payload: {- parentMessageId: 'msg-1',- toolCount: 2,- toolResults: [- {- data: 'Result from tool A',- executionTime: 100,- isSuccess: true,- toolCall: { identifier: 'builtin', apiName: 'searchA', id: 'tc-1' },- toolCallId: 'tc-1',- },- {- data: { items: [1, 2, 3] },- executionTime: 200,- isSuccess: true,- toolCall: { identifier: 'lobe-skills', apiName: 'activateSkill', id: 'tc-2' },- toolCallId: 'tc-2',- },- ],- },- session: {- sessionId: 'test-operation-1',- status: 'running',- stepCount: 2,- messageCount: 3,- },- },- events: [],- };-- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- await service.executeStep(mockParams);-- expect(dispatchSpy).toHaveBeenCalledWith(- 'test-operation-1',- 'afterStep',- expect.objectContaining({- toolsResult: [- expect.objectContaining({- apiName: 'searchA',- identifier: 'builtin',- output: 'Result from tool A',- }),- expect.objectContaining({- apiName: 'activateSkill',- identifier: 'lobe-skills',- output: JSON.stringify({ items: [1, 2, 3] }),- }),- ],- }),- undefined,- );-- dispatchSpy.mockRestore();- });-- it('should handle tool result with undefined data', async () => {- const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);-- const mockStepResult = {- newState: { ...mockState, stepCount: 2, status: 'running' },- nextContext: {- phase: 'tool_result',- payload: {- data: undefined,- toolCall: { identifier: 'builtin', apiName: 'noop', id: 'tc-1' },- toolCallId: 'tc-1',- },- session: {- sessionId: 'test-operation-1',- status: 'running',- stepCount: 2,- messageCount: 2,- },- },- events: [],- };-- const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };- vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });-- await service.executeStep(mockParams);-- expect(dispatchSpy).toHaveBeenCalledWith(- 'test-operation-1',- 'afterStep',- expect.objectContaining({- toolsResult: [- expect.objectContaining({- apiName: 'noop',- identifier: 'builtin',- output: undefined,- }),- ],- }),- undefined,- );-- dispatchSpy.mockRestore();- });- });-- describe('getOperationStatus', () => {- const mockState = {- operationId: 'test-operation-1',- status: 'running',- stepCount: 5,- messages: [{ content: 'msg1' }, { content: 'msg2' }],- cost: { total: 0.1 },- usage: { tokens: 100 },- lastModified: new Date().toISOString(),- };-- const mockMetadata = {- userId: 'user-123',- createdAt: new Date(Date.now() - 3600000).toISOString(), // 1 hour ago- lastActiveAt: new Date(Date.now() - 1800000).toISOString(), // 30 minutes ago- };-- beforeEach(() => {- mockCoordinator.loadAgentState.mockResolvedValue(mockState);- mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);- });-- it('should get operation status successfully', async () => {- const result = await service.getOperationStatus({- operationId: 'test-operation-1',- includeHistory: false,- });-- expect(result).toEqual({- operationId: 'test-operation-1',- currentState: expect.objectContaining({- status: 'running',- stepCount: 5,- cost: { total: 0.1 },- usage: { tokens: 100 },- }),- metadata: mockMetadata,- isActive: true,- isCompleted: false,- hasError: false,- needsHumanInput: false,- stats: {- totalSteps: 5,- totalMessages: 2,- totalCost: 0.1,- uptime: expect.any(Number),- lastActiveTime: expect.any(Number),- },- });- });-- it('should include history when requested', async () => {- const mockHistory = [{ stepIndex: 1, timestamp: Date.now() }];- const mockEvents = [{ type: 'step_start', timestamp: Date.now() }];-- mockCoordinator.getExecutionHistory.mockResolvedValue(mockHistory);- mockStreamManager.getStreamHistory.mockResolvedValue(mockEvents);-- const result = await service.getOperationStatus({- operationId: 'test-operation-1',- includeHistory: true,- historyLimit: 20,- });-- expect(result?.executionHistory).toEqual(mockHistory);- expect(result?.recentEvents).toEqual(mockEvents.slice(0, 10));- });-- it('should return null for missing operation', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- mockCoordinator.getOperationMetadata.mockResolvedValue(null);-- const result = await service.getOperationStatus({- operationId: 'nonexistent-operation',- });-- expect(result).toBeNull();- });-- it('should handle different operation statuses', async () => {- // Test waiting_for_human status- const waitingState = { ...mockState, status: 'waiting_for_human' };- mockCoordinator.loadAgentState.mockResolvedValue(waitingState);-- const result = await service.getOperationStatus({- operationId: 'test-operation-1',- });-- expect(result?.isActive).toBe(true);- expect(result?.needsHumanInput).toBe(true);- });- });-- describe('getPendingInterventions', () => {- it('should get pending interventions for specific operation', async () => {- const mockState = {- status: 'waiting_for_human',- pendingToolsCalling: [{ toolName: 'calculator', args: {} }],- stepCount: 3,- lastModified: new Date().toISOString(),- };-- const mockMetadata = {- userId: 'user-123',- modelRuntimeConfig: { model: 'gpt-4' },- };-- mockCoordinator.loadAgentState.mockResolvedValue(mockState);- mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);-- const result = await service.getPendingInterventions({- operationId: 'test-operation-1',- });-- expect(result).toEqual({- totalCount: 1,- timestamp: expect.any(String),- pendingInterventions: [- {- operationId: 'test-operation-1',- type: 'tool_approval',- status: 'waiting_for_human',- stepCount: 3,- lastModified: mockState.lastModified,- userId: 'user-123',- modelRuntimeConfig: { model: 'gpt-4' },- pendingToolsCalling: mockState.pendingToolsCalling,- },- ],- });- });-- it('should get pending interventions for user', async () => {- const mockOperations = ['operation-1', 'operation-2'];- mockCoordinator.getActiveOperations.mockResolvedValue(mockOperations);-- // Mock metadata for filtering by userId- mockCoordinator.getOperationMetadata- .mockResolvedValueOnce({ userId: 'user-123' })- .mockResolvedValueOnce({ userId: 'other-user' });-- // Mock states - only first operation needs intervention- mockCoordinator.loadAgentState- .mockResolvedValueOnce({- status: 'waiting_for_human',- pendingHumanPrompt: 'Please confirm',- stepCount: 2,- lastModified: new Date().toISOString(),- })- .mockResolvedValueOnce({- status: 'running',- stepCount: 1,- lastModified: new Date().toISOString(),- });-- const result = await service.getPendingInterventions({- userId: 'user-123',- });-- expect(result.totalCount).toBe(1);- expect(result.pendingInterventions[0]).toEqual({- operationId: 'operation-1',- type: 'human_prompt',- status: 'waiting_for_human',- pendingHumanPrompt: 'Please confirm',- stepCount: 2,- lastModified: expect.any(String),- userId: undefined, // getOperationMetadata is not called due to the way operations are filtered- modelRuntimeConfig: undefined,- });- });-- it('should return empty list when no interventions needed', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- status: 'running',- stepCount: 1,- });- mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: 'user-123' });-- const result = await service.getPendingInterventions({- operationId: 'test-operation-1',- });-- expect(result).toEqual({- totalCount: 0,- timestamp: expect.any(String),- pendingInterventions: [],- });- });- });-- describe('startExecution', () => {- const mockParams: StartExecutionParams = {- operationId: 'test-operation-1',- context: {- phase: 'user_input',- payload: {- message: { content: 'test' },- sessionId: 'test-operation-1',- isFirstMessage: false,- },- session: { sessionId: 'test-operation-1', status: 'idle', stepCount: 0, messageCount: 0 },- },- priority: 'high',- delay: 500,- };-- const mockState = {- operationId: 'test-operation-1',- status: 'idle',- stepCount: 2,- messages: [{ content: 'msg1' }],- lastModified: new Date().toISOString(),- };-- const mockMetadata = {- userId: 'user-123',- agentConfig: { name: 'test-agent' },- modelRuntimeConfig: { model: 'gpt-4' },- };-- beforeEach(() => {- mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);- mockCoordinator.loadAgentState.mockResolvedValue(mockState);- mockQueueService.scheduleMessage.mockResolvedValue('message-456');- });-- it('should start execution successfully', async () => {- const result = await service.startExecution(mockParams);-- expect(result).toEqual({- success: true,- scheduled: true,- operationId: 'test-operation-1',- messageId: 'message-456',- });-- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'test-operation-1',- expect.objectContaining({- status: 'running',- lastModified: expect.any(String),- }),- );-- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({- operationId: 'test-operation-1',- stepIndex: 2,- context: mockParams.context,- endpoint: 'http://localhost:3010/api/agent/run',- priority: 'high',- delay: 500,- });- });-- it('should create default context when none provided', async () => {- const paramsWithoutContext = { ...mockParams };- delete paramsWithoutContext.context;-- await service.startExecution(paramsWithoutContext);-- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({- operationId: 'test-operation-1',- stepIndex: 2,- context: expect.objectContaining({- phase: 'user_input',- payload: expect.objectContaining({- isFirstMessage: true,- message: [{ content: '' }], // message is now an array- }),- session: expect.objectContaining({- sessionId: 'test-operation-1',- status: 'idle',- stepCount: 2,- messageCount: 1,- }),- }),- endpoint: 'http://localhost:3010/api/agent/run',- priority: 'high', // Uses the provided priority from params- delay: 500, // Uses the provided delay from params- });- });-- it('should handle operation not found', async () => {- mockCoordinator.getOperationMetadata.mockResolvedValue(null);-- await expect(service.startExecution(mockParams)).rejects.toThrow(- 'Operation test-operation-1 not found',- );- });-- it('should handle already running operation', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...mockState,- status: 'running',- });-- await expect(service.startExecution(mockParams)).rejects.toThrow(- 'Operation test-operation-1 is already running',- );- });-- it('should handle completed operation', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...mockState,- status: 'done',- });-- await expect(service.startExecution(mockParams)).rejects.toThrow(- 'Operation test-operation-1 is already completed',- );- });-- it('should handle error state operation', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...mockState,- status: 'error',- });-- await expect(service.startExecution(mockParams)).rejects.toThrow(- 'Operation test-operation-1 is in error state',- );- });-- it('should reject restarting an interrupted operation', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...mockState,- status: 'interrupted',- });-- await expect(service.startExecution(mockParams)).rejects.toThrow(- 'Operation test-operation-1 is interrupted',- );- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });- });-- describe('processHumanIntervention', () => {- it('should process human intervention successfully', async () => {- mockQueueService.scheduleMessage.mockResolvedValue('message-789');-- const result = await service.processHumanIntervention({- operationId: 'test-operation-1',- stepIndex: 2,- action: 'approve',- approvedToolCall: { toolName: 'calculator', args: {} },- });-- expect(result).toEqual({- messageId: 'message-789',- });-- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({- operationId: 'test-operation-1',- stepIndex: 2,- context: undefined,- endpoint: 'http://localhost:3010/api/agent/run',- priority: 'high',- delay: 100,- payload: {- approvedToolCall: { toolName: 'calculator', args: {} },- humanInput: undefined,- rejectionReason: undefined,- },- });- });-- it('should handle different intervention actions', async () => {- mockQueueService.scheduleMessage.mockResolvedValue('message-890');-- await service.processHumanIntervention({- operationId: 'test-operation-1',- stepIndex: 3,- action: 'input',- humanInput: { type: 'text', content: 'user response' },- });-- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({- payload: expect.objectContaining({- humanInput: { type: 'text', content: 'user response' },- }),- }),- );- });- });-- describe('private methods', () => {- describe('shouldContinueExecution', () => {- it('should return false for completed status', () => {- const shouldContinue = (service as any).shouldContinueExecution(- { status: 'done' },- { phase: 'user_input' },- );- expect(shouldContinue).toBe(false);- });-- it('should return false for a plain interrupt with nothing left to settle', () => {- const shouldContinue = (service as any).shouldContinueExecution(- { status: 'interrupted' },- { phase: 'tool_result' },- );- expect(shouldContinue).toBe(false);- });-- it('should return false when waiting for human input', () => {- const shouldContinue = (service as any).shouldContinueExecution(- { status: 'waiting_for_human' },- { phase: 'user_input' },- );- expect(shouldContinue).toBe(false);- });-- it('should not check maxSteps — delegated to runtime.step()', () => {- // maxSteps is handled by runtime.step() which sets forceFinish → status:'done'- // shouldContinueExecution only checks status, not maxSteps- const shouldContinue = (service as any).shouldContinueExecution(- { status: 'running', maxSteps: 10, stepCount: 10 },- { phase: 'user_input' },- );- expect(shouldContinue).toBe(true);- });-- it('should continue when forceFinish is active even at maxSteps', () => {- // When runtime sets forceFinish, the service must allow one more step- // for the LLM to produce a final text response without tools- const shouldContinue = (service as any).shouldContinueExecution(- { status: 'running', maxSteps: 5, stepCount: 6, forceFinish: true },- { phase: 'llm_result' },- );- expect(shouldContinue).toBe(true);- });-- it('should return false when cost limit exceeded with stop action', () => {- const shouldContinue = (service as any).shouldContinueExecution(- {- status: 'running',- cost: { total: 1 },- costLimit: { maxTotalCost: 0.5, onExceeded: 'stop' },- },- { phase: 'user_input' },- );- expect(shouldContinue).toBe(false);- });-- it('should return true when cost limit exceeded with continue action', () => {- const shouldContinue = (service as any).shouldContinueExecution(- {- status: 'running',- cost: { total: 1 },- costLimit: { maxTotalCost: 0.5, onExceeded: 'continue' },- },- { phase: 'user_input' },- );- expect(shouldContinue).toBe(true);- });-- it('should return false when no context provided', () => {- const shouldContinue = (service as any).shouldContinueExecution(- { status: 'running' },- null,- );- expect(shouldContinue).toBe(false);- });-- it('should return true for normal running state', () => {- const shouldContinue = (service as any).shouldContinueExecution(- { status: 'running' },- { phase: 'user_input' },- );- expect(shouldContinue).toBe(true);- });- });-- describe('calculateStepDelay', () => {- it('should return base delay for normal step', () => {- const delay = (service as any).calculateStepDelay({- events: [{ type: 'llm_response' }],- });- expect(delay).toBe(50);- });-- it('should return longer delay for tool calls', () => {- const delay = (service as any).calculateStepDelay({- events: [{ type: 'tool_result' }],- });- expect(delay).toBe(100);- });-- it('should return exponential backoff delay for errors', () => {- const delay = (service as any).calculateStepDelay({- events: [{ type: 'error' }],- });- expect(delay).toBe(100);- });- });-- describe('calculatePriority', () => {- it('should return high priority for human input needed', () => {- const priority = (service as any).calculatePriority({- newState: { status: 'waiting_for_human' },- events: [],- });- expect(priority).toBe('high');- });-- it('should return normal priority for errors', () => {- const priority = (service as any).calculatePriority({- newState: { status: 'running' },- events: [{ type: 'error' }],- });- expect(priority).toBe('normal');- });-- it('should return normal priority by default', () => {- const priority = (service as any).calculatePriority({- newState: { status: 'running' },- events: [{ type: 'llm_response' }],- });- expect(priority).toBe('normal');- });- });- });-- describe('setQueuedMessages', () => {- it('writes the flag for an operation owned by the caller', async () => {- mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: mockUserId });- mockCoordinator.setQueuedMessages.mockResolvedValue(undefined);-- await expect(service.setQueuedMessages('op-1', true)).resolves.toBe(true);-- expect(mockCoordinator.setQueuedMessages).toHaveBeenCalledWith('op-1', true);- });-- it("refuses another user's operation", async () => {- mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: 'someone-else' });-- await expect(service.setQueuedMessages('op-1', true)).resolves.toBe(false);-- expect(mockCoordinator.setQueuedMessages).not.toHaveBeenCalled();- });-- it('refuses an unknown operation', async () => {- mockCoordinator.getOperationMetadata.mockResolvedValue(null);-- await expect(service.setQueuedMessages('op-missing', false)).resolves.toBe(false);-- expect(mockCoordinator.setQueuedMessages).not.toHaveBeenCalled();- });- });-- describe('interruptOperation', () => {- let findOperation: MockInstance<AgentOperationModel['findById']>;-- beforeEach(() => {- findOperation = vi.spyOn(AgentOperationModel.prototype, 'findById');- mockDb.select.mockReturnValue({- from: vi.fn().mockReturnValue({- where: vi.fn().mockReturnValue({ limit: vi.fn().mockResolvedValue([]) }),- }),- });- });-- afterEach(() => {- findOperation.mockRestore();- });-- it('should interrupt a running operation', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- operationId: 'op-1',- status: 'running',- stepCount: 3,- lastModified: new Date().toISOString(),- });-- const result = await service.interruptOperation('op-1');-- expect(result).toBe(true);- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'op-1',- expect.objectContaining({- status: 'interrupted',- lastModified: expect.any(String),- }),- );- expect(mockCoordinator.markInterrupted).toHaveBeenCalledWith('op-1');- // Sentinel must land before the state save: the step-boundary check- // reads only the sentinel, so state-first ordering would let a check- // between the two writes miss the interrupt and clobber it.- expect(mockCoordinator.markInterrupted.mock.invocationCallOrder[0]).toBeLessThan(- mockCoordinator.saveAgentState.mock.invocationCallOrder[0],- );- });-- it('should interrupt a waiting_for_human operation', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- operationId: 'op-2',- status: 'waiting_for_human',- stepCount: 1,- });-- const result = await service.interruptOperation('op-2');-- expect(result).toBe(true);- expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(- 'op-2',- expect.objectContaining({ status: 'interrupted' }),- );- });-- it('should return false when state and owned operation are not found', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);-- const result = await service.interruptOperation('non-existent');-- expect(result).toBe(false);- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();- expect(mockCoordinator.markInterrupted).not.toHaveBeenCalled();- });-- it('should acknowledge cancellation when operation already done', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- operationId: 'op-done',- status: 'done',- stepCount: 5,- });-- const result = await service.interruptOperation('op-done');-- expect(result).toBe(true);- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();- });-- it('should acknowledge cancellation when operation already in error state', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- operationId: 'op-err',- status: 'error',- stepCount: 2,- });-- const result = await service.interruptOperation('op-err');-- expect(result).toBe(true);- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();- });-- it('should acknowledge cancellation when operation already interrupted', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- operationId: 'op-int',- status: 'interrupted',- stepCount: 4,- });-- const result = await service.interruptOperation('op-int');-- expect(result).toBe(true);- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();- });-- it.each(['done', 'error', 'interrupted', 'abandoned'] as const)(- 'acknowledges an expired runtime state when the owned operation is %s',- async (status) => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- findOperation.mockResolvedValue({- id: 'op-expired',- status,- } as Awaited<ReturnType<AgentOperationModel['findById']>>);- expect(await service.interruptOperation('op-expired')).toBe(true);- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();- expect(mockCoordinator.markInterrupted).not.toHaveBeenCalled();- },- );-- it.each(['idle', 'running', 'waiting_for_human', 'waiting_for_async_tool'] as const)(- 'does not treat missing runtime state as stopped when the owned operation is %s',- async (status) => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- findOperation.mockResolvedValue({- id: 'op-active',- status,- } as Awaited<ReturnType<AgentOperationModel['findById']>>);- expect(await service.interruptOperation('op-active')).toBe(false);- expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();- expect(mockCoordinator.markInterrupted).not.toHaveBeenCalled();- },- );-- describe('running operation whose runtime state is gone', () => {- let settleStale: MockInstance<AgentOperationModel['settleStaleRunning']>;-- beforeEach(() => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- settleStale = vi.spyOn(AgentOperationModel.prototype, 'settleStaleRunning');- });-- afterEach(() => {- settleStale.mockRestore();- });-- it('retires a dead operation so the stop is confirmed', async () => {- const updatedAt = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);- findOperation.mockResolvedValue({- id: 'op-dead',- status: 'running',- updatedAt,- } as Awaited<ReturnType<AgentOperationModel['findById']>>);- settleStale.mockResolvedValue(true);-- expect(await service.interruptOperation('op-dead')).toBe(true);- expect(settleStale).toHaveBeenCalledWith('op-dead', expect.any(Date));- const staleBefore = settleStale.mock.calls[0][1];- expect(staleBefore.getTime()).toBeGreaterThan(updatedAt.getTime());- expect(staleBefore.getTime()).toBeLessThan(Date.now() - 5 * 60 * 1000);- });-- it('keeps refusing while the lease is fresh', async () => {- findOperation.mockResolvedValue({- id: 'op-live',- status: 'running',- updatedAt: new Date(Date.now() - 60 * 1000),- } as Awaited<ReturnType<AgentOperationModel['findById']>>);-- expect(await service.interruptOperation('op-live')).toBe(false);- expect(settleStale).not.toHaveBeenCalled();- });-- it('keeps refusing when a heartbeat wins the retirement race', async () => {- findOperation.mockResolvedValue({- id: 'op-race',- status: 'running',- updatedAt: new Date(Date.now() - 60 * 60 * 1000),- } as Awaited<ReturnType<AgentOperationModel['findById']>>);- settleStale.mockResolvedValue(false);-- expect(await service.interruptOperation('op-race')).toBe(false);- });- });- });-- // Stream events at step / operation boundaries should carry the canonical- // UIChatMessage[] snapshot so the client can use the pushed payload as- // Source of Truth instead of refetching from DB.- describe('queryUiMessages', () => {- const stubMessageService = (svc: any, queryMessages: ReturnType<typeof vi.fn>) => {- svc.messageServiceInstance = { queryMessages };- };-- it('returns messageService.queryMessages result when agentId + topicId are present', async () => {- const stubMessages = [{ id: 'msg_x', role: 'user' }];- const queryMessages = vi.fn().mockResolvedValue(stubMessages);- stubMessageService(service, queryMessages);-- const result = await service.queryUiMessages({- origin: { agentId: 'agt_1', topicId: 'tpc_1' },- } as any);-- expect(queryMessages).toHaveBeenCalledWith(- { agentId: 'agt_1', topicId: 'tpc_1' },- expect.anything(),- );- expect(result).toEqual(stubMessages);- });-- it('assembles a share visitor run snapshot under the visitor share Work scope', async () => {- // Regression: the visitor's Works are registered under their share scope,- // which the ordinary scope never resolves. Without it the terminal- // snapshot carried no Work card, so a sandbox-exported pptx only showed- // its card after the visitor reloaded the page.- const queryMessages = vi.fn().mockResolvedValue([]);- stubMessageService(service, queryMessages);-- await service.queryUiMessages({- origin: { agentId: 'agt_1', topicId: 'tpc_1' },- principal: {- actor: { shareVisitor: { shareId: 'share_1', visitorUserId: 'visitor_1' } },- },- } as any);-- expect(queryMessages).toHaveBeenCalledWith(- expect.objectContaining({ includeFileWorks: true, topicId: 'tpc_1' }),- {- allowShareVisitor: true,- workAccessScope: {- shareId: 'share_1',- topicId: 'tpc_1',- type: 'agentShare',- visitorUserId: 'visitor_1',- },- },- );- });-- it('keeps the ordinary Work scope and file-Work gate for a non-share run', async () => {- const queryMessages = vi.fn().mockResolvedValue([]);- stubMessageService(service, queryMessages);-- await service.queryUiMessages({ origin: { agentId: 'agt_1', topicId: 'tpc_1' } } as any);-- expect(queryMessages.mock.calls[0][0].includeFileWorks).toBeUndefined();- expect(queryMessages.mock.calls[0][1]).toEqual({ allowShareVisitor: true });- });-- it('includes file Works for an ordinary run whose client declared it renders them', async () => {- // Regression: an ordinary run's terminal snapshot/patch dropped the- // exported pptx card until the user reloaded the conversation.- const queryMessages = vi.fn().mockResolvedValue([]);- stubMessageService(service, queryMessages);-- await service.queryUiMessages({- host: { acceptsFileWorks: true },- origin: { agentId: 'agt_1', topicId: 'tpc_1' },- } as any);-- expect(queryMessages.mock.calls[0][0].includeFileWorks).toBe(true);- expect(queryMessages.mock.calls[0][1]).toEqual({ allowShareVisitor: true });- });-- it.each([undefined, 'visitor_1'])(- 'includes visitor rows (visitor=%s)',- async (visitorUserId) => {- // Regression: `MessageModel.query()` hides share-visitor messages by- // default. A visitor run executes under the creator's identity, so- // without the opt-in the terminal snapshot for the visitor's topic is- // `[]` and the client replaces the conversation it just streamed with- // nothing.- const queryMessages = vi.fn().mockResolvedValue([]);- stubMessageService(service, queryMessages);-- await service.queryUiMessages({- origin: { agentId: 'agt_1', topicId: 'tpc_1' },- principal: visitorUserId ? { actor: { shareVisitor: { visitorUserId } } } : undefined,- } as any);-- // The pushed snapshot always carries whole tool payloads now: it only- // reaches a client that did not ask for protocol 2, which has no way to- // fetch an omitted payload back.- expect(queryMessages).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ allowShareVisitor: true }),- );- },- );-- it('scopes the snapshot to the run thread when the operation is a subtopic run', async () => {- // Regression: without `threadId` the snapshot is the topic's MAIN- // conversation, and the client writes it into the thread's bucket at- // step_start / agent_runtime_end — wiping the turn the run just produced,- // so a freshly created subtopic renders the main conversation instead.- const queryMessages = vi.fn().mockResolvedValue([]);- stubMessageService(service, queryMessages);-- await service.queryUiMessages({- origin: { agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' },- } as any);-- expect(queryMessages).toHaveBeenCalledWith(- expect.objectContaining({ agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' }),- expect.anything(),- );- });-- it('leaves threadId unset for a main-conversation run', async () => {- const queryMessages = vi.fn().mockResolvedValue([]);- stubMessageService(service, queryMessages);-- await service.queryUiMessages({- origin: { agentId: 'agt_1', topicId: 'tpc_1' },- } as any);-- expect(queryMessages.mock.calls[0][0].threadId).toBeUndefined();- });-- it('returns undefined when agentId or topicId is missing (skips empty-array push)', async () => {- const queryMessages = vi.fn();- stubMessageService(service, queryMessages);-- const noAgent = await service.queryUiMessages({- origin: { topicId: 'tpc_1' },- } as any);- const noTopic = await service.queryUiMessages({- origin: { agentId: 'agt_1' },- } as any);- const noMeta = await service.queryUiMessages({} as any);-- expect(noAgent).toBeUndefined();- expect(noTopic).toBeUndefined();- expect(noMeta).toBeUndefined();- expect(queryMessages).not.toHaveBeenCalled();- });-- it('returns undefined and never throws when DB query fails (stream events must not fail the step)', async () => {- const queryMessages = vi.fn().mockRejectedValue(new Error('db down'));- stubMessageService(service, queryMessages);-- const result = await service.queryUiMessages({- origin: { agentId: 'agt_1', topicId: 'tpc_1' },- } as any);-- expect(result).toBeUndefined();- });- });-- describe('tryResumeParentFromAsyncTool', () => {- const parentOpId = 'parent-op-async';-- const fulfilledPlugin = { id: 'msg-tc1', state: { status: 'completed' }, toolCallId: 'tc1' };-- const stubFulfilled = () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [{ id: 'tc1' }],- status: 'waiting_for_async_tool',- stepCount: 3,- });- (service as any).serverDB.query = {- messagePlugins: { findFirst: vi.fn().mockResolvedValue(fulfilledPlugin) },- };- (service as any).messageModel.findById = vi.fn().mockResolvedValue({ content: 'answer' });- };-- it('wins the CAS and schedules the resume step when all pending tools are fulfilled', async () => {- stubFulfilled();- const casSpy = vi- .spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool')- .mockResolvedValue(true);-- const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });-- expect(won).toBe(true);- expect(casSpy).toHaveBeenCalledWith(parentOpId);- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({- operationId: parentOpId,- payload: { resumeAsyncTool: true },- priority: 'high',- stepIndex: 3,- }),- );- });-- it('holds (no CAS, no schedule) when a pending tool is not yet fulfilled', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [{ id: 'tc1' }],- status: 'waiting_for_async_tool',- stepCount: 1,- });- (service as any).serverDB.query = {- messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },- };- const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');-- const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });-- expect(won).toBe(false);- expect(casSpy).not.toHaveBeenCalled();- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('does not schedule when it loses the CAS to a concurrent sibling', async () => {- stubFulfilled();- vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool').mockResolvedValue(false);-- const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });-- expect(won).toBe(false);- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('skips when the parent is no longer parked', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [],- status: 'running',- stepCount: 1,- });- const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');-- const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });-- expect(won).toBe(false);- expect(casSpy).not.toHaveBeenCalled();- });-- it('arms the first verify (attempt 1, 15s) when the parent has not parked yet and scheduleVerifyOnHold is set', async () => {- // Child completed before the parent's parking step persisted its state.- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [],- status: 'running',- stepCount: 2,- });-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true },- );-- expect(won).toBe(false);- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({- delay: 15_000,- operationId: parentOpId,- payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },- stepIndex: 2,- }),- );- });-- it('arms a verify when the barrier is unsatisfied and scheduleVerifyOnHold is set', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [{ id: 'tc1' }],- status: 'waiting_for_async_tool',- stepCount: 1,- });- (service as any).serverDB.query = {- messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },- };-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true },- );-- expect(won).toBe(false);- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({- payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },- }),- );- });-- it('re-arms the next verify with exponential backoff while the barrier holds', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [{ id: 'tc1' }],- status: 'waiting_for_async_tool',- stepCount: 1,- });- (service as any).serverDB.query = {- messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },- };-- // A verify handler running as attempt 2 re-arms attempt 3 (60s).- await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true, verifyAttempt: 3 },- );-- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({- delay: 60_000,- payload: { asyncToolVerifyAttempt: 3, verifyAsyncToolBarrier: true },- }),- );- });-- it('stops re-arming once the bounded attempts are exhausted', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [{ id: 'tc1' }],- status: 'waiting_for_async_tool',- stepCount: 1,- });- (service as any).serverDB.query = {- messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },- };-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true, verifyAttempt: 6 },- );-- expect(won).toBe(false);- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('trusts a just-backfilled message id without re-reading it (read-your-writes)', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [{ id: 'tc1' }],- status: 'waiting_for_async_tool',- stepCount: 3,- });- // Plugin row exists (created at park) but its state still reads stale.- const findById = vi.fn().mockResolvedValue({ content: '' });- (service as any).serverDB.query = {- messagePlugins: {- findFirst: vi.fn().mockResolvedValue({ id: 'msg-tc1', state: null, toolCallId: 'tc1' }),- },- };- (service as any).messageModel.findById = findById;- const casSpy = vi- .spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool')- .mockResolvedValue(true);-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { knownFulfilledMessageId: 'msg-tc1' },- );-- expect(won).toBe(true);- expect(casSpy).toHaveBeenCalledWith(parentOpId);- // The stale read must be skipped — barrier trusted the local backfill.- expect(findById).not.toHaveBeenCalled();- });-- it('arms a fallback verify when a parked op has no pending tools', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [],- status: 'waiting_for_async_tool',- stepCount: 4,- });- const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true },- );-- expect(won).toBe(false);- expect(casSpy).not.toHaveBeenCalled();- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({- payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },- stepIndex: 4,- }),- );- });-- it('does not arm a verify for terminal parent states', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [],- status: 'done',- stepCount: 5,- });-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true },- );-- expect(won).toBe(false);- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('arms a verify when the parent state is missing/expired and scheduleVerifyOnHold is set', async () => {- // Redis read replica hasn't seen the park yet, or the child outran the- // parent's park. A missing state must retry, not strand on the first miss.- mockCoordinator.loadAgentState.mockResolvedValue(null);- const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true },- );-- expect(won).toBe(false);- expect(casSpy).not.toHaveBeenCalled();- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({- operationId: parentOpId,- payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },- // No state to read stepCount from — falls back to 0.- stepIndex: 0,- }),- );- });-- it('does not arm a verify on missing state when scheduleVerifyOnHold is not set', async () => {- // The clean-done bridge path resumes without opting into the watchdog;- // a missing state there must stay a silent no-op, not schedule a re-check.- mockCoordinator.loadAgentState.mockResolvedValue(null);-- const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });-- expect(won).toBe(false);- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('stops re-arming on missing state once the bounded attempts are exhausted', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);-- const won = await service.tryResumeParentFromAsyncTool(- { parentOperationId: parentOpId },- { scheduleVerifyOnHold: true, verifyAttempt: 6 },- );-- expect(won).toBe(false);- expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();- });-- it('schedules a finish step when the parked tool requests onComplete=finish (skipCallSupervisor / delegate)', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- pendingToolsCalling: [{ id: 'tc1' }],- status: 'waiting_for_async_tool',- stepCount: 4,- });- (service as any).serverDB.query = {- messagePlugins: {- findFirst: vi.fn().mockResolvedValue({- id: 'msg-tc1',- state: { onComplete: 'finish', status: 'completed' },- toolCallId: 'tc1',- }),- },- };- (service as any).messageModel.findById = vi.fn().mockResolvedValue({ content: 'answer' });- vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool').mockResolvedValue(true);-- const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });-- expect(won).toBe(true);- expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({ payload: { finishAfterAsyncTool: true }, stepIndex: 4 }),- );- });- });-- describe('loadGroupMemberBridge', () => {- const bridge = {- anchorMessageId: 'msg-speak',- expectedMembers: 1,- groupToolMessageId: 'msg-speak',- mode: 'isolated',- onComplete: 'resume',- parentOperationId: 'op-supervisor',- threadId: 'thd-1',- };-- it('reads the member and its bridge from the live runtime snapshot', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- host: { hooks: [{ id: 'group-member-bridge', webhook: { body: bridge } }] },- origin: {- agentId: 'agt-carol',- groupId: 'cg-1',- lineage: { orchestrationRole: 'member' },- threadId: 'thd-1',- topicId: 'tpc-1',- },- });-- expect(await service.loadGroupMemberBridge('op-carol')).toEqual({- agentId: 'agt-carol',- bridge,- groupId: 'cg-1',- threadId: 'thd-1',- topicId: 'tpc-1',- });- });-- it('falls back to the durable row once the snapshot has expired', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({- agentId: 'agt-carol',- chatGroupId: 'cg-1',- metadata: { groupMemberBridge: bridge },- threadId: 'thd-1',- topicId: 'tpc-1',- });-- expect(await service.loadGroupMemberBridge('op-carol')).toEqual({- agentId: 'agt-carol',- bridge,- groupId: 'cg-1',- threadId: 'thd-1',- topicId: 'tpc-1',- });- });-- it('is undefined for a run that is not a group member', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({- agentId: 'agt-solo',- metadata: {},- });-- expect(await service.loadGroupMemberBridge('op-solo')).toBeUndefined();- });- });-- describe('completeGroupActionMember', () => {- const memberState = {- messages: [- { content: 'question', role: 'user' },- { content: 'final answer', role: 'assistant' },- ],- origin: { agentId: 'agent-a' },- modelRuntimeConfig: { model: 'gpt-test' },- status: 'done',- usage: { llm: { tokens: { total: 42 } }, tools: { totalCalls: 2 } },- };-- let updateToolMessage: ReturnType<typeof vi.fn>;- let resumeSpy: MockInstance<AgentRuntimeService['tryResumeParentFromAsyncTool']>;-- beforeEach(() => {- vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({- metadata: { _hooks: [] },- });- updateToolMessage = vi.fn().mockResolvedValue({ success: true });- (service as any).messageModel.updateToolMessage = updateToolMessage;- resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);- });-- // G-05 follow-through: a member that inherits manual approval parks on- // `waiting_for_human`; that is a pause, not an answer, so the supervisor- // must stay parked until the approval continuation reports back.- it.each(['in_group', 'isolated'] as const)(- 'holds the supervisor while a %s member waits for approval',- async (mode) => {- const won = await service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- finalState: { ...memberState, status: 'waiting_for_human' } as any,- groupToolMessageId: 'grp-tool-1',- mode,- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'waiting_for_human',- });-- expect(won).toBe(false);- expect(updateToolMessage).not.toHaveBeenCalled();- expect(resumeSpy).not.toHaveBeenCalled();- },- );-- it('single in-group member: backfills a receipt onto the group tool and resumes', async () => {- const won = await service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- finalState: memberState as any,- groupToolMessageId: 'grp-tool-1',- mode: 'in_group',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- });-- expect(won).toBe(true);- expect(updateToolMessage).toHaveBeenCalledWith(- 'grp-tool-1',- expect.objectContaining({- content: 'Agent agent-a responded in the group.',- pluginState: expect.objectContaining({ status: 'completed' }),- }),- );- expect(resumeSpy).toHaveBeenCalledWith(- { parentOperationId: 'parent-1' },- { scheduleVerifyOnHold: true },- );- });-- it('single isolated member: backfills the final answer', async () => {- await service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- finalState: memberState as any,- groupToolMessageId: 'grp-tool-1',- mode: 'isolated',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'grp-tool-1',- expect.objectContaining({ content: 'final answer' }),- );- });-- it('single isolated member: extracts the final answer from an assistantGroup', async () => {- await service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- finalState: {- ...memberState,- messages: [- { content: 'question', role: 'user' },- {- children: [- {- content: '',- id: 'assistant-tools',- tools: [- {- id: 'tool-call-1',- result: { content: 'tool result', id: 'tool-result-1' },- },- ],- },- { content: 'grouped member answer', id: 'assistant-final' },- ],- content: '',- id: 'assistant-group',- role: 'assistantGroup',- },- ],- } as any,- groupToolMessageId: 'grp-tool-1',- mode: 'isolated',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'grp-tool-1',- expect.objectContaining({ content: 'grouped member answer' }),- );- });-- it('single isolated member: extracts serialized multimodal text after DB rehydration', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...memberState,- messages: undefined,- });- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain(- JSON.stringify([- { text: 'persisted member answer', type: 'text' },- { image: 'https://example.com/image.png', type: 'image' },- ]),- { isMultimodal: true },- ),- );-- await service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- groupToolMessageId: 'grp-tool-1',- mode: 'isolated',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'grp-tool-1',- expect.objectContaining({ content: 'persisted member answer' }),- );- });-- // Regression: same as completeSubAgentBridge's hetero case — a- // heterogeneous isolated member never populates the coordinator's- // runtime state at all, so `loadAgentState` genuinely resolves `null`.- // Recover the real answer from the member's own isolation thread instead- // of falling through to the "no textual answer" stub.- it('single isolated member: recovers the answer from the isolation thread when the coordinator has no state at all (hetero)', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain('hello from the CLI'),- );-- await service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- groupToolMessageId: 'grp-tool-1',- mode: 'isolated',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- threadId: 'thread-1',- });-- expect((service as any).messageModel.query).toHaveBeenCalledWith(- { threadId: 'thread-1' },- { allowShareVisitor: true },- );- expect(updateToolMessage).toHaveBeenCalledWith(- 'grp-tool-1',- expect.objectContaining({ content: 'hello from the CLI' }),- );- });-- // Mirrors completeSubAgentBridge's identical Codex-flagged regression:- // the thread fallback must be gated on `!finalState`, not merely an- // empty `lastAssistantContent` — a real finalState whose last turn is- // legitimately textless must keep the stub, not risk a stale earlier- // reply from the thread's own history.- it('single isolated member: does not query the thread when a real finalState already says the final turn is textless', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...memberState,- messages: undefined,- });- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain(- JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),- { isMultimodal: true },- ),- );- const threadFallbackSpy = vi.spyOn(service as any, 'resolveLastAssistantContentFromThread');-- await service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- groupToolMessageId: 'grp-tool-1',- mode: 'isolated',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- threadId: 'thread-1',- });-- expect(threadFallbackSpy).not.toHaveBeenCalled();- expect(updateToolMessage).toHaveBeenCalledWith(- 'grp-tool-1',- expect.objectContaining({ content: 'Agent member completed without a textual answer.' }),- );- });-- it('multi-member: holds (no group-tool backfill, no resume) until the barrier is met', async () => {- (service as any).serverDB.query = {- messagePlugins: { findFirst: vi.fn() },- messages: {- findMany: vi- .fn()- .mockResolvedValue([{ content: 'a note', id: 'anchor-0', role: 'tool' }]),- },- };- mockCoordinator.loadAgentState.mockResolvedValue({- status: 'waiting_for_async_tool',- stepCount: 1,- });-- const won = await service.completeGroupActionMember({- anchorMessageId: 'anchor-0',- expectedMembers: 2,- finalState: memberState as any,- groupToolMessageId: 'grp-tool-1',- mode: 'in_group',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- });-- expect(won).toBe(false);- expect(updateToolMessage).toHaveBeenCalledWith('anchor-0', expect.anything());- expect(updateToolMessage).not.toHaveBeenCalledWith('grp-tool-1', expect.anything());- expect(resumeSpy).not.toHaveBeenCalled();- });-- it('multi-member: last completion backfills the group tool and resumes', async () => {- (service as any).serverDB.query = {- messagePlugins: { findFirst: vi.fn() },- messages: {- findMany: vi.fn().mockResolvedValue([- { content: 'a', id: 'anchor-0', role: 'tool' },- { content: 'b', id: 'anchor-1', role: 'tool' },- ]),- },- };-- const won = await service.completeGroupActionMember({- anchorMessageId: 'anchor-1',- expectedMembers: 2,- finalState: memberState as any,- groupToolMessageId: 'grp-tool-1',- mode: 'in_group',- onComplete: 'resume',- operationId: 'child-2',- parentOperationId: 'parent-1',- reason: 'done',- });-- expect(won).toBe(true);- expect(updateToolMessage).toHaveBeenCalledWith('anchor-1', expect.anything());- expect(updateToolMessage).toHaveBeenCalledWith(- 'grp-tool-1',- expect.objectContaining({- content: 'All 2 agent members completed.',- pluginState: expect.objectContaining({ status: 'completed' }),- }),- );- expect(resumeSpy).toHaveBeenCalled();- });-- it('completes a multi-member empty-reason denial and retains it after callback replay', async () => {- const privateContent = 'synthetic-private-member-answer';- const defaultReason = 'Blocked by afterToolCall hook.';- const anchors = [- { id: 'anchor-0', content: '', state: {} },- { id: 'anchor-1', content: '', state: {} },- ];- const group = { id: 'grp-tool-1', parentId: 'assistant', content: '', state: {} };- const rows = [...anchors, group];- (service as any).serverDB.query = {- messages: { findMany: vi.fn(async () => anchors) },- messagePlugins: { findFirst: vi.fn().mockResolvedValue({ state: {} }) },- };- (service as any).messageModel.findById = vi.fn(async (id) =>- rows.find((row) => row.id === id),- );- (service as any).messageModel.findMessagePlugin = vi.fn(async (id) => ({- id,- toolCallId: 'group-call',- identifier: 'lobe-group-management',- apiName: 'executeAgentTasks',- arguments: '{}',- }));- updateToolMessage.mockImplementation(async (id, value) => {- const row = rows.find((row) => row.id === id)!;- if (row.content && value.onlyIfEmpty) return { success: true, applied: false };- row.content = value.content;- row.state = value.pluginState;- return { success: true, applied: true };- });- mockCoordinator.loadAgentState.mockResolvedValue({- operationId: 'parent-1',- stepCount: 1,- status: 'waiting_for_async_tool',- host: {- hooks: [- {- id: 'after-control',- type: 'afterToolCall',- webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },- },- ],- },- });- const fetchHook = vi- .spyOn(globalThis, 'fetch')- .mockImplementation(- async () => new Response(JSON.stringify({ decision: 'deny', reason: '' })),- );- const complete = (anchorMessageId: string) =>- service.completeGroupActionMember({- anchorMessageId,- expectedMembers: 2,- finalState: {- ...memberState,- messages: [{ role: 'assistant', content: privateContent }],- } as any,- groupToolMessageId: group.id,- mode: 'isolated',- onComplete: 'resume',- operationId: `child-${anchorMessageId}`,- parentOperationId: 'parent-1',- reason: 'done',- });- try {- expect(await complete('anchor-0')).toBe(false);- expect(resumeSpy).not.toHaveBeenCalled();- expect(await complete('anchor-1')).toBe(true);- expect(resumeSpy).toHaveBeenCalledTimes(1);- expect(fetchHook).toHaveBeenCalledTimes(3);- expect(rows.every((row) => row.content === defaultReason)).toBe(true);- expect(JSON.stringify(rows)).not.toContain(privateContent);-- mockCoordinator.loadAgentState.mockResolvedValue(null);- await complete('anchor-0');- expect(fetchHook).toHaveBeenCalledTimes(3);- expect(rows.every((row) => row.content === defaultReason)).toBe(true);- expect(JSON.stringify(rows)).not.toContain(privateContent);- } finally {- fetchHook.mockRestore();- }- });-- it('throws when the anchor backfill fails so the webhook redelivers', async () => {- updateToolMessage.mockResolvedValue({ success: false });-- await expect(- service.completeGroupActionMember({- anchorMessageId: 'grp-tool-1',- expectedMembers: 1,- finalState: memberState as any,- groupToolMessageId: 'grp-tool-1',- mode: 'in_group',- onComplete: 'resume',- operationId: 'child-1',- parentOperationId: 'parent-1',- reason: 'done',- }),- ).rejects.toThrow(/failed to backfill anchor/);- expect(resumeSpy).not.toHaveBeenCalled();- });- });-- describe('completeSubAgentBridge', () => {- const bridgeParams = {- operationId: 'child-op-1',- parentOperationId: 'parent-op-1',- reason: 'done',- threadId: 'thread-1',- toolMessageId: 'tool-msg-1',- };-- const childState = {- messages: [- { content: 'question', role: 'user' },- { content: 'final answer', role: 'assistant' },- ],- modelRuntimeConfig: { model: 'gpt-test' },- status: 'done',- usage: { llm: { tokens: { total: 42 } }, tools: { totalCalls: 2 } },- };-- let updateToolMessage: ReturnType<typeof vi.fn>;- let resumeSpy: MockInstance<AgentRuntimeService['tryResumeParentFromAsyncTool']>;-- beforeEach(() => {- vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({- metadata: { _hooks: [] },- });- updateToolMessage = vi.fn().mockResolvedValue({ success: true });- (service as any).messageModel.updateToolMessage = updateToolMessage;- resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);- });-- it('backfills the tool message from finalState and resumes with scheduleVerifyOnHold', async () => {- const won = await service.completeSubAgentBridge({- ...bridgeParams,- finalState: childState as any,- });-- expect(won).toBe(true);- expect(updateToolMessage).toHaveBeenCalledWith('tool-msg-1', {- onlyIfEmpty: true,- content: 'final answer',- pluginError: null,- pluginState: {- model: 'gpt-test',- status: 'completed',- threadId: 'thread-1',- totalToolCalls: 2,- totalTokens: 42,- },- });- expect(resumeSpy).toHaveBeenCalledWith(- { parentOperationId: 'parent-op-1' },- { knownFulfilledMessageId: 'tool-msg-1', scheduleVerifyOnHold: true },- );- });-- it.each([- {- reason: 'The child result is restricted by policy.',- expected: 'The child result is restricted by policy.',- },- { reason: '', expected: 'Blocked by afterToolCall hook.' },- ])(- 'gates deferred output before backfill and parent resume, including callback replay, reason=$reason',- async ({ reason, expected: denialReason }) => {- const privateContent = 'synthetic-private-child-answer';- const stored = {- id: 'tool-msg-1',- identifier: 'lobe-agent',- apiName: 'callSubAgent',- arguments: '{"instruction":"original"}',- toolCallId: 'native-child',- state: {},- };- (service as any).messageModel.findMessagePlugin = vi.fn(async () => stored);- (service as any).messageModel.findById = vi- .fn()- .mockResolvedValue({ id: 'tool-msg-1', parentId: 'assistant' });- const fetchHook = vi- .spyOn(globalThis, 'fetch')- .mockImplementation(- async () => new Response(JSON.stringify({ decision: 'deny', reason })),- );- const hooks = [- {- id: 'after-control',- type: 'afterToolCall',- webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },- },- ];- mockCoordinator.loadAgentState.mockResolvedValue({- operationId: 'parent-op-1',- stepCount: 3,- host: { hooks },- });- updateToolMessage.mockImplementation(async (_id, value) => {- if ((stored as any).content && value.onlyIfEmpty)- return { success: true, applied: false };- (stored as any).content = value.content;- stored.state = value.pluginState;- (service as any).messageModel.findById.mockResolvedValue({- id: 'tool-msg-1',- parentId: 'assistant',- content: value.content,- });- return { success: true };- });- try {- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: {- ...childState,- messages: [{ role: 'assistant', content: privateContent }],- } as any,- });- expect(JSON.parse(String(fetchHook.mock.calls[0][1]?.body))).toMatchObject({- args: { instruction: 'original' },- toolCallId: 'native-child',- result: { content: expect.stringContaining(privateContent) },- });- expect(JSON.stringify(updateToolMessage.mock.calls)).not.toContain(privateContent);- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({- content: denialReason,- pluginError: 'hook_denied',- pluginState: expect.objectContaining({- phase: 'afterToolCall',- reason: denialReason,- type: 'blocked',- }),- replacePluginState: true,- onlyIfEmpty: true,- }),- );- expect(resumeSpy).toHaveBeenCalledTimes(1);- // A duplicate callback cannot restore the raw child answer after configuration removal.- mockCoordinator.loadAgentState.mockResolvedValue(null);- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: {- ...childState,- messages: [{ role: 'assistant', content: privateContent }],- } as any,- });- expect(fetchHook).toHaveBeenCalledTimes(1);- expect((stored as any).content).toBe(denialReason);- expect(stored.state).toMatchObject({ reason: denialReason, type: 'blocked' });- expect(JSON.stringify(stored.state)).not.toContain(privateContent);- } finally {- fetchHook.mockRestore();- }- },- );-- it('ends a callSubAgent result with the sub-agent id so the parent can continue it', async () => {- (service as any).messageModel.findMessagePlugin = vi- .fn()- .mockResolvedValue({ apiName: 'callSubAgent', identifier: 'lobe-agent' });-- await service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any });- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: { ...childState, error: { message: 'Budget exceeded' } } as any,- reason: 'error',- });-- expect(updateToolMessage).toHaveBeenNthCalledWith(- 1,- 'tool-msg-1',- expect.objectContaining({ content: 'final answer\n\n<sub_agent id="thread-1" />' }),- );- expect(updateToolMessage).toHaveBeenNthCalledWith(- 2,- 'tool-msg-1',- expect.objectContaining({- content: expect.stringMatching(- /^Sub-agent did not complete \(error\): .*\n\n<sub_agent id="thread-1" \/>$/,- ),- }),- );- });-- it('leaves callAgent results without a sub-agent id', async () => {- (service as any).messageModel.findMessagePlugin = vi- .fn()- .mockResolvedValue({ apiName: 'callAgent', identifier: 'lobe-agent-management' });-- await service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'final answer' }),- );- });-- it('loads the child state from the coordinator when finalState is not passed (webhook path)', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(childState);-- await service.completeSubAgentBridge(bridgeParams);-- expect(mockCoordinator.loadAgentState).toHaveBeenCalledWith('child-op-1');- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'final answer' }),- );- });-- // Regression: a heterogeneous (CLI-driven) child never populates the- // coordinator's Redis-backed runtime state at all — `loadAgentState`- // genuinely resolves `null` for it, unlike the standard-runtime case- // above where it resolves a real (if message-stripped) state object.- // Without a thread-scoped fallback this always fell through to "Sub-agent- // completed without a textual answer.", even though the CLI produced a- // real reply — because the webhook's `eventFields` deliberately excludes- // `lastAssistantContent` (see `createSubAgentBridgeHook`) and hetero never- // writes into the coordinator, so nothing else could ever supply it.- it('recovers the answer from the isolation thread when the coordinator has no state at all (hetero)', async () => {- mockCoordinator.loadAgentState.mockResolvedValue(null);- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain('hello from the CLI'),- );-- await service.completeSubAgentBridge(bridgeParams);-- expect((service as any).messageModel.query).toHaveBeenCalledWith(- { threadId: 'thread-1' },- { allowShareVisitor: true },- );- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'hello from the CLI' }),- );- });-- it('extracts a grouped final answer after webhook state is rehydrated from the DB', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...childState,- messages: undefined,- });- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain('final answer after tool use'),- );-- await service.completeSubAgentBridge(bridgeParams);-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'final answer after tool use' }),- );- });-- it('extracts text from serialized multimodal content after DB query and group parsing', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...childState,- messages: undefined,- });- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain(- JSON.stringify([- { text: 'persisted multimodal answer', type: 'text' },- { image: 'https://example.com/image.png', type: 'image' },- ]),- { isMultimodal: true },- ),- );-- await service.completeSubAgentBridge(bridgeParams);-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'persisted multimodal answer' }),- );- });-- it('uses the no-text fallback for an image-only serialized final assistant', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...childState,- messages: undefined,- });- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain(- JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),- { isMultimodal: true },- ),- );-- await service.completeSubAgentBridge(bridgeParams);-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),- );- });-- // Regression for a Codex review finding on the thread-fallback above: it- // must be gated on `!finalState` (no authoritative state at all — the- // heterogeneous case), not merely an empty `lastAssistantContent`.- // Otherwise a REAL, authoritative finalState whose last turn is- // legitimately textless would still trigger the thread re-query, and a- // lagging read that surfaces an EARLIER real reply from the same thread- // would silently show stale text instead of the correct empty-answer- // stub.- it('does not query the thread when a real finalState already says the final turn is textless', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({- ...childState,- messages: undefined,- });- (service as any).messageModel.query.mockResolvedValue(- buildPersistedToolChain(- JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),- { isMultimodal: true },- ),- );- const threadFallbackSpy = vi.spyOn(service as any, 'resolveLastAssistantContentFromThread');-- await service.completeSubAgentBridge(bridgeParams);-- expect(threadFallbackSpy).not.toHaveBeenCalled();- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),- );- });-- it('extracts text parts from the grouped final assistant content', async () => {- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: {- ...childState,- messages: [- {- children: [- {- content: [- { text: 'final answer', type: 'text' },- { image_url: { url: 'https://example.com/image.png' }, type: 'image_url' },- ],- id: 'assistant-final',- },- ],- content: '',- id: 'assistant-group',- role: 'assistantGroup',- },- ],- } as any,- });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'final answer' }),- );- });-- it('does not fall back to stale text when the grouped final assistant is empty', async () => {- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: {- ...childState,- messages: [- { content: 'stale answer', id: 'assistant-stale', role: 'assistant' },- { content: 'follow-up', id: 'user-follow-up', role: 'user' },- {- children: [{ content: '', id: 'assistant-final' }],- content: '',- id: 'assistant-group',- role: 'assistantGroup',- },- ],- } as any,- });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),- );- });-- it('writes an error note + pluginError when the child failed, surfacing the real reason', async () => {- // The parent agent's LLM only sees `content`; without the inlined reason it- // gets the opaque generic note and cannot tell why the dispatch failed- // (issue #16257). The structured error still rides on pluginError.- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: { ...childState, error: { message: 'boom' } } as any,- reason: 'error',- });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({- content: 'Sub-agent did not complete (error): boom',- pluginError: { message: 'boom' },- pluginState: expect.objectContaining({ status: 'error' }),- }),- );- });-- it('falls back to the generic note when the failed child has no error detail', async () => {- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: { ...childState, error: undefined } as any,- reason: 'error',- });-- expect(updateToolMessage).toHaveBeenCalledWith(- 'tool-msg-1',- expect.objectContaining({- content: 'Sub-agent did not complete (error).',- pluginState: expect.objectContaining({ status: 'error' }),- }),- );- });-- // A watchdog-abandoned child's reloaded state has no error; the abandon- // hand-off passes it explicitly. Without it the parent got a bare "(error).".- it('explains a watchdog-abandoned child from the hand-off error message', async () => {- await service.completeSubAgentBridge({- ...bridgeParams,- errorMessage: 'Operation abandoned: inactivity_watchdog',- finalState: { ...childState, error: undefined } as any,- reason: 'error',- });-- const call = updateToolMessage.mock.calls.at(-1)?.[1];- expect(call.content).toBe(- 'Sub-agent did not complete (error): the sub-agent stopped making progress and the platform ended it (inactivity_watchdog). ' +- 'Anything it already did (searches, pages read, documents written) is kept in its thread.',- );- expect(call.pluginError).toEqual({ message: 'Operation abandoned: inactivity_watchdog' });- });-- // "Budget exceeded" alone reads like a per-sub-agent allowance, so parents- // retried or fanned out more sub-agents against the same exhausted limit.- describe('billing-limit failures', () => {- const budgetError = (type: string, budgetTypeAtError?: string) => ({- body: {- budget: {- availableCredits: 24_659,- budgetTypeAtError,- requiredCredits: 50_638,- },- message: 'Budget exceeded',- },- message: 'Budget exceeded',- type,- });- const bridgeContent = async (error: unknown) => {- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: { ...childState, error } as any,- reason: 'error',- });- return updateToolMessage.mock.calls.at(-1)?.[1];- };-- it('explains a personal credit shortfall without quoting the balance', async () => {- const error = budgetError('InsufficientBudgetForModel', 'subscription');- const call = await bridgeContent(error);-- expect(call.content).toBe(- 'Sub-agent did not complete (error): stopped by a LobeHub billing limit (InsufficientBudgetForModel): ' +- "the account's LobeHub credits are too low for this model; the account owner has to top up or upgrade. " +- 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents on the same model will not get past it; ' +- 'a sub-agent that runs on a less expensive model may still fit. ' +- 'Otherwise finish with what you already have and tell the user about the limit.',- );- expect(call.content).not.toMatch(/24659|24,659|50638/);- expect(call.pluginError).toEqual(error);- });-- it.each([- [- 'workspace',- "the workspace's shared LobeHub credits can't cover this model's estimated cost",- ],- [- 'workspace_member',- "this member's workspace credit allowance can't cover this model's estimated cost",- ],- ])('names the %s allowance as the one to raise', async (scope, expected) => {- const call = await bridgeContent(budgetError('InsufficientBudgetForModel', scope));-- expect(call.content).toContain(expected);- expect(call.content).not.toContain('top up');- });-- it('points plan-limit failures at the plan, not at credits', async () => {- const call = await bridgeContent(budgetError('SubscriptionPlanLimit', 'subscription'));-- expect(call.content).toContain(- 'plan limit was reached or the plan does not cover this model',- );- });-- // InsufficientBudgetForModel still leaves credits in the allowance, so a- // cheaper model can fit; only an exhausted plan makes every dispatch futile.- it('keeps the cheaper-model path open for a model-cost shortfall only', async () => {- const shortfall = await bridgeContent(- budgetError('InsufficientBudgetForModel', 'workspace_member'),- );- expect(shortfall.content).toContain('on the same model will not get past it');- expect(shortfall.content).toContain('less expensive model may still fit');-- const exhausted = await bridgeContent(budgetError('FreePlanLimit', 'workspace'));- expect(exhausted.content).toContain("the workspace's shared LobeHub credits are used up");- expect(exhausted.content).toContain('more sub-agents will not get past it');- expect(exhausted.content).not.toContain('less expensive model');- });- });-- it('truncates an oversized child error so it cannot bloat the parent context', async () => {- const huge = 'x'.repeat(500);- await service.completeSubAgentBridge({- ...bridgeParams,- finalState: { ...childState, error: { message: huge } } as any,- reason: 'error',- });-- const call = updateToolMessage.mock.calls.at(-1)?.[1];- expect(call.content).toBe(`Sub-agent did not complete (error): ${'x'.repeat(300)}…`);- });-- it('throws when the backfill reports success: false so the webhook path redelivers', async () => {- // updateToolMessage swallows transaction errors into { success: false } —- // acking 200 here would strand the parent: the barrier stays unsatisfied- // and QStash never retries an acknowledged delivery.- updateToolMessage.mockResolvedValue({ success: false });-- await expect(- service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any }),- ).rejects.toThrow(/failed to backfill/);- expect(resumeSpy).not.toHaveBeenCalled();- });-- it('propagates backfill infrastructure errors for the same redelivery', async () => {- updateToolMessage.mockRejectedValue(new Error('db down'));-- await expect(- service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any }),- ).rejects.toThrow('db down');- expect(resumeSpy).not.toHaveBeenCalled();- });- });-- describe('resolveAsyncToolOnComplete', () => {- it('returns finish when ANY pending tool requests finish (not just the first)', async () => {- // First pending tool resumes; a later one is a group finish action. The- // disposition must scan all pending tools, not only pending[0].- (service as any).serverDB.query = {- messagePlugins: {- findFirst: vi- .fn()- .mockResolvedValueOnce({ state: { status: 'completed' } })- .mockResolvedValueOnce({ state: { onComplete: 'finish', status: 'completed' } }),- },- };-- const result = await (service as any).resolveAsyncToolOnComplete([- { id: 'tc1' },- { id: 'tc2' },- ]);-- expect(result).toBe('finish');- });-- it('returns resume when no pending tool requests finish', async () => {- (service as any).serverDB.query = {- messagePlugins: {- findFirst: vi.fn().mockResolvedValue({ state: { status: 'completed' } }),- },- };-- const result = await (service as any).resolveAsyncToolOnComplete([- { id: 'tc1' },- { id: 'tc2' },- ]);-- expect(result).toBe('resume');- });- });-- describe('group member timeout watchdog', () => {- const timeoutParams = {- anchorMessageId: 'anchor-1',- expectedMembers: 1,- groupToolMessageId: 'grp-tool-1',- memberOperationId: 'member-op-1',- mode: 'isolated' as const,- onComplete: 'resume' as const,- parentOperationId: 'parent-1',- };-- it('no-ops when the member already reached a terminal state', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({ status: 'done' });- const interruptSpy = vi.spyOn(service, 'interruptOperation');- const bridgeSpy = vi.spyOn(service, 'completeGroupActionMember');-- const result = await service.executeStep({- groupMemberTimeout: timeoutParams,- operationId: 'member-op-1',- stepIndex: 0,- } as any);-- expect(result.success).toBe(true);- expect(result.nextStepScheduled).toBe(false);- expect(interruptSpy).not.toHaveBeenCalled();- expect(bridgeSpy).not.toHaveBeenCalled();- });-- it('interrupts the member and bridges a timeout when it is still running', async () => {- mockCoordinator.loadAgentState.mockResolvedValue({ status: 'running' });- const interruptSpy = vi.spyOn(service, 'interruptOperation').mockResolvedValue(true);- const bridgeSpy = vi.spyOn(service, 'completeGroupActionMember').mockResolvedValue(true);-- const result = await service.executeStep({- groupMemberTimeout: timeoutParams,- operationId: 'member-op-1',- stepIndex: 0,- } as any);-- expect(interruptSpy).toHaveBeenCalledWith('member-op-1');- expect(bridgeSpy).toHaveBeenCalledWith(- expect.objectContaining({- onComplete: 'resume',- operationId: 'member-op-1',- parentOperationId: 'parent-1',- reason: 'timeout',- }),- );- expect(result.nextStepScheduled).toBe(true);- });- });-});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsdeleted file mode 100644index 447f65c7ea3..00000000000--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ /dev/null@@ -1,5526 +0,0 @@-import { randomUUID } from 'node:crypto';--import type {- Agent,- AgentRunClientLlmWait,- AgentRunLlmExecutor,- AgentRuntimeContext,- AgentState,- GeneralAgentConfig,- ToolCallHookEvent,- ToolForwardingRequest,- ToolRunResult,-} from '@lobechat/agent-runtime';-import {- AgentRuntime,- extractActivatedToolIdsFromMessages,- findInMessages,- GeneralChatAgent,- isParkedStatus,-} from '@lobechat/agent-runtime';-import type { ISnapshotStore } from '@lobechat/agent-tracing';-import { DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';-import { appendSubAgentReference, isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';-import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';-import { ABANDONED_OPERATION_ERROR_PREFIX } from '@lobechat/const/goal';-import { parse } from '@lobechat/conversation-flow';-import { getModelPropertyWithFallback } from '@lobechat/model-runtime';-import {- context as otelContext,- SpanStatusCode,- trace as otelTrace,-} from '@lobechat/observability-otel/api';-import {- asyncToolResumeCounter,- buildInvokeAgentAttributes,- buildInvokeAgentResultAttributes,- invokeAgentSpanName,- tracer as agentRuntimeTracer,-} from '@lobechat/observability-otel/modules/agent-runtime';-import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';-import {- type ChatToolPayload,- type ClientLlmWaitItem,- type EvalToolForwardingConfig,- type ExecSubAgentParams,- type ExecSubAgentResult,- type ExecVirtualSubAgentParams,- type ResumeClientLlmWaitResult,- type UIChatMessage,-} from '@lobechat/types';-import { ChatErrorType, RequestTrigger } from '@lobechat/types';-import { isRecord } from '@lobechat/utils/object';-import debug from 'debug';-import pMap from 'p-map';-import urlJoin from 'url-join';--import {- deriveAgentInterventionQueueDeduplicationId,- matchesAgentInterventionContinuationProvenance,-} from '@/business/server/agent-run/agentInterventionIdentity';-import { AgentOperationModel } from '@/database/models/agentOperation';-import { MessageModel } from '@/database/models/message';-import { type LobeChatDatabase } from '@/database/type';-import { appEnv } from '@/envs/app';-import { isDeviceCapablePlan, isDeviceLockedPlan } from '@/helpers/executionTarget';-import { type AgentRuntimeCoordinatorOptions } from '@/server/modules/AgentRuntime';-import { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modules/AgentRuntime';-import { runMayUseDevice } from '@/server/modules/AgentRuntime/executors/resolveRunActiveDeviceId';-import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';-import {- buildClientLlmWait,- buildClientLlmWaitMessageError,- buildClientLlmWaitResumeContext,- CLIENT_WAIT_REVERT_RETRY_DELAYS_MS,- isClientLlmWaitExpiryOf,- MIN_CLIENT_LLM_WAIT_REMAINING_MS,-} from '@/server/modules/AgentRuntime/llmRelay/clientWait';-import {- createClientLlmExecutorUnavailableError,- getClientLlmWaitableReason,-} from '@/server/modules/AgentRuntime/llmRelay/errors';-import { CLIENT_LLM_WAIT_CAPABILITY } from '@/server/modules/AgentRuntime/llmRelay/protocol';-import { hasNonPersistedMessage } from '@/server/modules/AgentRuntime/messagePersistence';-import {- createRuntimeExecutors,- type RuntimeExecutorContext,-} from '@/server/modules/AgentRuntime/RuntimeExecutors';-import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';-import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';-import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';-import { traceStartStage } from '@/server/services/aiAgent/pipeline/sendTracing';-import { FileService } from '@/server/services/file';-import { mcpService } from '@/server/services/mcp';-import { MessageService } from '@/server/services/message';-import { QueueService } from '@/server/services/queue';-import { LocalQueueServiceImpl } from '@/server/services/queue/impls';-import { ToolExecutionService } from '@/server/services/toolExecution';-import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';-import { createWidgetDryRunAudit } from '@/server/services/widget/dryRunAudit';-import {- resolveRunWorkAccessScope,- stateHasEntityFileEdits,-} from '@/server/services/workRegistration';--import { resolveMessageFileUrls } from '../message/resolveMessageFileUrls';-import { isAbortError, throwIfAborted } from './abort';-import {- CompletionLifecycle,- CriticalAgentInterventionPersistenceError,- extractTextFromMessage,- findLastAssistantMessage,- isAgentShareRun,- isSuccessLikeCompletionReason,- normalizeCompletionMessages,-} from './CompletionLifecycle';-import { stepChangedCredentials } from './credentialFacts';-import { logToolCallPc } from './formalObservation';-import { type AgentHook, hookDispatcher, parseSerializedHooks } from './hooks';-import {- controlDeferredToolResult,- type DeferredToolResultControlInput,- loadDurableToolResultHooks,-} from './hooks/deferredToolResultControl';-import { HumanInterventionHandler } from './HumanInterventionHandler';-import { buildProjectedMessagePatch } from './messagePatch';-import { OperationTraceRecorder } from './OperationTraceRecorder';-import { createDefaultSnapshotStore } from './snapshotStore';-import { buildStepPresentation, formatTokenCount } from './stepPresentation';-import {- type AgentExecutionParams,- type AgentExecutionResult,- type AgentStepContinuation,- type ExecGroupMemberParams,- type ExecGroupMemberResult,- type GroupActionMemberBridgeParams,- type GroupActionOnComplete,- type GroupMemberTimeoutParams,- type OperationCreationParams,- type OperationCreationResult,- type OperationStatusResult,- type PendingInterventionsResult,- type StartExecutionParams,- type StartExecutionResult,- type StepCompletionReason,- type SubAgentBridgeParams,-} from './types';--if (process.env.VERCEL) {- // Route debug output to stdout (`console.info`) instead of stderr, which- // Vercel would otherwise surface as error-level logs.- debug.log = console.info.bind(console);-}--const log = debug('lobe-server:agent-runtime-service');--/** Tries for a client wait's notice or expiry error on the assistant row. */-const CLIENT_WAIT_ROW_WRITE_ATTEMPTS = 3;--/**- * Base delay before the first `verifyAsyncToolBarrier` re-check fires after a- * sub-agent completion found the parent not yet resumable. Long enough for- * the parent's parking step to finish persisting, short enough that a lost- * resume is recovered promptly. Subsequent attempts back off exponentially —- * see {@link asyncToolVerifyDelayMs}.- */-const ASYNC_TOOL_VERIFY_DELAY_MS = 15_000;--/**- * Maximum number of bounded watchdog re-checks armed per parked parent. The- * watchdog re-arms after each unsatisfied check (instead of the old single- * shot) so a transient miss — a read-replica lag, a sibling dying between- * backfill and resume — is retried rather than leaving the parent stuck in- * `waiting_for_async_tool` forever. With exponential backoff from a 15s base,- * 5 attempts span ~15s → ~7.75min total before giving up. For details see: async sub-agent suspend/resume stability hardening — bounded watchdog retry with exponential backoff instead of single-shot verification.- */-const ASYNC_TOOL_VERIFY_MAX_ATTEMPTS = 5;--/** Hard ceiling on a single backoff delay so late attempts don't overshoot. */-const ASYNC_TOOL_VERIFY_MAX_DELAY_MS = 240_000;--const STEP_LOCK_TTL_SECONDS = 120;-/**- * How often a live step re-reads its own operation state to notice an- * interrupt. Interrupts are persisted by a different invocation, so this poll- * is the only way a running tool learns it should stop.- */-const STEP_ABORT_POLL_INTERVAL_MS = 2_000;-/**- * Temporary compatibility cadence for interrupts written by pre-sentinel- * workers during a rolling deployment. Remove after every worker writes the- * sentinel; keeping this much slower than the sentinel poll preserves most of- * the Redis bandwidth reduction in the meantime.- */-const LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS = 30_000;-/** Cap on the exponential backoff multiplier after consecutive poll failures. */-const STEP_ABORT_POLL_MAX_BACKOFF = 8;-const STEP_LOCK_HEARTBEAT_MS = 30_000;-const DURABLE_LEASE_HEARTBEAT_EVERY_TICKS = 3;-/**- * How long a `running` operation's durable lease may go unrefreshed, with its- * runtime state gone, before a stop request treats it as dead. Far above the- * heartbeat cadence (STEP_LOCK_HEARTBEAT_MS × DURABLE_LEASE_HEARTBEAT_EVERY_TICKS).- */-const DEAD_OPERATION_LEASE_MS = 10 * 60 * 1000;-const EVAL_TOOL_FORWARDING_HOOK_ID = 'eval-tool-forwarding';-const INTERVENTION_LIFECYCLE_CHECKPOINT_KEY = '_agentInterventionLifecycle';--/**- * Drop the frozen model facts from a copy of `modelRuntimeConfig`.- *- * They exist so a live run's steps stop re-reading the model bank and the- * user's rows, and the run reads them back off its Redis state. The durable- * `agent_operations` row and the operation metadata only ever surface the model- * and provider, so neither needs to keep ~0.5KB of cards per operation — the row- * keeps them forever.- */-const withoutFrozenModelFacts = (modelRuntimeConfig?: any) => {- if (!modelRuntimeConfig?.modelFacts) return modelRuntimeConfig;- const { modelFacts: _frozen, ...rest } = modelRuntimeConfig;- return rest;-};--interface InterventionLifecycleCheckpoint {- state: 'completed' | 'pending';- stepIndex: number;-}--const toToolForwardingFailure = (error?: unknown): ToolRunResult => ({- content: error === undefined ? 'Tool forwarding failed' : String(error),- error,- success: false,-});--export const createEvalToolForwardingHook = (- toolForwarding: EvalToolForwardingConfig,- caseId?: string,-): AgentHook => ({- handler: async (event) => {- const { apiName, args, callIndex, identifier, mock, operationId, stepIndex } =- event as unknown as ToolCallHookEvent;- const target = toolForwarding[identifier];- if (!target) return;-- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), target.timeoutMs ?? 15_000);-- try {- const payload: ToolForwardingRequest = {- data: { apiName, args, identifier },- metadata: { ...(caseId && { caseId }), callIndex, operationId, stepIndex },- type: 'toolCall',- };- const response = await ssrfSafeFetch(target.endpoint, {- body: JSON.stringify(payload),- headers: { 'Content-Type': 'application/json' },- method: 'POST',- signal: controller.signal,- });- if (!response.ok) throw `Tool forwarding server responded with HTTP ${response.status}`;-- const body: unknown = await response.json();- if (!isRecord(body)) throw new Error('Invalid tool forwarding response');-- if (body.success === true) {- const result = body.data;- if (- isRecord(result) &&- typeof result.content === 'string' &&- typeof result.success === 'boolean'- ) {- mock({ ...result, content: result.content, success: result.success });- } else {- mock({ content: 'No tool result', success: true });- }- } else {- mock(toToolForwardingFailure(body.error));- }- } catch (error) {- mock(toToolForwardingFailure(error));- } finally {- clearTimeout(timeout);- }- },- id: EVAL_TOOL_FORWARDING_HOOK_ID,- type: 'beforeToolCall',-});--/**- * How many times a delivery that lost the operation lock re-queues itself- * before giving up and falling back to a retryable response.- */-const STEP_LOCK_RETRY_MAX_ATTEMPTS = 12;-/** Base delay for the first lock-conflict re-delivery. */-const STEP_LOCK_RETRY_BASE_DELAY_MS = 15_000;-/**- * Ceiling on a single lock-conflict backoff. Together with the base delay,- * {@link STEP_LOCK_RETRY_MAX_ATTEMPTS} attempts span ~20 minutes — comfortably- * longer than the platform's hard step ceiling, so a step that legitimately- * holds the lock for minutes no longer strands the delivery waiting behind it.- */-const STEP_LOCK_RETRY_MAX_DELAY_MS = 120_000;--/**- * Exponential backoff for the Nth (1-based) lock-conflict re-delivery:- * 15s, 30s, 60s, 120s, then capped at {@link STEP_LOCK_RETRY_MAX_DELAY_MS}.- */-const stepLockRetryDelayMs = (attempt: number): number =>- Math.min(- STEP_LOCK_RETRY_BASE_DELAY_MS * 2 ** (Math.max(1, attempt) - 1),- STEP_LOCK_RETRY_MAX_DELAY_MS,- );--/**- * Exponential backoff delay for the Nth (1-based) watchdog re-check:- * 15s, 30s, 60s, 120s, 240s, capped at {@link ASYNC_TOOL_VERIFY_MAX_DELAY_MS}.- */-const asyncToolVerifyDelayMs = (attempt: number): number =>- Math.min(- ASYNC_TOOL_VERIFY_DELAY_MS * 2 ** (Math.max(1, attempt) - 1),- ASYNC_TOOL_VERIFY_MAX_DELAY_MS,- );--const createStepLockOwner = (operationId: string, stepIndex: number): string =>- `${operationId}:${stepIndex}:${process.pid}:${Date.now()}:${randomUUID()}`;--/**- * Format error for storage in message pluginError metadata.- * Handles Error objects which don't serialize properly with JSON.stringify.- */-const formatErrorForMetadata = (error: unknown): Record<string, any> | undefined => {- if (!error) return undefined;- if (error instanceof Error) return { message: error.message, name: error.name };- if (typeof error === 'object' && 'message' in error) return error as Record<string, any>;- return { message: String(error) };-};--const SUB_AGENT_CREDIT_ERROR_TYPES = new Set<string>([- ChatErrorType.FreePlanLimit,- ChatErrorType.InsufficientBudgetForModel,- ChatErrorType.SubscriptionPlanLimit,-]);--/**- * A child stopped by the cost-admission gate fails with the bare message- * "Budget exceeded", which reads like a per-sub-agent allowance. The parent- * then retries or fans out more sub-agents against the same limit. Say which- * limit it is and who can lift it.- *- * Mirrors the bot reply copy (`bot/replyTemplate.ts`): the payer is not- * addressed as "you" and figures are never quoted, because a bot run is billed- * to its owner while the parent's reply may reach a shared channel.- */-const formatSubAgentCreditErrorReason = (error: unknown): string | undefined => {- if (!error || typeof error !== 'object') return;- const { body, errorType, type } = error as {- body?: { budget?: { budgetTypeAtError?: unknown } };- errorType?: unknown;- type?: unknown;- };- const creditType = [type, errorType].find(- (value): value is string =>- typeof value === 'string' && SUB_AGENT_CREDIT_ERROR_TYPES.has(value),- );- if (!creditType) return;-- const budgetType = body?.budget?.budgetTypeAtError;- // InsufficientBudgetForModel means the allowance still has credits, just not- // enough for this model's estimated cost — a cheaper model may still fit, so- // the no-retry claim only holds for the same model (bot/replyTemplate gives- // the same "switch to a less expensive model" advice).- const modelCostShortfall = creditType === ChatErrorType.InsufficientBudgetForModel;- const shortfall = modelCostShortfall ? "can't cover this model's estimated cost" : 'are used up';- const limit =- budgetType === 'workspace'- ? `the workspace's shared LobeHub credits ${shortfall}; a workspace admin has to add credits`- : budgetType === 'workspace_member'- ? `this member's workspace credit allowance ${modelCostShortfall ? shortfall : 'is used up'}; a workspace admin has to raise it`- : modelCostShortfall- ? "the account's LobeHub credits are too low for this model; the account owner has to top up or upgrade"- : "the account's LobeHub plan limit was reached or the plan does not cover this model; the account owner has to upgrade the plan";-- const advice = modelCostShortfall- ? 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents on the same model will not get past it; a sub-agent that runs on a less expensive model may still fit. ' +- 'Otherwise finish with what you already have and tell the user about the limit.'- : 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents will not get past it. ' +- 'Finish with what you already have and tell the user about the limit.';-- return `stopped by a LobeHub billing limit (${creditType}): ${limit}. ${advice}`;-};--/**- * Extract a short, human-readable reason string from a failed operation's- * `state.error`, for inlining into the tool-result `content` a parent agent- * sees. Without this the supervising agent only gets the opaque generic note- * ("Sub-agent did not complete (error).") and cannot tell *why* a `callAgent`- * dispatch failed — so it can't retry, switch target, or report the cause; it- * silently falls back to answering itself (issue #16257). The full structured- * error still rides on `pluginError`; this is just the readable summary.- */-const formatSubAgentErrorReason = (error: unknown): string | undefined => {- const creditReason = formatSubAgentCreditErrorReason(error);- if (creditReason) return creditReason;-- const message = formatErrorForMetadata(error)?.message;- if (typeof message !== 'string') return undefined;- const trimmed = message.trim();- if (!trimmed) return undefined;- // "Operation abandoned: inactivity_watchdog" names an internal mechanism;- // the parent needs to know the child went silent and that its work survives.- if (trimmed.startsWith(ABANDONED_OPERATION_ERROR_PREFIX)) {- const cause = trimmed.slice(ABANDONED_OPERATION_ERROR_PREFIX.length).trim();- return (- `the sub-agent stopped making progress and the platform ended it (${cause || 'abandoned'}). ` +- 'Anything it already did (searches, pages read, documents written) is kept in its thread.'- );- }- // Keep the tool result compact — a runaway provider error body would otherwise- // bloat the parent's LLM context.- return trimmed.length > 300 ? `${trimmed.slice(0, 300)}…` : trimmed;-};--const toAgentSignalSnapshotEvents = (- emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,-) => {- if (!emission || emission.deduped) return [];-- return toAgentSignalTraceEvents({- actions: emission.orchestration.actions,- results: emission.orchestration.results,- signals: emission.orchestration.emittedSignals,- source: emission.source,- });-};--/**- * Operations the runtime delegates UP to its owning layer (AiAgentService).- *- * The dependency arrow is one-way: AiAgentService → AgentRuntimeService. The- * runtime is the low-level step executor — it cannot resolve agent configs,- * build tool engines, manage threads, or run the full `execAgent` pipeline;- * those live in the layer above it. Yet some tools (e.g. `lobe-agent.callSubAgent`)- * need exactly such a high-level action *mid-step*. Rather than import- * AiAgentService (which would be a circular dependency), the runtime delegates- * these operations back to its owner through callbacks injected here.- *- * Convention: every future "the runtime, mid-execution, must trigger a- * higher-layer pipeline" capability belongs on this delegate — not as a loose- * top-level option. One named home for the whole upward-call surface.- */-export interface AgentRuntimeDelegate {- /**- * Fork a group member ("call agent member") under a `lobe-group-management`- * tool call. Handles both in-group (non-isolated, shared group session) and- * isolated members, installing the group-action member completion bridge that- * enforces the K=N member barrier before resuming/finishing the supervisor.- */- execGroupMember?: (params: ExecGroupMemberParams) => Promise<ExecGroupMemberResult>;- /**- * Run a legacy agent invocation through the full high-level pipeline- * (AiAgentService.execSubAgent → execAgent: agent-config resolution, tool- * engine, context engineering, createOperation).- */- execSubAgent?: (params: ExecSubAgentParams) => Promise<ExecSubAgentResult>;- /**- * Fork a `lobe-agent.callSubAgent` virtual child run. The child is marked as a- * sub-agent and owns the completion bridge that backfills the parent tool- * placeholder before resuming the parked parent operation.- */- execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;- /**- * Re-check that an Agent Share visitor run is STILL authorized to continue,- * called on EVERY step. Without it, a revocation that lands mid-run (link →- * private, share disabled, agent deleted) would only stop NEW requests: the- * already-created operation keeps its tool snapshot and gateway channel and- * keeps running under the CREATOR's credentials and budget, unstoppable by- * the visitor (whose Stop button re-resolves the now-private share and gets- * `FORBIDDEN`). Re-checking at every step boundary means a revocation always- * takes effect within one step, with no durable interrupt-retry machinery.- *- * Implemented by AiAgentService via `AgentShareModel.isRunStillAuthorized`.- * Returns `false` (not a throw) for an ordinary "no longer authorized"- * outcome; the caller treats a THROWN error the same as `false` — fail- * closed, never fail open.- */- verifyShareRunStillAuthorized?: (params: {- agentId: string;- shareId: string;- }) => Promise<boolean>;-}--export interface AgentRuntimeServiceOptions {- /**- * Custom agent factory. When provided, this function is called instead of- * the default `new GeneralChatAgent(config)` to create the Agent instance.- * This allows injecting alternative Agent implementations (e.g. GraphAgent)- * without the service needing to know about them.- */- agentFactory?: (config: GeneralAgentConfig) => Agent;- /**- * Coordinator configuration options- * Allows injection of custom stateManager and streamEventManager- */- coordinatorOptions?: AgentRuntimeCoordinatorOptions;- /**- * Operations the runtime delegates up to its owning layer. See- * {@link AgentRuntimeDelegate}. Injected by AiAgentService so the runtime can- * trigger high-level pipelines (e.g. sub-agent forking) mid-step without a- * circular import.- */- delegate?: AgentRuntimeDelegate;- /**- * Opt IN to agent-share visitor rows for the models this service owns.- * Reserved for share-runtime entry points that drive a visitor turn under- * the CREATOR's `userId`. Defaults to false. See- * {@link import('@/database/models/message').MessageModelOptions}.- */- includeShareVisitor?: boolean;- /**- * Custom QueueService- * Set to null to disable queue scheduling (for synchronous execution tests)- */- queueService?: QueueService | null;- /**- * Optional snapshot store for persisting agent execution traces.- * When provided, execution snapshots are recorded on every step and finalized on completion.- * In dev mode without this option, falls back to FileSnapshotStore automatically.- */- snapshotStore?: ISnapshotStore;- /**- * Custom StreamEventManager- * Defaults to Redis-based StreamEventManager- * Can pass InMemoryStreamEventManager in test environments- */- streamEventManager?: IStreamEventManager;- /**- * Workspace id for scoping all DB reads/writes (messages, agent_operations).- * Falls back to user-personal scope when omitted.- */- workspaceId?: string;-}--/**- * Agent Runtime Service- * Encapsulates Agent execution logic and provides a unified service interface- *- * Supports dependency injection for testing with in-memory implementations:- * ```ts- * // Production environment (uses Redis by default)- * const service = new AgentRuntimeService(db, userId);- *- * // Test environment- * const service = new AgentRuntimeService(db, userId, {- * streamEventManager: new InMemoryStreamEventManager(),- * queueService: null, // Disable queue, use executeSync- * });- * ```- */-export class AgentRuntimeService {- private agentOperationModel: AgentOperationModel;- private agentFactory?: (config: GeneralAgentConfig) => Agent;- private completionLifecycle: CompletionLifecycle;- private coordinator: AgentRuntimeCoordinator;- private delegate: AgentRuntimeDelegate;- private humanIntervention: HumanInterventionHandler;- private streamManager: IStreamEventManager;- private queueService: QueueService | null;- private traceRecorder: OperationTraceRecorder;- private toolExecutionService: ToolExecutionService;- private get baseURL() {- const baseUrl = process.env.AGENT_RUNTIME_BASE_URL || appEnv.APP_URL || 'http://localhost:3010';-- return urlJoin(baseUrl, '/api/agent');- }- private serverDB: LobeChatDatabase;- private userId: string;- private workspaceId?: string;- private messageModel: MessageModel;- // Lazily constructed because MessageService instantiates a FileService- // which eagerly creates the S3 client and throws when S3 env vars are- // missing — eager construction would break every test that builds an- // AgentRuntimeService without mocking the file backend.- private messageServiceInstance?: MessageService;- private get messageService(): MessageService {- if (!this.messageServiceInstance) {- this.messageServiceInstance = new MessageService(- this.serverDB,- this.userId,- this.workspaceId,- );- }- return this.messageServiceInstance;- }-- constructor(db: LobeChatDatabase, userId: string, options?: AgentRuntimeServiceOptions) {- // Use factory function to auto-select Redis or InMemory implementation.- // Gateway pushes are deferred off the step path: every point where this- // invocation can stop or hand the run over calls `drainPushes` first.- this.streamManager =- options?.streamEventManager ??- options?.coordinatorOptions?.streamEventManager ??- createStreamEventManager({ deferPushes: true });- this.coordinator = new AgentRuntimeCoordinator({- ...options?.coordinatorOptions,- messagePatchModeResolver: (state) => this.usesGatewayMessagePatch(state),- streamEventManager: this.streamManager,- // Provide the canonical UIChatMessage[] for terminal-state events so- // the client can use the pushed payload directly instead of refetching- // from DB. Falls back gracefully when topicId isn't set.- uiMessagesResolver: async (state) =>- this.usesGatewayMessagePatch(state) ? undefined : this.queryUiMessages(state),- });- this.queueService =- options?.queueService === null ? null : (options?.queueService ?? new QueueService());- this.traceRecorder = new OperationTraceRecorder(- options?.snapshotStore ?? createDefaultSnapshotStore(),- );- this.agentFactory = options?.agentFactory;- this.delegate = options?.delegate ?? {};- this.serverDB = db;- this.userId = userId;- this.workspaceId = options?.workspaceId;- const workspaceId = this.workspaceId;- const includeShareVisitor = options?.includeShareVisitor ?? false;- this.agentOperationModel = new AgentOperationModel(db, this.userId, workspaceId);- this.messageModel = new MessageModel(db, this.userId, workspaceId, undefined, {- includeShareVisitor,- });- this.completionLifecycle = new CompletionLifecycle(db, userId, workspaceId, {- includeShareVisitor,- });- this.humanIntervention = new HumanInterventionHandler(db, this.messageModel);-- // Initialize ToolExecutionService with dependencies- const builtinToolsExecutor = new BuiltinToolsExecutor(db, userId);-- this.toolExecutionService = new ToolExecutionService({- builtinToolsExecutor,- mcpService,- });-- // Setup local execution callback for LocalQueueServiceImpl- this.setupLocalExecutionCallback();- }-- private startStepLockHeartbeat(- operationId: string,- stepIndex: number,- ownerId: string,- ): () => void {- let heartbeatTick = 0;- const timer = setInterval(() => {- heartbeatTick += 1;- const refreshDurableLease = heartbeatTick % DURABLE_LEASE_HEARTBEAT_EVERY_TICKS === 0;-- Promise.all([- this.coordinator.refreshStepLock(operationId, stepIndex, STEP_LOCK_TTL_SECONDS, ownerId),- refreshDurableLease- ? this.agentOperationModel.touchRunning(operationId)- : Promise.resolve(true),- ])- .then(([refreshed, leaseRefreshed]) => {- if (!refreshed) {- log(- '[%s][%d] Step lock heartbeat did not refresh; ownership may have changed',- operationId,- stepIndex,- );- }- if (!leaseRefreshed) {- log(- '[%s][%d] Durable operation lease was lost; terminal persistence will be rejected',- operationId,- stepIndex,- );- }- })- .catch((error) => {- log('[%s][%d] Step lock heartbeat failed: %O', operationId, stepIndex, error);- });- }, STEP_LOCK_HEARTBEAT_MS);-- const timerWithUnref = timer as { unref?: () => void };- timerWithUnref.unref?.();-- return () => clearInterval(timer);- }-- /**- * Setup execution callback for LocalQueueServiceImpl- * This breaks the circular dependency by using callback injection- */- private setupLocalExecutionCallback(): void {- if (!this.queueService) return;-- const impl = this.queueService.getImpl();- if (impl instanceof LocalQueueServiceImpl) {- log('Setting up local execution callback');- impl.setExecutionCallback(async (operationId, stepIndex, context, payload) => {- // Mirror the QStash path where payload fields (approvedToolCall,- // toolMessageId, resumeAsyncTool, …) ride the request body into- // executeStep. Without this spread, local/in-memory resumes silently- // lose their intervention/resume signal.- await this.executeStep({ context, operationId, stepIndex, ...payload });- });- }- }-- // ==================== Operation Interruption ====================-- /**- * Whether someone already asked this run to stop (the interrupt sentinel is- * set), even though it may still be finishing its current step.- */- async isOperationInterrupted(operationId: string): Promise<boolean> {- return this.coordinator.isInterrupted(operationId);- }-- /**- * Interrupt a running agent operation by setting its state to 'interrupted'.- * The agent will stop at the next step boundary (cannot abort an in-flight LLM call).- * Works with both Redis and InMemory state managers via the coordinator abstraction.- *- * @returns true if interruption is acknowledged (including an already terminal operation),- * false if missing runtime state prevents confirming that the operation has stopped.- */- async interruptOperation(operationId: string): Promise<boolean> {- const state = await this.coordinator.loadAgentState(operationId);- if (!state) {- // Runtime state can expire before the task-topic completion callback lands.- // Absence alone is not proof of exit (e.g. another in-memory worker owns- // the run). Only an owned, durably terminal operation can acknowledge it.- const operation = await this.agentOperationModel.findById(operationId);- if (!operation) return false;- if (['done', 'error', 'interrupted', 'abandoned'].includes(operation.status)) return true;-- // A `running` row with no runtime state whose durable lease stopped- // refreshing long ago has nothing executing it: the step heartbeat moves- // `updatedAt` every few minutes while a step is live. Without this, the- // row stays `running` forever and every stop request on its task is- // refused as unconfirmed. Retire it atomically — a concurrent heartbeat- // moves `updatedAt` past the cutoff and wins, keeping a live run alive.- if (- operation.status === 'running' &&- operation.updatedAt &&- new Date(operation.updatedAt).getTime() < Date.now() - DEAD_OPERATION_LEASE_MS- ) {- return this.agentOperationModel.settleStaleRunning(- operationId,- new Date(Date.now() - DEAD_OPERATION_LEASE_MS),- );- }- return false;- }-- if (state.status === 'done' || state.status === 'error' || state.status === 'interrupted') {- // A retried stop must be able to settle a stale running task-topic without- // overwriting the original completion outcome or emitting another stop.- return true;- }-- // Sentinel FIRST: the poller and the step-boundary check read only the- // sentinel, so it must become visible no later than the interrupted- // state — otherwise a boundary check landing between the two writes- // reads false and the following saveStepResult clobbers the- // interruption. Writing it first also keeps failure atomic: if the- // sentinel write throws, the state below is never marked either, so the- // two never diverge. A sentinel that lands without the state save- // (crash between the writes) only stops the op earlier than the record- // shows — the step-boundary check then persists the interrupted state.- await this.coordinator.markInterrupted(operationId);-- const parkedWait = state.status === 'waiting_for_client' ? state.clientLlmWait : undefined;- const interruptedState: AgentState = {- ...state,- ...(state.status === 'waiting_for_client' && { clientLlmWait: undefined }),- lastModified: new Date().toISOString(),- status: 'interrupted',- };- await this.coordinator.saveAgentState(operationId, interruptedState);-- // A run parked for a client has no step that would reach a boundary and- // settle it, so settle it here — otherwise the row and the topic stay live- // until the wait expires. Its waiting card goes too: nothing can continue it.- if (state.status === 'waiting_for_client') {- if (parkedWait?.assistantMessageId) {- await this.messageModel- .update(parkedWait.assistantMessageId, { error: null })- .catch((error) => log('[%s] Failed to clear the waiting notice: %O', operationId, error));- }- if (await this.agentOperationModel.settleClientWait(operationId, 'interrupted')) {- await this.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');- } else if (parkedWait) {- // The wait's expiry claimed the row first and has not finished (its- // Redis state still read this park). Its retry would find the state- // this Stop just wrote and give up, so finish it here as the row says.- const row = await this.agentOperationModel.findById(operationId).catch(() => undefined);- if (row?.status === 'error') {- log('[%s] Stop lost to the wait expiry; finishing the expiry', operationId);- await this.endExpiredClientLlmWait(operationId, state, parkedWait);- }- }- }-- log('[%s] Operation interrupted', operationId);- return true;- }-- /**- * The relay executor a new run carries: the one its client declared, else- * its parent's, so a child run (group member, `callSubAgent` / `callAgent`- * sub-agent) on the same local model reaches the same device. No client- * subscribes to the child's own channel — the gateway only hands- * `llm_execute` to subscribers of the op it is sent on — so the inherited- * executor names the channel its tab does listen on: the parent's, or the- * one the parent already inherited. The parent stays subscribed meanwhile: it- * is parked (`waiting_for_async_tool`) or supervising its members.- * Only the caller's own parent in this workspace counts: a client can name- * any `parentOperationId`, and a foreign run's executor would hand this- * child's LLM payload to another user's tab, or to a tab of the same user- * relaying with another workspace's providers.- * Best-effort: an expired parent leaves the child without one.- */- private async resolveLlmExecutor(- declared: AgentRunLlmExecutor | undefined,- parentOperationId: string | undefined,- ): Promise<AgentRunLlmExecutor | undefined> {- if (declared) return declared;- if (!parentOperationId) return;-- let parent: AgentState | null | undefined;- try {- parent = await this.coordinator.loadAgentState(parentOperationId);- } catch (error) {- log('[%s] Failed to read the parent relay executor: %O', parentOperationId, error);- return;- }- if (- parent?.origin?.userId !== this.userId ||- (parent.origin.workspaceId ?? undefined) !== (this.workspaceId ?? undefined)- )- return;-- const inherited = parent.host?.llmExecutor;- if (!inherited) return;-- return {- ...inherited,- channelOperationId: inherited.channelOperationId ?? parentOperationId,- };- }-- /**- * The relay executor an operation carries, e.g. for an approval continuation- * that the parked operation's client resumes. Best-effort: an unknown or- * expired operation reads as none.- */- async getLlmExecutor(operationId: string): Promise<AgentRunLlmExecutor | undefined> {- try {- const state = await this.coordinator.loadAgentState(operationId);- return state?.host?.llmExecutor;- } catch (error) {- log('[%s] Failed to read the relay executor: %O', operationId, error);- return;- }- }-- /**- * Whether the client that started this operation declared it renders `file`- * Works. An unknown or expired operation reads as `false`, so a continuation- * then keeps the pushed snapshot every client can render.- */- async acceptsFileWorks(operationId: string): Promise<boolean> {- try {- const state = await this.coordinator.loadAgentState(operationId);- return state?.host?.acceptsFileWorks === true;- } catch (error) {- log('[%s] Failed to read the file Works declaration: %O', operationId, error);- return false;- }- }-- /**- * Whether the client that started this operation declared it handles- * `member_runtime_end`. An unknown or expired operation reads as `false`, so- * a continuation then keeps the verbatim terminal every client understands.- */- async acceptsMemberRuntimeEnd(operationId: string): Promise<boolean> {- const metadata = await this.coordinator.getOperationMetadata(operationId).catch(() => null);- return metadata?.acceptsMemberRuntimeEnd === true;- }-- /**- * Record whether the client still holds user messages queued behind a run.- * Only the run's owner may flag it; an unknown or foreign operation is a- * no-op, so a caller cannot touch another user's run by guessing its id.- *- * @returns true when the flag was written- */- async setQueuedMessages(operationId: string, pending: boolean): Promise<boolean> {- const metadata = await this.coordinator.getOperationMetadata(operationId);- if (!metadata || metadata.userId !== this.userId) return false;-- await this.coordinator.setQueuedMessages(operationId, pending);- log('[%s] Queued messages flag set to %s', operationId, pending);- return true;- }-- /**- * Read the queued-messages flag for a step. A failed read keeps the run- * going: the follow-up still starts once the run ends, exactly as it did- * before the flag existed, instead of failing the step.- */- private async readQueuedMessagesFlag(operationId: string, stepIndex: number): Promise<boolean> {- try {- return await this.coordinator.hasQueuedMessages(operationId);- } catch (error) {- log('[%s][%d] Queued messages flag read failed: %O', operationId, stepIndex, error);- return false;- }- }-- /** Review out-of-band results before any subsequent history read can expose them. */- async controlCompletedToolResult(input: DeferredToolResultControlInput) {- const controlled = await controlDeferredToolResult(- {- dispatcher: hookDispatcher,- loadState: (operationId) => this.coordinator.loadAgentState(operationId),- loadDurableHooks: (operationId) =>- loadDurableToolResultHooks(this.agentOperationModel, operationId),- messageModel: this.messageModel,- userId: this.userId,- workspaceId: this.workspaceId,- },- input,- );- return controlled;- }-- /** Load the authoritative runtime state for a deterministic intervention continuation. */- async loadInterventionContinuationState(operationId: string): Promise<AgentState | null> {- return this.coordinator.loadAgentState(operationId);- }-- /**- * The completion bridge of a group member run: from its runtime snapshot- * while it lives, else from the durable copy recorded on the operation row- * at start. Undefined for any run that is not a group member.- */- async loadGroupMemberBridge(operationId: string): Promise<- | {- agentId: string;- bridge: Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'>;- groupId?: string;- threadId?: string;- topicId?: string;- }- | undefined- > {- const state = await this.coordinator.loadAgentState(operationId);- if (state) {- const origin = state.origin;- const bridge = state.host?.hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook- ?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;- if (origin?.lineage?.orchestrationRole !== 'member' || !origin.agentId || !bridge) {- return undefined;- }- return {- agentId: origin.agentId,- bridge,- groupId: origin.groupId ?? undefined,- threadId: origin.threadId ?? undefined,- topicId: origin.topicId ?? undefined,- };- }-- const row = await this.agentOperationModel.findById(operationId);- const bridge = (row?.metadata as Record<string, unknown> | null | undefined)- ?.groupMemberBridge as- Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;- if (!row?.agentId || !bridge) return undefined;- return {- agentId: row.agentId,- bridge,- groupId: row.chatGroupId ?? undefined,- threadId: row.threadId ?? undefined,- topicId: row.topicId ?? undefined,- };- }-- /**- * Re-enqueue a continuation whose durable state was written but whose first- * queue delivery may have been lost with the resolving HTTP process. The- * operation id and step index are stable, so the ordinary distributed step- * lock de-duplicates concurrent/repeated schedules.- */- async ensureInterventionContinuationStarted(- operationId: string,- ): Promise<'already_started' | 'missing' | 'scheduled'> {- const state = await this.coordinator.loadAgentState(operationId);- if (!state) return 'missing';-- const provenance = state.origin?.continuation as- | {- resolutionRequestId?: unknown;- sourceOperationId?: unknown;- sourceToolMessageIds?: unknown;- }- | undefined;- const preparation = state.metadata?.agentInterventionPreparation as- | {- deduplicationId?: unknown;- resolutionRequestId?: unknown;- state?: unknown;- stepIndex?: unknown;- }- | undefined;- if (- typeof provenance?.resolutionRequestId !== 'string' ||- typeof provenance.sourceOperationId !== 'string' ||- !Array.isArray(provenance.sourceToolMessageIds) ||- !provenance.sourceToolMessageIds.every((id) => typeof id === 'string')- ) {- throw new Error(`Intervention continuation provenance missing: ${operationId}`);- }- if (- preparation?.state !== 'ready' ||- preparation.resolutionRequestId !== provenance.resolutionRequestId ||- typeof preparation.stepIndex !== 'number' ||- !Number.isSafeInteger(preparation.stepIndex) ||- preparation.stepIndex < 0- ) {- throw new Error(`Intervention continuation is not ready to schedule: ${operationId}`);- }- const stepIndex = preparation.stepIndex;- const deduplicationId = deriveAgentInterventionQueueDeduplicationId(operationId, stepIndex);- if (preparation.deduplicationId !== deduplicationId) {- throw new Error(`Intervention continuation dedupe provenance conflict: ${operationId}`);- }- const operation = await this.agentOperationModel.findById(operationId);- if (- !operation ||- !matchesAgentInterventionContinuationProvenance(- operation.metadata?.agentInterventionContinuation,- provenance as {- resolutionRequestId: string;- sourceOperationId: string;- sourceToolMessageIds: string[];- },- )- ) {- throw new Error(`Intervention continuation durable provenance conflict: ${operationId}`);- }- const durablePreparation = operation.metadata?.agentInterventionPreparation as- | {- deduplicationId?: unknown;- resolutionRequestId?: unknown;- state?: unknown;- stepIndex?: unknown;- }- | undefined;- if (- durablePreparation &&- (durablePreparation.state !== 'ready' ||- durablePreparation.resolutionRequestId !== provenance.resolutionRequestId ||- durablePreparation.stepIndex !== stepIndex ||- durablePreparation.deduplicationId !== deduplicationId)- ) {- throw new Error(`Intervention continuation durable preparation conflict: ${operationId}`);- }- if (!durablePreparation) {- const persisted = await this.agentOperationModel.recordAgentInterventionPreparation(- operationId,- {- deduplicationId,- resolutionRequestId: provenance.resolutionRequestId,- state: 'ready',- stepIndex,- },- );- if (!persisted) {- throw new Error(`Failed to backfill intervention preparation: ${operationId}`);- }- }- const dispatchMarker = operation.metadata?.agentInterventionDispatch as- | {- deduplicationId?: unknown;- messageId?: unknown;- resolutionRequestId?: unknown;- state?: unknown;- }- | undefined;- if (dispatchMarker) {- if (- dispatchMarker.state !== 'scheduled' ||- dispatchMarker.resolutionRequestId !== provenance.resolutionRequestId ||- dispatchMarker.deduplicationId !== deduplicationId- ) {- throw new Error(`Intervention continuation dispatch marker conflict: ${operationId}`);- }- return 'already_started';- }- if (!this.queueService) {- throw new Error(`Cannot schedule intervention continuation ${operationId}`);- }-- // Missing provider ACK is never inferred from `state.status`: a worker may- // have raced the HTTP response and advanced this state to running/terminal.- // Re-publish with the same provider dedupe key to recover the ACK without a- // second actual delivery, then persist the authoritative dispatch marker.- const messageId = await this.queueService.scheduleMessage({- context: (state as AgentState & { initialContext: AgentRuntimeContext }).initialContext,- deduplicationId,- delay: 0,- endpoint: `${this.baseURL}/run`,- operationId,- priority: 'high',- retryDelay:- typeof state.host?.queue?.retryDelay === 'string'- ? state.host?.queue?.retryDelay- : undefined,- retries:- typeof state.host?.queue?.retries === 'number' ? state.host?.queue?.retries : undefined,- stepIndex,- });- await this.persistInterventionDispatchAck({- deduplicationId,- messageId,- operationId,- resolutionRequestId: provenance.resolutionRequestId,- });-- return 'scheduled';- }-- private async persistInterventionDispatchAck(params: {- deduplicationId: string;- messageId: string;- operationId: string;- resolutionRequestId: string;- }): Promise<void> {- const marker = {- deduplicationId: params.deduplicationId,- messageId: params.messageId,- resolutionRequestId: params.resolutionRequestId,- scheduledAt: new Date().toISOString(),- state: 'scheduled' as const,- };- const persisted = await this.agentOperationModel.recordAgentInterventionDispatch(- params.operationId,- marker,- );- if (!persisted) {- throw new Error(`Failed to persist intervention queue ACK: ${params.operationId}`);- }- }-- /**- * Terminate an Agent Share visitor run whose authorization was revoked- * mid-flight (see the per-step check in `executeStep`).- *- * Persists `interrupted` onto the already-loaded state — the same terminal- * status a visitor's own Stop produces — so the client's stream settles- * normally instead of hanging. Falls back to `interruptOperation` when no- * state was readable. A persistence failure is logged, never rethrown: the- * run must stop regardless of whether the terminal status could be written.- *- * The completion lifecycle (`emitSignalEvents` + `dispatchHooks`) must run- * here too: this abort short-circuits `executeStep` before `runtime.step()`,- * so no downstream path is left to persist the terminal status. Without it- * `saveAgentState` would only update the runtime-state cache and publish the- * terminal stream event, leaving `agent_operations` stuck on `running` —- * which `TopicModel.tryReserveTaskCallback` then reads as a live run and- * blocks the visitor's next send on that topic for the abandoned-run TTL.- */- private async buildShareAbortResult(- operationId: string,- state: AgentState | null | undefined,- ): Promise<AgentExecutionResult> {- log('[%s] Aborting share visitor run — the share is no longer authorized', operationId);-- try {- if (state) {- const interruptedState: AgentState = {- ...state,- lastModified: new Date().toISOString(),- status: 'interrupted',- };- await this.coordinator.saveAgentState(operationId, interruptedState);-- await this.completionLifecycle.emitSignalEvents(- operationId,- interruptedState,- 'interrupted',- );- await this.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');- } else {- await this.interruptOperation(operationId);- }- } catch (error) {- log(- '[%s] Failed to persist interrupted state for an aborted share run: %O',- operationId,- error,- );- }-- return {- nextStepScheduled: false,- state: { status: 'interrupted' },- stepResult: null,- success: false,- };- }-- // ==================== Operation Management ====================-- /**- * Create a new Agent operation- */- async createOperation(params: OperationCreationParams): Promise<OperationCreationResult> {- const {- acceptsFileWorks,- acceptsMemberRuntimeEnd,- activeDeviceId,- activeDeviceScope,- operationId,- initialContext,- agentConfig,- agentGroup,- agentShareVisitor,- modelRuntimeConfig,- operationCredentials,- userId,- autoStart = true,- stream,- initialMessages = [],- interventionResolution,- onInterventionPrepared,- appContext,- toolSet,- hooks,- userInterventionConfig,- queueRetries,- queueRetryDelay,- searchDecision,- botContext,- botPlatformContext,- deviceAccessPolicy,- connectorOwnershipNote,- discordContext,- evalContext,- evalRuntime,- enableExpertise,- expertise,- projectInstructions,- executionPlan,- maxSteps,- userMemory,- deviceSystemInfo,- disabledPluginIds,- operationSkillSet,- parentOperationId,- signal,- userTimezone,- initialStepCount = 0,- workspaceId,- } = params;-- // Persist initial agent_operations row. CompletionLifecycle owns both- // ends of the persistence lifecycle (start row here, terminal update- // in dispatchHooks) and swallows DB errors so runtime startup is never- // blocked.- // A group member's completion bridge lives in the runtime snapshot, which- // expires (2h). Keep a durable copy on the row so a late approval or a- // stop can still reach the member's supervisor (`loadGroupMemberBridge`).- const groupMemberBridge = hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook- ?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;- // The Redis state expires independently of pending tools/approvals. Keep- // caller hook templates on the private operation record, as hetero runs do.- const durableHooks = parseSerializedHooks(- (hooks ?? []).flatMap((hook) =>- hook.webhook- ? [{ id: hook.id, type: hook.type, matcher: hook.matcher, webhook: hook.webhook }]- : [],- ),- );- const requiresDurableResultControl = durableHooks.some(- (hook) => hook.type === 'afterToolCall' && hook.webhook?.responseHandling === 'toolCall',- );- const operationStartPersisted = await traceStartStage('record_start', () =>- this.completionLifecycle.recordStart({- agentId: appContext?.agentId ?? null,- appContext: {- defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,- documentId: appContext?.documentId,- editingAgentId: appContext?.editingAgentId,- groupId: appContext?.groupId,- scope: appContext?.scope,- sessionId: appContext?.sessionId,- sourceMessageId: appContext?.sourceMessageId,- },- chatGroupId: appContext?.groupId ?? null,- maxSteps,- metadata: {- ...(durableHooks.length > 0 && { _hooks: durableHooks }),- ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),- ...(interventionResolution- ? { agentInterventionContinuation: interventionResolution }- : {}),- ...(groupMemberBridge ? { groupMemberBridge } : {}),- },- model: modelRuntimeConfig?.model,- modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),- operationId,- parentOperationId: parentOperationId ?? null,- provider: modelRuntimeConfig?.provider,- taskId: appContext?.taskId ?? null,- threadId: appContext?.threadId ?? null,- topicId: appContext?.topicId ?? null,- trigger: appContext?.trigger,- }),- );- if (requiresDurableResultControl && !operationStartPersisted) {- throw new Error('Failed to durably persist afterToolCall control policy before dispatch');- }- if (interventionResolution && !operationStartPersisted) {- throw new Error(- `Failed to durably persist intervention continuation ${operationId} before dispatch`,- );- }-- // A member's durable bridge is what a Stop or a late approval falls back- // to once the runtime snapshot expires; a member without it could strand- // its supervisor, so fail the start instead.- if (groupMemberBridge && !operationStartPersisted) {- throw new Error(`Failed to durably persist group member ${operationId} before dispatch`);- }-- if (interventionResolution) {- const durableOperation = await this.agentOperationModel.findById(operationId);- const persistedProvenance = durableOperation?.metadata?.agentInterventionContinuation;- if (- !durableOperation ||- !matchesAgentInterventionContinuationProvenance(persistedProvenance, interventionResolution)- ) {- throw new Error(`Intervention continuation operation identity conflict: ${operationId}`);- }- }-- const operationToolSet = toolSet;- let operationCreated = false;- let hooksRegistered = false;-- try {- throwIfAborted(signal, 'Agent execution aborted before operation startup');-- const memories = userMemory?.memories;- log(- '[%s] Creating new operation (autoStart: %s) with params: model=%s, provider=%s, tools=%d, messages=%d, manifests=%d, memory=%s',- operationId,- autoStart,- agentConfig?.model,- agentConfig?.provider,- operationToolSet.tools?.length ?? 0,- initialMessages.length,- operationToolSet.manifestMap ? Object.keys(operationToolSet.manifestMap).length : 0,- memories- ? `{contexts:${memories.contexts?.length ?? 0},experiences:${memories.experiences?.length ?? 0},preferences:${memories.preferences?.length ?? 0},identities:${memories.identities?.length ?? 0},activities:${memories.activities?.length ?? 0},persona:${memories.persona ? 'yes' : 'no'}}`- : 'none',- );-- // Initialize operation state - create state before saving- const activatableToolIds = new Set(operationToolSet.activatableToolIds ?? []);- const restoredActivatedToolIds = extractActivatedToolIdsFromMessages(initialMessages)?.filter(- (id) => activatableToolIds.has(id),- );- const activatedStepTools = restoredActivatedToolIds?.length- ? restoredActivatedToolIds.map((id) => ({- activatedAtStep: initialStepCount,- id,- manifest: operationToolSet.manifestMap[id],- source: 'discovery' as const,- }))- : undefined;-- const llmExecutor = await this.resolveLlmExecutor(params.llmExecutor, parentOperationId);- // A member's pushes reach the supervisor's client, so it renders what- // that client declared.- const fileWorksAccepted =- acceptsFileWorks ??- (parentOperationId && appContext?.orchestrationRole === 'member'- ? await this.acceptsFileWorks(parentOperationId)- : undefined);-- const initialState = {- activatedStepTools,- createdAt: new Date().toISOString(),- // Store initialContext for executeSync to use- initialContext,- lastModified: new Date().toISOString(),- // Use the passed initial messages- messages: initialMessages,- // Late-bound execution facts. The device may be unrouted here and get- // bound at a later step boundary (`computeDeviceContext`).- ...((activeDeviceId || deviceSystemInfo) && {- binding: {- device: {- ...(activeDeviceId && { id: activeDeviceId }),- ...(deviceSystemInfo && { systemInfo: deviceSystemInfo }),- },- },- }),- // What the host needs to deliver and retry the run. Hooks are stamped- // right after creation once the dispatcher has serialized them.- host: {- ...(fileWorksAccepted === true && { acceptsFileWorks: true }),- ...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),- ...(params.includeFinalState === true && { includeFinalState: true }),- ...(llmExecutor && { llmExecutor }),- queue: { retries: queueRetries, retryDelay: queueRetryDelay },- },- // Run ledger — everything fixed at creation lives in the typed slots.- metadata: {},- // 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,- editingAgentId: appContext?.editingAgentId,- editingGroupId: appContext?.editingGroupId,- 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,- },- maxSteps,- // modelRuntimeConfig at state level for executor fallback- modelRuntimeConfig,- // Read once during discovery; dropped again as soon as the run changes- // its own credentials (see the creds invalidation after a step).- operationCredentials,- operationId,- // The run's only copy of its tool set. The manifest map is the heaviest- // thing on the state and the state is re-serialized at every step, so the- // former top-level mirrors (`tools`, `toolManifestMap`, `toolSourceMap`,- // `toolExecutorMap`) are no longer written; readers go through- // `selectToolManifestMap` and friends.- operationToolSet,- status: 'idle',- stepCount: initialStepCount,- // How the run executes — frozen from here on.- plan: {- eval: evalRuntime,- execution: executionPlan,- skills: operationSkillSet,- stream,- workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,- },- // Under whose authority the run acts and what it may do — decided here,- // re-presented (never re-derived) at each dispatch boundary.- principal: {- actor: {- bot: botContext,- deviceScope: activeDeviceScope,- shareVisitor: agentShareVisitor,- },- audit: { clientIp: appContext?.clientIp, userAgent: appContext?.userAgent },- // What the run may do, decided once here: device access and the- // approval mode its tool calls answer to.- policy: { deviceAccess: deviceAccessPolicy, userIntervention: userInterventionConfig },- },- // Compat mirrors for a rolling deploy: a worker still running the- // pre-slot build reads only these, and a missing approval mode defaults- // to `manual` there — which parks a headless run on an approval nobody- // can give. Drop them (and the matching entries in- // `normalizeAgentState`'s COMPAT_MIRROR_PATHS) once no pre-slot worker- // can pick up a step.- enableExpertise,- expertise,- userInterventionConfig,- // What the model is told about the run's world — frozen from here on;- // the context engine reads it on every step.- world: {- agent: agentConfig,- ...((botPlatformContext || discordContext) && {- channel: { botPlatform: botPlatformContext, discord: discordContext },- }),- connectorOwnershipNote,- disabledPluginIds,- enableExpertise,- eval: evalContext,- expertise,- group: agentGroup,- projectInstructions,- searchDecision,- userMemory,- userTimezone,- },- } as Partial<AgentState>;-- // Use coordinator to create operation, automatically sends initialization event.- // For an in-group broadcast/speak member, mirror its Gateway stream events- // onto the supervisor op's channel (parentOperationId) so they flow down the- // supervisor's existing WebSocket — the client subscribes to one connection,- // not one per member (single-connection multiplexing).- const mirrorToOperationId =- appContext?.orchestrationRole === 'member' ? (parentOperationId ?? undefined) : undefined;- await traceStartStage('runtime_meta', () =>- this.coordinator.createAgentOperation(operationId, {- acceptsMemberRuntimeEnd,- agentConfig,- // Persisted so a queue worker that never ran this op's init still- // applies the owner-configured visitor redaction policy instead of the- // fail-closed full strip. See `gatewayVisitorRedaction.ts`.- visitorRedaction: agentShareVisitor- ? {- showErrorDetails: agentShareVisitor.showErrorDetails,- showModelInfo: agentShareVisitor.showModelInfo,- }- : undefined,- mirrorToOperationId,- modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),- // Share-visitor runs execute as the creator (`userId`) but stream only- // to the visitor — the gateway registers the WS channel under this id.- streamOwnerUserId: agentShareVisitor?.visitorUserId,- userId,- workspaceId: this.workspaceId,- }),- );- operationCreated = true;-- // Save initial state- await traceStartStage('save_state', () =>- this.coordinator.saveAgentState(operationId, initialState as any),- );-- // Register external hooks- hookDispatcher.register(operationId, hooks ?? []);- hooksRegistered = hookDispatcher.hasHooks(operationId);- if (hooksRegistered) {- // Persist webhook configs to state metadata for production mode- const serializedHooks = hookDispatcher.getSerializedHooks(operationId);- if (serializedHooks && serializedHooks.length > 0) {- const currentState = await this.coordinator.loadAgentState(operationId);- if (currentState) {- await this.coordinator.saveAgentState(operationId, {- ...currentState,- host: { ...currentState.host, hooks: serializedHooks },- });- }- }- }-- if (interventionResolution) {- const preparedState = await this.coordinator.loadAgentState(operationId);- if (!preparedState) {- throw new Error(`Intervention continuation state disappeared: ${operationId}`);- }- const preparation = {- deduplicationId: deriveAgentInterventionQueueDeduplicationId(- operationId,- initialStepCount,- ),- resolutionRequestId: interventionResolution.resolutionRequestId,- state: 'ready' as const,- stepIndex: initialStepCount,- };- await this.coordinator.saveAgentState(operationId, {- ...preparedState,- metadata: {- ...preparedState.metadata,- agentInterventionPreparation: preparation,- },- });- const preparationPersisted =- await this.agentOperationModel.recordAgentInterventionPreparation(- operationId,- preparation,- );- if (!preparationPersisted) {- throw new Error(- `Failed to persist intervention continuation preparation: ${operationId}`,- );- }- onInterventionPrepared?.();- }-- await params.onOperationCreated?.(operationId);-- throwIfAborted(signal, 'Agent execution aborted before first step scheduling');-- let messageId: string | undefined;- let autoStarted = false;-- if (autoStart && this.queueService) {- const deduplicationId = interventionResolution- ? deriveAgentInterventionQueueDeduplicationId(operationId, initialStepCount)- : undefined;- // Both local and queue modes use scheduleMessage- // LocalQueueServiceImpl uses setTimeout + callback mechanism- // QStashQueueServiceImpl schedules HTTP requests- const queueService = this.queueService;- messageId = await traceStartStage('schedule_step', () =>- queueService.scheduleMessage({- context: initialContext,- deduplicationId,- delay: 50, // Short delay for startup- endpoint: `${this.baseURL}/run`,- operationId,- priority: 'high',- retryDelay: queueRetryDelay,- retries: queueRetries,- stepIndex: initialStepCount,- }),- );- if (interventionResolution && deduplicationId) {- await this.persistInterventionDispatchAck({- deduplicationId,- messageId,- operationId,- resolutionRequestId: interventionResolution.resolutionRequestId,- });- }- autoStarted = true;- log('[%s] Scheduled first step (messageId: %s)', operationId, messageId);- }-- if (!autoStarted) {- log('[%s] Created operation without auto-start', operationId);- }-- return { autoStarted, messageId, operationId, success: true };- } catch (error) {- if (isAbortError(error)) {- if (hooksRegistered) {- hookDispatcher.unregister(operationId);- }-- if (operationCreated) {- try {- await this.coordinator.deleteAgentOperation(operationId);- } catch (cleanupError) {- console.error('Failed to cleanup aborted operation %s: %O', operationId, cleanupError);- }- }-- log('[%s] Operation creation aborted before scheduling', operationId);- throw error;- }-- console.error('Failed to create operation %s: %O', operationId, error);- throw error;- }- }-- /**- * Query the canonical UIChatMessage[] snapshot for the active topic — the- * same shape the `message.getMessages` trpc lambda returns to the client.- * Attached to step_start / agent_runtime_end stream events so the client- * can use the pushed payload directly instead of refetching from DB.- *- * Returns undefined when the topic isn't known yet (e.g. very early in- * bootstrap before the topic row has been committed) so callers can skip- * the `uiMessages` field entirely instead of pushing an empty array.- */- async queryUiMessages(- agentState: AgentState,- options?: {- /**- * Skip the Work-summary assembly for mid-stream (step_start) snapshots —- * each step would otherwise re-run the per-type Work queries. Terminal- * (agent_runtime_end) snapshots keep works so the settled message list- * carries the round's Work chips. The client preserves previously- * rendered works when applying a skipped snapshot (`preserveWorks`).- */- skipWorks?: boolean;- },- ): Promise<UIChatMessage[] | undefined> {- 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?.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?.origin?.threadId ?? undefined;- if (!agentId || !topicId) return undefined;-- // A share visitor's Works are registered under the visitor's share scope- // (`registerFileWorks`), which the ordinary scope never resolves — without- // it the terminal snapshot carries no Work card and the visitor only sees- // it after a reload through `shareChat.getMessages`. The visitor surface- // always opts in to file Works on that read path, and visitor runs never- // use message patches, so this snapshot only ever reaches that client.- const workAccessScope = resolveRunWorkAccessScope({- shareVisitor: agentState?.principal?.actor?.shareVisitor,- topicId,- });- const isShareVisitorRun = !!workAccessScope;- // `file` Works stay out of the push unless the receiving client declared- // it renders them: released desktop builds crash on the unknown type.- const includeFileWorks = isShareVisitorRun || agentState?.host?.acceptsFileWorks === true;-- try {- return await this.messageService.queryMessages(- {- agentId,- groupId,- ...(includeFileWorks && { includeFileWorks: true }),- skipWorks: options?.skipWorks,- threadId,- topicId,- },- // The run's own topic is already resolved and authorized; an agent-share- // visitor run executes under the CREATOR's identity, so without this the- // creator-facing exclusion in `MessageModel.query()` returns an EMPTY- // snapshot for the visitor's topic, and the client applies it as the- // terminal Source of Truth — wiping the conversation the run just- // produced. Visitor-facing redaction of the pushed snapshot happens in- // `GatewayStreamNotifier`.- { allowShareVisitor: true, ...(workAccessScope && { workAccessScope }) },- );- } catch (error) {- // Stream events must never fail the step. If the DB hiccups, fall back- // to letting the client refresh as before.- console.error('[queryUiMessages] Failed to load uiMessages snapshot: %O', error);- return undefined;- }- }-- /** Native harness + Gateway mux is the only producer of message patches. */- /**- * Whether this run reconciles the client's message list through- * `message_patch` revisions instead of pushing whole `uiMessages` snapshots.- *- * Decided by the capability the starting client declared when the operation- * was created (`host.clientProtocol`), NOT by a user preference: the run is- * delivered to whatever bundle that client is, and a desktop build older than- * `message_patch` would drop every mid-run reconciliation it was sent.- *- * A share visitor is always excluded — the visitor surface has no- * owner-scoped read to reconcile against.- */- private usesGatewayMessagePatch(agentState: AgentState): boolean {- if (agentState.principal?.actor?.shareVisitor) return false;- return agentState.host?.clientProtocol === 2;- }-- /**- * Execute Agent step- */- async executeStep(params: AgentExecutionParams): Promise<AgentExecutionResult> {- const {- operationId,- stepIndex,- context,- humanInput,- approvedToolCall,- rejectionReason,- rejectAndContinue,- resumeAsyncTool,- finishAfterAsyncTool,- groupMemberTimeout,- toolMessageId,- verifyAsyncToolBarrier,- asyncToolVerifyAttempt,- resumeClientLlm,- clientLlmWaitExpired,- externalRetryCount = 0,- lockRetryAttempt = 0,- inlineContinuation = false,- retainStepLock = false,- stepLockOwner: providedStepLockOwner,- } = params;-- // Group member timeout watchdog: enforce a member's deadline without claiming- // the step lock. No-op if the member already finished; otherwise interrupt it- // and bridge a `timeout` completion so the parked supervisor resumes/finishes.- if (groupMemberTimeout) {- return this.handleGroupMemberTimeout(groupMemberTimeout);- }-- // Expiry check of a `waiting_for_client` park. It executes nothing: the CAS- // on the durable row decides whether the wait (still parked, same park) ends- // here or a resume already took the run. Ahead of the terminal-row guard- // below, because a retried expiry whose first attempt settled the row but- // failed to finish must still get to finish it.- if (clientLlmWaitExpired) {- const expired = await this.expireClientLlmWait(operationId, clientLlmWaitExpired);- return {- nextStepScheduled: false,- state: expired ? { status: 'error' } : {},- stepResult: null,- success: true,- };- }-- // Redis keeps the resumable step state, but the durable operation row is- // the authority for cancellation/recovery. A queued QStash delivery can- // outlive a crashed process and arrive after Goal recovery has atomically- // marked that operation interrupted. ACK it without touching the old- // topic; otherwise the abandoned attempt can finish concurrently with its- // replacement and submit a second Acceptance run.- try {- const durableOperation = await this.agentOperationModel.findById(operationId);- if (- durableOperation &&- ['done', 'error', 'interrupted', 'abandoned'].includes(durableOperation.status)- ) {- log(- '[%s][%d] Skipping delivery for terminal durable operation (%s)',- operationId,- stepIndex,- durableOperation.status,- );- return {- nextStepScheduled: false,- state: {- status:- durableOperation.status === 'abandoned' ? 'interrupted' : durableOperation.status,- },- stepResult: null,- success: true,- };- }- } catch (error) {- // Preserve runtime availability when the durable store has a transient- // read failure. The step lock and normal persistence path still apply.- log('[%s][%d] Durable operation status check failed: %O', operationId, stepIndex, error);- }-- // Watchdog re-check for a parked async-tool wait: re-run the barrier + CAS- // without claiming the step lock or executing anything. Idempotent — the- // CAS guarantees at most one real resume regardless of how many checks run.- // Opt back into `scheduleVerifyOnHold` with the next attempt so an- // unsatisfied barrier re-arms (bounded backoff) instead of giving up after- // a single shot — bounded watchdog retry ensures transient misses are recovered.- if (verifyAsyncToolBarrier) {- const attempt = asyncToolVerifyAttempt ?? 1;- log(- '[%s][%d] Running async-tool barrier verify (attempt %d)',- operationId,- stepIndex,- attempt,- );- const resumed = await this.tryResumeParentFromAsyncTool(- { parentOperationId: operationId },- { scheduleVerifyOnHold: true, verifyAttempt: attempt + 1 },- );- return {- nextStepScheduled: resumed,- state: {},- stepResult: null,- success: true,- };- }-- // ===== Distributed lock: prevent duplicate execution from QStash retries =====- const stepLockOwner = providedStepLockOwner ?? createStepLockOwner(operationId, stepIndex);- const claimed = await this.coordinator.tryClaimStep(- operationId,- stepIndex,- STEP_LOCK_TTL_SECONDS,- stepLockOwner,- );- if (!claimed) {- // Someone else owns this operation now. Whatever this invocation buffered- // for the trace belongs to their partial from here — every return below- // leaves without it, so drop it once, up front, rather than per exit.- this.traceRecorder.discardPartial();-- let currentState: AgentState | null | undefined = null;- try {- currentState = await this.coordinator.loadAgentState(operationId);- } catch (error) {- log(- '[%s][%d] Failed to load state while handling step lock conflict: %O',- operationId,- stepIndex,- error,- );- }-- const currentStepCount = currentState?.stepCount;- if (currentState && typeof currentStepCount === 'number' && currentStepCount > stepIndex) {- if (- this.shouldReplayPendingInterventionLifecycle(currentState, stepIndex, externalRetryCount)- ) {- // This is a retry of a completed human-approval step whose Review- // lifecycle did not finish. Do not ACK it while another delivery still- // owns the step lock: once that owner releases the lock, QStash must- // redeliver so the lifecycle-only replay below can publish the Review.- log(- '[%s][%d] Pending intervention lifecycle retry is still locked; requesting redelivery',- operationId,- stepIndex,- );- return {- locked: true,- nextStepScheduled: false,- state: currentState,- success: false,- };- }-- log(- '[%s][%d] Step lock conflict is stale (stepCount=%d), skipping',- operationId,- stepIndex,- currentStepCount,- );- return {- nextStepScheduled: false,- state: currentState,- stepResult: null,- success: true,- };- }-- // The lock is held by a live step of this operation, and this delivery is- // not a stale duplicate — it still has to run once the holder is done.- //- // Don't lean on the queue's own retry budget for that wait: the lock is- // heartbeat-refreshed for as long as the holding step runs (unbounded),- // while the budget is a handful of fixed-delay retries. A step that runs- // longer than the budget therefore exhausts it and the delivery is- // dead-lettered — the step it carried is then never executed. Re-queue a- // fresh delivery on our own bounded backoff instead, and ACK this one.- //- // The re-delivery has to carry this delivery's own resume/intervention- // payload: a human-intervention resume (`processHumanIntervention`) or an- // async-tool resume (`tryResumeParentFromAsyncTool`) can lose the lock- // race too, and re-queueing only the retry counter would run a plain step- // once the lock clears — silently dropping the approval / human input, or- // leaving a parked operation parked forever. Undefined fields drop out of- // the JSON body, so unrelated deliveries still send just the counter.- const nextLockRetryAttempt = lockRetryAttempt + 1;- if (this.queueService && nextLockRetryAttempt <= STEP_LOCK_RETRY_MAX_ATTEMPTS) {- const delay = stepLockRetryDelayMs(nextLockRetryAttempt);- log(- '[%s][%d] Step lock conflict — re-queueing attempt %d/%d in %dms',- operationId,- stepIndex,- nextLockRetryAttempt,- STEP_LOCK_RETRY_MAX_ATTEMPTS,- delay,- );-- try {- await this.queueService.scheduleMessage({- context,- delay,- endpoint: `${this.baseURL}/run`,- operationId,- payload: {- approvedToolCall,- finishAfterAsyncTool,- humanInput,- lockRetryAttempt: nextLockRetryAttempt,- rejectAndContinue,- rejectionReason,- resumeAsyncTool,- resumeClientLlm,- toolMessageId,- },- priority: 'high',- retryDelay:- typeof currentState?.host?.queue?.retryDelay === 'string'- ? currentState.host?.queue?.retryDelay- : undefined,- retries:- typeof currentState?.host?.queue?.retries === 'number'- ? currentState.host?.queue?.retries- : undefined,- stepIndex,- });-- return {- locked: true,- lockRescheduled: true,- nextStepScheduled: true,- state: {},- success: true,- };- } catch (error) {- // Fall through to the retryable response so the delivery isn't lost.- log(- '[%s][%d] Failed to re-queue after step lock conflict: %O',- operationId,- stepIndex,- error,- );- }- }-- log(- '[%s][%d] Step lock conflict — another instance is executing this step, returning locked',- operationId,- stepIndex,- );- return {- locked: true,- nextStepScheduled: false,- state: {},- success: false,- };- }-- await this.agentOperationModel.touchRunning(operationId).catch((error) => {- log('[%s][%d] Operation lease refresh failed: %O', operationId, stepIndex, error);- });- const stopStepLockHeartbeat = this.startStepLockHeartbeat(- operationId,- stepIndex,- stepLockOwner,- );-- // Hoisted so the shared `finally` can stop it on every exit path — an- // orphaned interval would keep polling Redis for a step that is long gone.- let stepAbortPoll: ReturnType<typeof setTimeout> | undefined;- // Clearing the timeout is not enough: a poll already awaiting the state read- // would schedule the next one after the step is gone, leaking a loop that- // re-reads the store forever for a finished operation.- let stepAbortPollStopped = false;-- // Hoisted so the error-path snapshot finalize can record an- // approximate startedAt for the failing step. The inner `startAt` at the- // runtime.step() call site stays as the authoritative start for the- // success path.- const stepStartAt = Date.now();-- // Hoisted so the shared `finally` knows whether the next step stays in this- // invocation. When it does, the accumulated trace partial stays in memory;- // on every other exit some other process reads it, so it has to be durable.- let handedOffInline = false;-- // OTel invoke_agent span. Wraps the entire step body so child spans- // (chat / execute_tool / context_engineering) auto-nest via the active- // context. Started with minimal attrs; agent/model/topic are added once- // agentState is loaded.- const invokeAgentSpan = agentRuntimeTracer.startSpan(invokeAgentSpanName(), {- attributes: buildInvokeAgentAttributes({ operationId, stepIndex }),- });- const invokeAgentCtx = otelTrace.setSpan(otelContext.active(), invokeAgentSpan);-- try {- return await otelContext.with(invokeAgentCtx, async () => {- log('[%s][%d] Start step executing...', operationId, stepIndex);-- // Load agent state BEFORE publishing step_start so we can attach the- // canonical UIChatMessage snapshot to the event payload. step_start- // fires after the previous step's DB writes are awaited durable, so- // the snapshot query here reflects strongly-consistent state — that's- // the contract that lets the client treat the pushed uiMessages as- // the source of truth instead of doing its own refetch.- const agentState = await this.coordinator.loadAgentState(operationId);-- if (!agentState) {- throw new Error(`Agent state not found for operation ${operationId}`);- }-- // A parked approval step is already durable before its generic Review- // is published. When that final Review write fails, the request returns- // non-2xx and QStash retries this SAME step with `upstash-retried > 0`.- // The runtime state now has stepCount > stepIndex, so the ordinary stale- // delivery guard below would ACK it and permanently strand the Review.- // Replay only the idempotent completion lifecycle: never run beforeStep,- // runtime.step (LLM/tools), afterStep, or saveStepResult again.- if (- agentState.stepCount > stepIndex &&- this.shouldReplayPendingInterventionLifecycle(agentState, stepIndex, externalRetryCount)- ) {- agentState.metadata = {- ...agentState.metadata,- externalRetryCount,- };-- const reason = 'waiting_for_human' as const;- const completionSignalEvents = await this.completionLifecycle.emitSignalEvents(- operationId,- agentState,- reason,- );- await this.completionLifecycle.dispatchHooks(operationId, agentState, reason);- await this.recordInterventionLifecycleCompletion(operationId, agentState, stepIndex);- await this.traceRecorder.finalize(operationId, {- appendEventsToLastStep: completionSignalEvents,- completionReason: reason,- state: agentState,- });-- log('[%s][%d] Replayed pending intervention lifecycle', operationId, stepIndex);- return {- nextStepScheduled: false,- state: agentState,- stepResult: null,- success: true,- };- }-- const gatewayMessagePatchEnabled = this.usesGatewayMessagePatch(agentState);- const { uiMessages: stepStartUiMessages, messages: stepEntryMessages } =- await this.queryStepEntryMessages(agentState);- await this.streamManager.publishStreamEvent(operationId, {- data: gatewayMessagePatchEnabled- ? { messageRevision: stepIndex }- : { ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }) },- stepIndex,- type: 'step_start',- });-- agentState.metadata = {- ...agentState.metadata,- externalRetryCount,- };-- // Enrich invoke_agent span with agent identity now that state is loaded.- const stateAgentConfig = agentState.world?.agent as- { description?: string | null; title?: string | null } | undefined;- const stateModel = agentState.modelRuntimeConfig?.model;- const stateProvider = agentState.modelRuntimeConfig?.provider;- invokeAgentSpan.updateName(invokeAgentSpanName(stateAgentConfig?.title ?? undefined));- invokeAgentSpan.setAttributes(- buildInvokeAgentAttributes({- agentDescription: stateAgentConfig?.description ?? undefined,- agentId: agentState.origin?.agentId,- agentName: stateAgentConfig?.title ?? undefined,- conversationId: agentState.origin?.topicId,- operationId,- provider: stateProvider,- requestModel: stateModel,- stepIndex,- }),- );-- // Layer 2 defense: catch extremely delayed retries that arrive after lock TTL expired- if (agentState.stepCount > stepIndex) {- log(- '[%s][%d] Step already completed (stepCount=%d), skipping',- operationId,- stepIndex,- agentState.stepCount,- );- return {- nextStepScheduled: false,- state: agentState,- stepResult: null,- success: true,- };- }-- // Early exit: skip step if operation is already in a terminal state- // This prevents executing expensive LLM/tool calls after timeout or interruption- if (- agentState.status === 'interrupted' ||- agentState.status === 'done' ||- agentState.status === 'error'- ) {- log(- '[%s][%d] Skipping step — operation already in terminal state: %s',- operationId,- stepIndex,- agentState.status,- );-- const reason = this.determineCompletionReason(agentState);-- await this.completionLifecycle.emitSignalEvents(operationId, agentState, reason);-- // Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize- await this.completionLifecycle.dispatchHooks(operationId, agentState, reason);-- return {- nextStepScheduled: false,- state: agentState,- stepResult: null,- success: true,- };- }-- // A run parked for a client moves only through its own resume: any other- // delivery (a duplicate, a stale redrive) would replay the call with no- // client to take it.- if (agentState.status === 'waiting_for_client' && !resumeClientLlm) {- log('[%s][%d] Skipping step — operation is waiting for a client', operationId, stepIndex);- return {- nextStepScheduled: false,- state: agentState,- stepResult: null,- success: true,- };- }-- // Agent Share: re-prove this visitor run's authorization on EVERY step.- // A revocation only flips the `agent_shares` row — nothing tears down- // an operation that was already created, so without this the run keeps- // going under the creator's credentials/budget for the rest of its- // (potentially very long) lifetime, and the visitor's own Stop button- // has already stopped working (it re-resolves the now-private share and- // gets FORBIDDEN). Re-checking here means a revocation cannot survive a- // step boundary. See `AgentShareModel.isRunStillAuthorized`'s JSDoc for- // why one query covers every revocation path (visibility flip — which- // is what turning sharing off does — share delete, agent delete).- if (this.delegate.verifyShareRunStillAuthorized) {- const shareMarker = agentState.principal?.actor?.shareVisitor as- { agentId?: string; shareId?: string } | undefined;- if (shareMarker?.agentId && shareMarker.shareId) {- let stillAuthorized = false;- try {- stillAuthorized = await this.delegate.verifyShareRunStillAuthorized({- agentId: shareMarker.agentId,- shareId: shareMarker.shareId,- });- } catch (error) {- // Fail closed: a read failure must not be read as "still- // authorized". Falls through to the abort below with- // `stillAuthorized` left `false`.- log(- '[%s][%d] Share run authorization re-check failed: %O',- operationId,- stepIndex,- error,- );- }- if (!stillAuthorized) {- return this.buildShareAbortResult(operationId, agentState);- }- }- }-- let beforeStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];-- // Dispatch beforeStep hooks- try {- 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- // reasoning (and same predicate) as the completion-signal guard in- // `CompletionLifecycle.emitSignalEvents`.- const beforeStepSignalEmission = isAgentShareRun(agentState)- ? undefined- : await emitAgentSignalSourceEvent(- {- payload: {- agentId: beforeStepOrigin.agentId,- operationId,- serializedContext: undefined,- stepIndex,- topicId: beforeStepOrigin.topicId,- turnCount: agentState?.stepCount || 0,- },- sourceId: `${operationId}:before:${stepIndex}`,- sourceType: 'runtime.before_step',- },- {- agentId: beforeStepOrigin.agentId,- db: this.serverDB,- userId: beforeStepOrigin.userId || this.userId,- workspaceId: this.workspaceId,- },- { ignoreError: true },- );- beforeStepSignalEvents = toAgentSignalSnapshotEvents(beforeStepSignalEmission);- await hookDispatcher.dispatch(- operationId,- 'beforeStep',- {- agentId: beforeStepOrigin.agentId || '',- finalState: agentState,- operationId,- stepIndex,- steps: agentState?.stepCount || 0,- userId: beforeStepOrigin.userId || this.userId,- },- agentState?.host?.hooks,- );- } catch (hookError) {- log('[%s] beforeStep hook dispatch error: %O', operationId, hookError);- }-- // Per-step buffer for context engine input/output. Populated by the- // `tracingContextEngine` callback passed into the executor context;- // consumed by traceRecorder.appendStep below. Routing CE this way keeps- // its heavy payload (agentDocuments, systemRole, …) out of- // `stepResult.events` and therefore out of the Redis state pipeline.- //- // Context: contextEngine.input (agentDocuments) was ~2.7MB/step,- // hitting Upstash Redis 10MB limit. Bypassing events keeps the heavy- // payload in trace only, reducing per-step Redis state by ~500x.- let contextEnginePayload:- { input: unknown; metadata?: unknown; output: unknown } | undefined;-- // Create Agent and Runtime instances- // Use agentState.metadata which contains the full app context (topicId, agentId, etc.)- // operationMetadata only contains basic fields (agentConfig, modelRuntimeConfig, userId)- // Interrupts arrive as a sentinel key beside the persisted state — the- // request that asked for the stop runs in a different invocation, so- // there is no in-process controller to share. Poll while the step is alive- // and cancel locally, otherwise a multi-minute tool would keep running- // long after the user asked it to stop.- const stepAbortController = new AbortController();- // Serialized on purpose: `setInterval` would fire a new read without- // waiting for the last one, so a slow or failing state store turns every- // concurrent run into a growing pile of overlapping requests — the load- // spikes exactly when the store is already struggling. Each read is- // scheduled only after the previous one settles, and failures back off.- let abortPollFailures = 0;- let lastLegacyInterruptStatePollAt = Date.now();- const pollForAbort = async () => {- try {- // Prefer the sentinel. During the first rolling deployment, an old- // worker can still write only the authoritative state, so sample- // that large blob at a much lower cadence until all writers have- // sentinel support.- let interrupted = await this.coordinator.isInterrupted(operationId);- const now = Date.now();- if (- !interrupted &&- now - lastLegacyInterruptStatePollAt >= LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS- ) {- lastLegacyInterruptStatePollAt = now;- interrupted =- (await this.coordinator.loadAgentState(operationId))?.status === 'interrupted';- }- abortPollFailures = 0;- if (interrupted) {- stepAbortController.abort();- return;- }- } catch (error) {- abortPollFailures += 1;- log('[%s][%d] Abort poll failed: %O', operationId, stepIndex, error);- }-- if (stepAbortPollStopped || stepAbortController.signal.aborted) return;-- stepAbortPoll = setTimeout(- pollForAbort,- STEP_ABORT_POLL_INTERVAL_MS *- Math.min(2 ** abortPollFailures, STEP_ABORT_POLL_MAX_BACKOFF),- );- };- stepAbortPoll = setTimeout(pollForAbort, STEP_ABORT_POLL_INTERVAL_MS);-- const { runtime } = await this.createAgentRuntime({- abortSignal: stepAbortController.signal,- agentState,- operationId,- stepIndex,- tracingContextEngine: (input, output, metadata) => {- contextEnginePayload = { input, metadata, output };- },- });-- // Handle human intervention- let currentContext = context;- // The wait this step resumes, if any: a resumed call that finds no client- // again re-parks under the same deadline, so retries never extend it.- let resumedClientLlmWait: AgentRunClientLlmWait | undefined;- let currentState = agentState;-- if (humanInput || approvedToolCall || rejectionReason) {- const interventionResult = await this.humanIntervention.process(currentState, {- approvedToolCall,- humanInput,- rejectAndContinue,- rejectionReason,- toolMessageId,- });- currentState = interventionResult.newState;- currentContext = interventionResult.nextContext;- }-- // Resume from a parked async-tool wait (server sub-agent completion- // bridge). Every deferred tool has delivered its result by now, so clear- // the pending set, refresh messages from the DB (to pick up the tool- // results written out-of-band), and re-enter the LLM with them.- if (resumeAsyncTool && currentState.status === 'waiting_for_async_tool') {- const refreshed = await this.refreshMessagesFromDB(currentState);- const pendingTools = (currentState.pendingToolsCalling ?? []) as ChatToolPayload[];- const resumeParentMessageId = this.resolveAsyncToolResumeParentMessageId(- refreshed,- pendingTools,- );- currentState = structuredClone(currentState);- currentState.messages = refreshed;- currentState.pendingToolsCalling = [];- currentState.status = 'running';- currentState.interruption = undefined;- // Whatever ran while this operation was parked is invisible from- // here: a sub-agent that saved a credential cleared its own snapshot,- // not this one. Drop ours rather than render a list that predates it.- currentState.operationCredentials = undefined;- currentState.lastModified = new Date().toISOString();- // A resume op (e.g. approving a callSubAgent) seeds its assistant- // placeholder before running the tool; when that tool is deferred the- // op parks with the seed unclaimed. Fill it now — creating another- // assistant leaves the seed as an empty "…" sibling branch that hides- // the real answer.- const seededAssistantMessageId = currentState.pendingAssistantMessageId;- currentContext = {- payload: {- ...(seededAssistantMessageId && { assistantMessageId: seededAssistantMessageId }),- parentMessageId: resumeParentMessageId,- },- phase: 'user_input',- } as AgentRuntimeContext;- log(- '[%s][%d] Resuming from async tool with %d messages (parent=%s)',- operationId,- stepIndex,- refreshed.length,- resumeParentMessageId,- );- }-- // Continue a run parked in `waiting_for_client`: a client that can run the- // provider asked for it (`resumeFromClientLlmWait` already recorded it as- // the run's executor). Replay the parked LLM turn into the assistant row- // it created, on the messages the parked step had.- if (resumeClientLlm && currentState.status === 'waiting_for_client') {- const wait = currentState.clientLlmWait;- resumedClientLlmWait = wait;- currentState = structuredClone(currentState);- currentState.status = 'running';- currentState.clientLlmWait = undefined;- currentState.error = undefined;- currentState.lastModified = new Date().toISOString();- if (wait?.assistantMessageId)- currentState.pendingAssistantMessageId = wait.assistantMessageId;- currentContext = buildClientLlmWaitResumeContext(wait);- log(- '[%s][%d] Resuming from waiting_for_client (assistant=%s)',- operationId,- stepIndex,- wait?.assistantMessageId,- );- }-- // Finish a parked supervisor op WITHOUT another LLM turn (group- // orchestration skipCallSupervisor / delegate). Refresh messages so the- // final group conversation is captured, transition straight to `done`,- // and let the standard `!shouldContinue` finalization below record- // completion + dispatch hooks. Skips runtime.step entirely.- let forcedFinishState: AgentState | undefined;- if (finishAfterAsyncTool && currentState.status === 'waiting_for_async_tool') {- const refreshed = await this.refreshMessagesFromDB(currentState);- currentState = structuredClone(currentState);- currentState.messages = refreshed;- currentState.pendingToolsCalling = [];- currentState.status = 'done';- currentState.interruption = undefined;- currentState.lastModified = new Date().toISOString();- forcedFinishState = currentState;- log(- '[%s][%d] Finishing parked supervisor op after async tool (%d messages)',- operationId,- stepIndex,- refreshed.length,- );- }-- // Pre-step computation: extract device context from DB messages- // Follows front-end computeStepContext pattern — computed at step boundary, not inside executors- // Only for a run that may actually touch a device: the executors read the- // id through the same gate, so binding one here for a forbidden run buys- // nothing and puts the device's working directory and system info into- // the prompt variables (`serverCallLlmContextBuilder`).- //- // A run whose plan still leaves the device open (unrouted, not locked)- // keeps the remote-device picker for its whole lifetime, so it must keep- // following it: re-read on every step and let the latest activation win.- // Binding only once made every later `activateDevice` report success- // while local tools stayed on the first device.- const executionPlan = currentState.plan?.execution;- const deviceStillSelectable =- !!executionPlan &&- isDeviceCapablePlan(executionPlan) &&- !isDeviceLockedPlan(executionPlan);- if (- (!currentState.binding?.device?.id || deviceStillSelectable) &&- runMayUseDevice(currentState)- ) {- // Interventions and async resumes can change tool rows after the- // entry snapshot. Those paths still need a fresh device read.- const canReuseEntryMessages =- !humanInput &&- !approvedToolCall &&- !rejectionReason &&- !resumeAsyncTool &&- !finishAfterAsyncTool;- const deviceContext = await this.computeDeviceContext(- currentState,- canReuseEntryMessages ? stepEntryMessages : undefined,- );- if (deviceContext && deviceContext.activeDeviceId !== currentState.binding?.device?.id) {- currentState.binding = {- ...currentState.binding,- device: {- id: deviceContext.activeDeviceId,- platform: deviceContext.devicePlatform,- systemInfo: deviceContext.deviceSystemInfo,- },- };- log(- '[%s][%d] Pre-step: device context computed from messages (deviceId: %s)',- operationId,- stepIndex,- deviceContext.activeDeviceId,- );- }- }-- // Queued follow-ups live in the client's composer, not in this state.- // The client mirrors them into a flag; the agent reads it from the step- // context and hands the turn back at its next decision point, so the- // follow-up starts as the next turn instead of after the whole run.- // This read is authoritative for the step: a value carried in on the- // incoming context must not keep a hand-back the user has withdrawn.- if (currentContext && !forcedFinishState) {- const hasQueuedMessages = await this.readQueuedMessagesFlag(operationId, stepIndex);- if (hasQueuedMessages !== Boolean(currentContext.stepContext?.hasQueuedMessages)) {- const stepContext = { ...currentContext.stepContext };- if (hasQueuedMessages) stepContext.hasQueuedMessages = true;- else delete stepContext.hasQueuedMessages;- currentContext = { ...currentContext, stepContext };- }- }-- // Execute step (skipped when force-finishing a parked supervisor op).- const startAt = Date.now();- logToolCallPc(operationId, stepIndex, 'post.runtime_step_entered', () => ({- forcedFinish: Boolean(forcedFinishState),- stateStatus: currentState.status,- }));- let stepResult = forcedFinishState- ? { events: [], newState: forcedFinishState, nextContext: undefined }- : await runtime.step(currentState, currentContext);-- // Inner runtime.step() catches model-runtime exceptions and stuffs the- // raw error into newState.error without re-throwing — so the outer- // catch at the bottom of this method never sees them. Normalize +- // classify here so the raw error doesn't reach Redis state, the- // success-path trace finalize, or `persistCompletion`'s JSONB write.- if (stepResult.newState.error) {- stepResult.newState.error = formatErrorForState(stepResult.newState.error);- }- logToolCallPc(operationId, stepIndex, 'post.runtime_step_returned', () => ({- errorCategory: stepResult.newState.error?.category ?? null,- errorRetryable: stepResult.newState.error?.retryable ?? null,- nextContextPresent: stepResult.nextContext !== undefined,- stateStatus: stepResult.newState.status,- }));-- // Check if the operation was interrupted while the step was executing- // (e.g., user clicked abort during a long LLM call). Prefer the tiny- // sentinel, but fall back to the state once at the step boundary while- // old workers that only write `status: 'interrupted'` may still be- // running during a rolling deployment.- const sentinelInterrupted = await this.coordinator.isInterrupted(operationId);- const wasInterrupted = sentinelInterrupted- ? true- : (await this.coordinator.loadAgentState(operationId))?.status === 'interrupted';- logToolCallPc(operationId, stepIndex, 'post.latest_state_loaded', () => ({- interrupted: wasInterrupted,- }));- if (wasInterrupted) {- // Stop can be persisted after a client-tool executor's last local- // signal check but before this reconciliation read. If that executor- // just returned a parked state, run the agent's existing abort path- // once so every pending tool call gets a terminal row before the- // interrupted state is saved.- if (- stepResult.newState.status === 'waiting_for_async_tool' &&- stepResult.newState.pendingToolsCalling?.length &&- currentContext- ) {- const interruptedState = structuredClone(stepResult.newState);- interruptedState.status = 'interrupted';- const abortContext: AgentRuntimeContext = {- ...currentContext,- payload: {- ...(currentContext.payload as Record<string, unknown>),- hasToolsCalling: true,- toolsCalling: interruptedState.pendingToolsCalling,- },- phase: 'llm_result',- };- const abortResult = await runtime.step(interruptedState, abortContext);- stepResult = {- ...abortResult,- events: [...stepResult.events, ...abortResult.events],- };- }-- stepResult.newState.status = 'interrupted';- stepResult.newState.lastModified = new Date().toISOString();- log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);- } else if (stepResult.newState.status === 'error') {- // No client could run the step's LLM call: park for one instead of- // failing (U4c). The parked state is what the step started from, so- // a resume replays the same call.- const parkedState = await this.parkForClientLlm(- operationId,- stepResult.newState,- currentContext,- resumedClientLlmWait?.expiresAt,- currentState,- );- if (parkedState) {- stepResult = { ...stepResult, newState: parkedState, nextContext: undefined };- }- }-- // Decide whether to schedule next step (hoisted above the save: it also- // gates the pre-snapshot file-Work registration below)- const shouldContinue = this.shouldContinueExecution(- stepResult.newState,- stepResult.nextContext,- );-- // Register entity-file Works BEFORE the terminal save: `saveStepResult`- // publishes `agent_runtime_end`, whose `uiMessages` snapshot the client- // adopts as the settled message list — the Work rows must exist by then- // or the file-Work card stays absent until a manual refresh. Perceived- // loading is not extended: for runs with entity edits the early- // `visible_output_end` is suppressed (see `createAgentRuntime`), so- // loading covers this export window by design. Idempotent — the- // dispatchHooks backstop below no-ops via the state marker.- if (!shouldContinue) {- const preSaveReason = this.determineCompletionReason(stepResult.newState);- if (preSaveReason === 'waiting_for_human') {- stepResult.newState.metadata = {- ...stepResult.newState.metadata,- [INTERVENTION_LIFECYCLE_CHECKPOINT_KEY]: {- state: 'pending',- stepIndex,- } satisfies InterventionLifecycleCheckpoint,- };- }-- // Success-like reasons ONLY — a `waiting_for_human` park must NOT- // register because it is not a completed deliverable boundary. The- // fresh approval continuation sees the complete authoritative- // history and performs the terminal scan after the decision runs;- // registering here would freeze pre-approval content too early.- if (isSuccessLikeCompletionReason(preSaveReason)) {- await this.completionLifecycle.registerFileWorks(operationId, stepResult.newState);- logToolCallPc(operationId, stepIndex, 'post.file_works_registered', () => ({}));- }- }-- // Protocol v2 native runs reconcile only what this step changed. The- // full before/after lists stay server-side; the wire sees a bounded- // patch. Publish before saveStepResult because a terminal save emits- // agent_runtime_end immediately, and the client must apply the patch- // before completing the run.- if (gatewayMessagePatchEnabled && stepStartUiMessages) {- const settledUiMessages = await this.queryUiMessages(stepResult.newState, {- skipWorks: shouldContinue,- });- if (settledUiMessages) {- // Projected: this branch runs only for a client that asked for- // protocol 2, which renders tool view models and can fetch a stored- // payload back. The model-facing lists are read elsewhere, straight- // off `MessageModel`, and stay whole.- await this.streamManager.publishStreamEvent(operationId, {- data: buildProjectedMessagePatch(- stepStartUiMessages,- settledUiMessages,- stepIndex + 1,- ),- stepIndex,- type: 'message_patch',- });- }- }-- // A credential the run just saved or connected changes the list the next- // step must show, so the snapshot frozen at creation no longer holds.- // Dropped before the save below — that write is what the next step- // reloads, and nothing else persists the state on a plain step.- if (- stepChangedCredentials(stepResult.nextContext) &&- stepResult.newState.operationCredentials- ) {- stepResult.newState.operationCredentials = undefined;- log('[%s][%d] Credentials changed in-run; dropped the snapshot', operationId, stepIndex);- }-- // Save state, coordinator will handle event sending automatically- await this.coordinator.saveStepResult(operationId, {- ...stepResult,- executionTime: Date.now() - startAt,- stepIndex, // placeholder- });- logToolCallPc(operationId, stepIndex, 'post.step_result_saved', () => ({- stateStatus: stepResult.newState.status,- stateStepCount: stepResult.newState.stepCount,- }));-- let nextStepScheduled = false;- let continuation: AgentStepContinuation | undefined;-- // Publish step complete event- await this.streamManager.publishStreamEvent(operationId, {- data: {- ...(stepResult.newState.host?.includeFinalState === true && {- finalState: stepResult.newState,- }),- nextStepScheduled,- stepIndex,- },- stepIndex,- type: 'step_complete',- });- logToolCallPc(operationId, stepIndex, 'post.step_complete_published', () => ({}));-- await this.publishSubAgentProgress(stepResult.newState, stepIndex);-- // Build enhanced step completion log & presentation data- const { presentation: stepPresentationData, summary: stepSummary } = buildStepPresentation(- stepResult,- Date.now() - startAt,- );-- const { usage } = stepResult.newState;- log(- '[%s][%d] completed %s | total: %s tokens / $%s | llm×%d | tools×%d',- operationId,- stepIndex,- stepSummary,- formatTokenCount(stepPresentationData.totalTokens),- stepPresentationData.totalCost.toFixed(4),- usage?.llm?.apiCalls ?? 0,- usage?.tools?.totalCalls ?? 0,- );-- const toolsCalling = stepPresentationData.toolsCalling;- const content = stepPresentationData.content;-- let afterStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];-- // 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()- : undefined;- const stepLabel = metadata?._stepLabel;-- // See the `runtime.before_step` guard above — same share-visitor- // suppression at the sibling per-step emission.- afterStepSignalEvents = toAgentSignalSnapshotEvents(- isAgentShareRun(stepResult.newState)- ? undefined- : await emitAgentSignalSourceEvent(- {- payload: {- agentId: origin.agentId,- operationId,- serializedContext: undefined,- stepIndex,- topicId: origin.topicId,- turnCount: stepResult.newState?.stepCount || 0,- },- sourceId: `${operationId}:after:${stepIndex}`,- sourceType: 'runtime.after_step',- },- {- agentId: origin.agentId,- db: this.serverDB,- userId: origin.userId || this.userId,- },- { ignoreError: true },- ),- );-- await hookDispatcher.dispatch(- operationId,- 'afterStep',- {- agentId: origin.agentId || '',- content,- elapsedMs,- executionTimeMs: stepPresentationData.executionTimeMs,- finalState: stepResult.newState,- ...(stepLabel && { stepLabel }),- lastLLMContent: tracking.lastLLMContent,- lastToolsCalling: tracking.lastToolsCalling,- operationId,- reasoning: stepPresentationData.reasoning,- shouldContinue,- status: stepResult.newState?.status,- stepCost: stepPresentationData.stepCost,- stepIndex,- stepType: stepPresentationData.stepType,- steps: stepResult.newState?.stepCount || 0,- thinking: stepPresentationData.thinking,- toolCalls: stepResult.newState?.usage?.tools?.totalCalls,- toolsCalling: stepPresentationData.toolsCalling,- toolsResult: stepPresentationData.toolsResult,- 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: origin.userId || this.userId,- },- stepResult.newState?.host?.hooks,- );- } catch (hookError) {- log('[%s] afterStep hook dispatch error: %O', operationId, hookError);- }-- await this.traceRecorder.appendStep(operationId, {- afterStepSignalEvents,- agentState,- beforeStepSignalEvents,- contextEngine: contextEnginePayload,- currentContext,- externalRetryCount,- presentation: stepPresentationData,- startedAt: startAt,- stepIndex,- stepResult,- });-- // Update step tracking in state metadata for afterStep hooks (cross-step accumulator)- const hasAfterStepHooks = stepResult.newState.host?.hooks?.some(- (h: { type: string }) => h.type === 'afterStep',- );- logToolCallPc(operationId, stepIndex, 'post.trace_appended', () => ({}));- logToolCallPc(operationId, stepIndex, 'post.route_selected', () => ({- hasAfterStepHooks,- nextContextPresent: stepResult.nextContext !== undefined,- queueAvailable: Boolean(this.queueService),- shouldContinue,- }));- if (hasAfterStepHooks && stepResult.newState.metadata) {- const prevTracking = stepResult.newState.metadata._stepTracking || {};- const newTotalToolCalls =- (prevTracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0);-- // Truncate content to 1800 chars to keep state small- const truncatedContent = content- ? content.length > 1800- ? content.slice(0, 1800) + '...'- : content- : prevTracking.lastLLMContent;-- const updatedTracking = {- lastLLMContent: truncatedContent,- lastToolsCalling: toolsCalling || prevTracking.lastToolsCalling,- totalToolCalls: newTotalToolCalls,- };-- // Persist tracking state for next step- stepResult.newState.metadata._stepTracking = updatedTracking;- await this.coordinator.saveAgentState(operationId, stepResult.newState);- logToolCallPc(operationId, stepIndex, 'post.step_tracking_saved', () => ({}));- }-- if (shouldContinue && stepResult.nextContext && this.queueService) {- const nextStepIndex = stepIndex + 1;- const next: AgentStepContinuation = {- context: stepResult.nextContext,- delay: this.calculateStepDelay(stepResult),- operationId,- priority: this.calculatePriority(stepResult),- retries:- typeof stepResult.newState.host?.queue?.retries === 'number'- ? stepResult.newState.host?.queue?.retries- : undefined,- retryDelay:- typeof stepResult.newState.host?.queue?.retryDelay === 'string'- ? stepResult.newState.host?.queue?.retryDelay- : undefined,- stepIndex: nextStepIndex,- };-- // Park the envelope before handing it over. The caller is about to run- // this step in-process with nothing queued behind it; if that- // invocation dies mid-step, the only way back is for a redelivery to- // find this envelope — the stale-delivery guard would otherwise ACK- // the (now older) delivered step and strand the operation.- //- // Inlining is therefore conditional on the park succeeding. When it- // doesn't, fall back to the ordinary queue round-trip: slower by a- // step boundary, but it keeps the recovery path the queue provides.- const parked = inlineContinuation- ? await this.coordinator.saveInlineResume(operationId, next)- : false;-- if (!parked && inlineContinuation) {- log(- '[%s][%d] Could not park the inline envelope; falling back to the queue',- operationId,- stepIndex,- );- }-- if (parked) {- handedOffInline = true;- // Hand the next step back to the caller instead of paying a full- // queue round-trip for it. The caller either runs it in this same- // invocation or publishes it via `scheduleContinuation` when its- // time budget runs out, so the step is never dropped.- continuation = next;- logToolCallPc(operationId, stepIndex, 'post.next_step_inlined', () => ({- nextStepIndex,- }));- log('[%s][%d] Next step %d deferred to caller', operationId, stepIndex, nextStepIndex);- } else {- // The next step runs in another invocation, which rebuilds the- // partial from the store — it has to see this step. The gateway- // pushes this invocation issued have to land for the same reason:- // nothing carries them once it stops running.- await this.traceRecorder.flushPartial();- await this.streamManager.drainPushes?.(operationId);- await this.queueService.scheduleMessage({ ...next, endpoint: `${this.baseURL}/run` });- nextStepScheduled = true;- logToolCallPc(operationId, stepIndex, 'post.next_step_scheduled', () => ({- nextStepIndex,- }));-- log('[%s][%d] Scheduled next step %d', operationId, stepIndex, nextStepIndex);- }- }-- // Record final agent-level usage on the invoke_agent span. Done on every- // step so partial trees (e.g. interrupted runs) still carry the- // last-known token counters.- invokeAgentSpan.setAttributes(- buildInvokeAgentResultAttributes({- inputTokens: stepResult.newState.usage?.llm?.tokens?.input,- outputTokens: stepResult.newState.usage?.llm?.tokens?.output,- stepCount: stepResult.newState.stepCount,- }),- );-- // Check if operation is complete- if (!shouldContinue) {- const reason = this.determineCompletionReason(stepResult.newState);- invokeAgentSpan.setAttributes(- buildInvokeAgentResultAttributes({ completionReason: reason }),- );-- // A client park is no completion: the run continues under this id.- const completionSignalEvents =- reason === 'waiting_for_client'- ? []- : await this.completionLifecycle.emitSignalEvents(- operationId,- stepResult.newState,- reason,- );- logToolCallPc(operationId, stepIndex, 'post.completion_signals', () => ({ reason }));-- // Dispatch completion hooks- await this.completionLifecycle.dispatchHooks(operationId, stepResult.newState, reason);- logToolCallPc(operationId, stepIndex, 'post.completion_hooks', () => ({ reason }));-- if (reason === 'waiting_for_human') {- await this.recordInterventionLifecycleCompletion(- operationId,- stepResult.newState,- stepIndex,- );- }-- // Park-time self-check: sub-agents are dispatched mid-step, so a- // fast child can complete BEFORE this op's parked state/row were- // persisted — its resume attempt then no-ops against the status- // guard and nothing retries. Now that both the Redis state and the- // `agent_operations` row (via dispatchHooks → persistCompletion)- // say `waiting_for_async_tool`, re-run the barrier once to recover- // any resume that raced the park.- if (stepResult.newState.status === 'waiting_for_async_tool') {- try {- await this.tryResumeParentFromAsyncTool({ parentOperationId: operationId });- } catch (selfCheckError) {- log(- '[%s][%d] Park-time async-tool self-check failed (non-fatal): %O',- operationId,- stepIndex,- selfCheckError,- );- }- }-- // Finalize tracing snapshot. The error catch below uses the same- // recorder so propagated failures still write the canonical S3- // snapshot instead of orphaning the partial ().- // A client park is no trace boundary: keep the partial so the resumed- // steps extend the same trajectory and the real end finalizes it whole.- const newStateError = stepResult.newState.error;- if (reason === 'waiting_for_client') {- await this.traceRecorder.flushPartial();- } else- await this.traceRecorder.finalize(operationId, {- appendEventsToLastStep: completionSignalEvents,- completionReason: reason,- error: newStateError- ? {- attribution: newStateError.attribution,- body: newStateError.body,- category: newStateError.category,- countAsFailure: newStateError.countAsFailure,- httpStatus: newStateError.httpStatus,- message:- this.completionLifecycle.extractErrorMessage(newStateError) ??- JSON.stringify(newStateError),- numericId: newStateError.numericId,- retryable: newStateError.retryable,- severity: newStateError.severity,- type: String(newStateError.type ?? newStateError.errorType ?? 'unknown'),- }- : undefined,- state: stepResult.newState,- });- logToolCallPc(operationId, stepIndex, 'post.trace_finalized', () => ({ reason }));- }-- return {- continuation,- nextStepScheduled,- state: stepResult.newState,- stepResult,- success: true,- };- });- } catch (error) {- const isInterventionPersistenceFailure =- error instanceof CriticalAgentInterventionPersistenceError;- invokeAgentSpan.recordException(error as Error);- invokeAgentSpan.setStatus({- code: SpanStatusCode.ERROR,- message: error instanceof Error ? error.message : String(error),- });- invokeAgentSpan.setAttributes(- buildInvokeAgentResultAttributes({- completionReason: isInterventionPersistenceFailure ? 'waiting_for_human' : 'error',- }),- );-- log('Step %d failed for operation %s: %O', stepIndex, operationId, error);-- // The runtime step and its waiting_for_human state are already durable;- // only the idempotent generic Review publication failed. Turning this- // infrastructure failure into an agent error would overwrite the parked- // state/operation row and make the QStash redelivery terminal-short-circuit.- // Preserve the parked state and propagate non-2xx so the completed-step- // lifecycle replay above can retry Review persistence without repeating- // any LLM or tool side effects.- if (isInterventionPersistenceFailure) {- log(- '[%s][%d] Intervention Review persistence failed; keeping operation parked for retry',- operationId,- stepIndex,- );- throw error;- }-- const formattedError = formatErrorForState(error);-- // Build error state — try loading current state from coordinator, but if that- // also fails (e.g. Redis ECONNRESET), fall back to a minimal error state so- // that completion callbacks and webhooks can still fire.- let finalStateWithError: any;- try {- await this.streamManager.publishStreamEvent(operationId, {- data: {- error: formattedError.message,- errorType: String(formattedError.type),- phase: 'step_execution',- stepIndex,- },- stepIndex,- type: 'error',- });- } catch (publishError) {- log(- '[%s] Failed to publish error event (infra may be down): %O',- operationId,- publishError,- );- }-- try {- const errorState = await this.coordinator.loadAgentState(operationId);- finalStateWithError = {- ...errorState!,- error: formattedError,- metadata: {- ...errorState?.metadata,- externalRetryCount,- },- status: 'error' as const,- stepCount: errorState?.stepCount ?? stepIndex,- };- } catch (loadError) {- log('[%s] Failed to load error state (infra may be down): %O', operationId, loadError);- // Fallback: construct a minimal error state so callbacks still receive useful info- finalStateWithError = {- error: formattedError,- metadata: { externalRetryCount },- status: 'error' as const,- stepCount: stepIndex,- };- }-- try {- await this.coordinator.saveAgentState(operationId, finalStateWithError);- } catch (saveError) {- log('[%s] Failed to save error state (infra may be down): %O', operationId, saveError);- }-- await this.completionLifecycle.emitSignalEvents(operationId, finalStateWithError, 'error');- logToolCallPc(operationId, stepIndex, 'post.completion_signals', () => ({ reason: 'error' }));-- // Dispatch onComplete + onError hooks- await this.completionLifecycle.dispatchHooks(operationId, finalStateWithError, 'error');- logToolCallPc(operationId, stepIndex, 'post.completion_hooks', () => ({ reason: 'error' }));-- // Finalize the partial snapshot into the canonical S3 path so the- // failed op is observable in the same place as a successful run.- // Without this, propagated errors (e.g. markPersistFatal from- // RuntimeExecutors) leave the partial as an orphan at- // `_partial/<op>.json.zst` and the canonical- // `agent-traces/<agentId>/<topicId>/<op>.json.zst` returns 404 — see- // .- //- // `failedStep` synthesizes a step record for the failure because the- // real step never reached `appendStepToPartial` — it threw before the- // success path could push it. Without this synthetic step, the- // snapshot's step count would lag the assistant message that- // triggered the failing call.- await this.traceRecorder.finalize(operationId, {- completionReason: 'error',- error: {- attribution: formattedError.attribution,- body: formattedError.body,- category: formattedError.category,- countAsFailure: formattedError.countAsFailure,- httpStatus: formattedError.httpStatus,- message: formattedError.message ?? String(formattedError.type),- numericId: formattedError.numericId,- retryable: formattedError.retryable,- severity: formattedError.severity,- type: String(formattedError.type),- },- failedStep: {- startedAt: stepStartAt,- stepIndex,- stepType: formattedError.category === 'provider' ? 'call_llm' : 'call_tool',- },- state: finalStateWithError,- });- logToolCallPc(operationId, stepIndex, 'post.trace_finalized', () => ({ reason: 'error' }));-- throw error;- } finally {- invokeAgentSpan.end();- stepAbortPollStopped = true;- if (stepAbortPoll) clearTimeout(stepAbortPoll);- stopStepLockHeartbeat();- // Parked runs (human input, async tools) and finished ones are read back- // by a different invocation, so the partial cannot stay in memory only.- // An inline hand-off keeps it: the next step runs on this recorder.- if (!handedOffInline) {- await this.traceRecorder.flushPartial();- // Same boundary for the stream: an issued push is only guaranteed to- // reach the gateway while this invocation is still running.- await this.streamManager.drainPushes?.(operationId);- }- // The inline step loop keeps the lock across step boundaries — releasing- // here would open a window for a stale redelivery to claim it mid-run.- // Its caller releases once, in a `finally`, for the whole invocation.- if (!retainStepLock) {- await this.coordinator.releaseStepLock(operationId, stepIndex, stepLockOwner);- }- }- }-- /**- * Publish a continuation that `executeStep` handed back instead of queueing.- * The inline step loop calls this when it runs out of invocation budget, so- * the remaining steps resume in a fresh invocation.- */- async scheduleContinuation(continuation: AgentStepContinuation): Promise<void> {- if (!this.queueService) {- throw new Error(- `Cannot schedule continuation for ${continuation.operationId}: no queue service`,- );- }-- // The steps this invocation inlined are still only in memory — the- // invocation that picks the run up reads the partial from the store, and- // the gateway pushes it issued have nothing else to carry them.- await this.traceRecorder.flushPartial();- await this.streamManager.drainPushes?.(continuation.operationId);-- await this.queueService.scheduleMessage({- ...continuation,- endpoint: `${this.baseURL}/run`,- });-- log('[%s] Handed step %d back to the queue', continuation.operationId, continuation.stepIndex);- }-- /**- * Release a lock that was retained across an inline step loop. Owner-scoped,- * so it is a no-op when this invocation never held the lock.- */- async releaseOperationLock(operationId: string, stepLockOwner: string): Promise<void> {- await this.coordinator.releaseStepLock(operationId, 0, stepLockOwner);- }-- /**- * Mint a lock owner for an inline step loop. Unique per invocation, which is- * what makes re-entering the same lock on the next step safe.- */- createOperationLockOwner(operationId: string): string {- return createStepLockOwner(operationId, 0);- }-- /**- * Get operation status- */- async getOperationStatus(params: {- historyLimit?: number;- includeHistory?: boolean;- operationId: string;- }): Promise<OperationStatusResult | null> {- const { operationId, includeHistory = false, historyLimit = 10 } = params;-- try {- log('Getting operation status for %s', operationId);-- // Get current state and metadata- const [currentState, operationMetadata] = await Promise.all([- this.coordinator.loadAgentState(operationId),- this.coordinator.getOperationMetadata(operationId),- ]);-- // Operation may have expired or does not exist, return null- if (!currentState || !operationMetadata) {- log('Operation %s not found (may have expired)', operationId);- return null;- }-- // Get execution history (if needed)- let executionHistory;- if (includeHistory) {- try {- executionHistory = await this.coordinator.getExecutionHistory(operationId, historyLimit);- } catch (error) {- log('Failed to load execution history: %O', error);- executionHistory = [];- }- }-- // Get recent stream events (for debugging)- let recentEvents;- if (includeHistory) {- try {- recentEvents = await this.streamManager.getStreamHistory(operationId, 20);- } catch (error) {- log('Failed to load recent events: %O', error);- recentEvents = [];- }- }-- // Calculate operation statistics- const stats = {- lastActiveTime: operationMetadata.lastActiveAt- ? Date.now() - new Date(operationMetadata.lastActiveAt).getTime()- : 0,- totalCost: currentState.cost?.total || 0,- totalMessages: currentState.messages?.length || 0,- totalSteps: currentState.stepCount || 0,- uptime: operationMetadata.createdAt- ? Date.now() - new Date(operationMetadata.createdAt).getTime()- : 0,- };-- return {- currentState: {- cost: currentState.cost,- costLimit: currentState.costLimit,- error: currentState.error,- interruption: currentState.interruption,- lastModified: currentState.lastModified,- maxSteps: currentState.maxSteps,- pendingHumanPrompt: currentState.pendingHumanPrompt,- pendingHumanSelect: currentState.pendingHumanSelect,- pendingToolsCalling: currentState.pendingToolsCalling,- status: currentState.status,- stepCount: currentState.stepCount,- usage: currentState.usage,- },- executionHistory: executionHistory?.slice(0, historyLimit),- hasError: currentState.status === 'error',- isActive: currentState.status === 'running' || isParkedStatus(currentState.status),- isCompleted: currentState.status === 'done',- metadata: operationMetadata,- needsHumanInput: currentState.status === 'waiting_for_human',- operationId,- recentEvents: recentEvents?.slice(0, 10),- stats,- };- } catch (error) {- log('Failed to get operation status for %s: %O', operationId, error);- throw error;- }- }-- /**- * Get list of pending human interventions- */- async getPendingInterventions(params: {- operationId?: string;- userId?: string;- }): Promise<PendingInterventionsResult> {- const { operationId, userId } = params;-- try {- log('Getting pending interventions for operationId: %s, userId: %s', operationId, userId);-- let operations: string[] = [];-- if (operationId) {- operations = [operationId];- } else if (userId) {- // Get all active operations for the user- try {- const activeOperations = await this.coordinator.getActiveOperations();-- // Filter operations belonging to this user- const userOperations = [];- for (const operation of activeOperations) {- try {- const metadata = await this.coordinator.getOperationMetadata(operation);- if (metadata?.userId === userId) {- userOperations.push(operation);- }- } catch (error) {- log('Failed to get metadata for operation %s: %O', operation, error);- }- }- operations = userOperations;- } catch (error) {- log('Failed to get active operations: %O', error);- operations = [];- }- }-- // Check status of each operation- const pendingInterventions = [];-- for (const operation of operations) {- try {- const [state, metadata] = await Promise.all([- this.coordinator.loadAgentState(operation),- this.coordinator.getOperationMetadata(operation),- ]);-- if (state?.status === 'waiting_for_human') {- const intervention: any = {- lastModified: state.lastModified,- modelRuntimeConfig: metadata?.modelRuntimeConfig,- operationId: operation,- status: state.status,- stepCount: state.stepCount,- userId: metadata?.userId,- };-- // Add specific pending content- if (state.pendingToolsCalling) {- intervention.type = 'tool_approval';- intervention.pendingToolsCalling = state.pendingToolsCalling;- } else if (state.pendingHumanPrompt) {- intervention.type = 'human_prompt';- intervention.pendingHumanPrompt = state.pendingHumanPrompt;- } else if (state.pendingHumanSelect) {- intervention.type = 'human_select';- intervention.pendingHumanSelect = state.pendingHumanSelect;- }-- pendingInterventions.push(intervention);- }- } catch (error) {- log('Failed to get state for operation %s: %O', operation, error);- }- }-- return {- pendingInterventions,- timestamp: new Date().toISOString(),- totalCount: pendingInterventions.length,- };- } catch (error) {- log('Failed to get pending interventions: %O', error);- throw error;- }- }-- /**- * Explicitly start operation execution- */- async startExecution(params: StartExecutionParams): Promise<StartExecutionResult> {- const { operationId, context, priority = 'normal', delay = 50 } = params;-- try {- log('Starting execution for operation %s', operationId);-- // Check if operation exists- const operationMetadata = await this.coordinator.getOperationMetadata(operationId);- if (!operationMetadata) {- throw new Error(`Operation ${operationId} not found`);- }-- // Get current state- const currentState = await this.coordinator.loadAgentState(operationId);- if (!currentState) {- throw new Error(`Agent state not found for operation ${operationId}`);- }-- // Check operation status- if (currentState.status === 'running') {- throw new Error(`Operation ${operationId} is already running`);- }-- if (currentState.status === 'done') {- throw new Error(`Operation ${operationId} is already completed`);- }-- if (currentState.status === 'error') {- throw new Error(`Operation ${operationId} is in error state`);- }-- if (currentState.status === 'interrupted') {- throw new Error(`Operation ${operationId} is interrupted`);- }-- // Build execution context- let executionContext = context;- if (!executionContext) {- // If no context provided, build default context from metadata- // Note: AgentRuntimeContext requires sessionId for compatibility with @lobechat/agent-runtime- executionContext = {- payload: {- isFirstMessage: true,- message: [{ content: '' }],- },- phase: 'user_input' as const,- session: {- messageCount: currentState.messages?.length || 0,- sessionId: operationId,- status: 'idle' as const,- stepCount: currentState.stepCount || 0,- },- };- }-- // Update operation status to running- await this.coordinator.saveAgentState(operationId, {- ...currentState,- lastModified: new Date().toISOString(),- status: 'running',- });-- // Schedule execution (if queue service is available)- let messageId: string | undefined;- if (this.queueService) {- messageId = await this.queueService.scheduleMessage({- context: executionContext,- delay,- endpoint: `${this.baseURL}/run`,- operationId,- priority,- stepIndex: currentState.stepCount || 0,- });- log('Scheduled execution for operation %s (messageId: %s)', operationId, messageId);- } else {- log('Queue service disabled, skipping schedule for operation %s', operationId);- }-- return {- messageId,- operationId,- scheduled: !!messageId,- success: true,- };- } catch (error) {- log('Failed to start execution for operation %s: %O', operationId, error);- throw error;- }- }-- /**- * Process human intervention- */- async processHumanIntervention(params: {- action: 'approve' | 'reject' | 'reject_continue' | 'input' | 'select';- approvedToolCall?: any;- humanInput?: any;- operationId: string;- rejectAndContinue?: boolean;- rejectionReason?: string;- stepIndex: number;- toolMessageId?: string;- }): Promise<{ messageId?: string }> {- const {- operationId,- stepIndex,- action,- approvedToolCall,- humanInput,- rejectAndContinue,- rejectionReason,- toolMessageId,- } = params;-- try {- log(- 'Processing human intervention for operation %s:%d (action: %s)',- operationId,- stepIndex,- action,- );-- // Schedule execution with high priority (if queue service is available)- let messageId: string | undefined;- if (this.queueService) {- messageId = await this.queueService.scheduleMessage({- context: undefined, // Will be retrieved from state manager- delay: 100,- endpoint: `${this.baseURL}/run`,- operationId,- payload: {- approvedToolCall,- humanInput,- rejectAndContinue,- rejectionReason,- toolMessageId,- },- priority: 'high',- stepIndex,- });- log(- 'Scheduled immediate execution for operation %s (messageId: %s)',- operationId,- messageId,- );- } else {- log('Queue service disabled, skipping schedule for operation %s', operationId);- }-- return { messageId };- } catch (error) {- log('Failed to process human intervention for operation %s: %O', operationId, error);- throw error;- }- }-- /**- * Completion-bridge entry point for async sub-agent tools.- *- * Called once per sub-op completion (the bridge already backfilled that- * sub-op's tool message). Implements the K=N barrier + single-fire resume:- *- * 1. The parent must still be parked (`waiting_for_async_tool`).- * 2. Every tool in this turn's `pendingToolsCalling` must be fulfilled —- * the true gate, since the LLM can only continue once every tool_result- * message row is present (covers mixed sub-agent + client-tool batches).- * 3. Atomically claim the resume via a status CAS; only the winner proceeds.- * 4. Schedule the parent's next step (`resumeAsyncTool`), which re-enters- * the LLM with the refreshed tool results.- *- * Returns true only for the CAS winner that scheduled the resume.- *- * `options.scheduleVerifyOnHold` arms a one-shot delayed re-check- * (`verifyAsyncToolBarrier`) when the parent is found not yet resumable.- * Sub-agent completions set it to cover the child finishing before the- * parent's parked state is persisted, and transient failures around the- * last completion (a sibling dying between backfill and resume, a DB- * hiccup during the barrier read). Pure concurrency needs no cover: each- * completion checks the barrier only after committing its own backfill, so- * the last committer always sees every earlier one. The re-check itself- * never re-arms, so retries stay bounded.- */- async tryResumeParentFromAsyncTool(- params: { parentOperationId: string },- options?: {- /**- * Message id of a tool placeholder the caller just backfilled to a- * terminal state. Trusted by the barrier as fulfilled without re-reading- * `message_plugins` — closes the read-your-writes gap where the barrier- * query hits a read replica that hasn't seen the just-committed write.- */- knownFulfilledMessageId?: string;- /**- * Group orchestration disposition (skipCallSupervisor / delegate → finish).- * When omitted, resolved from the parked tool message's pluginState.- */- onComplete?: GroupActionOnComplete;- scheduleVerifyOnHold?: boolean;- /** 1-based watchdog attempt to arm when the parent isn't resumable yet. */- verifyAttempt?: number;- },- ): Promise<boolean> {- const { parentOperationId } = params;-- const state = await this.coordinator.loadAgentState(parentOperationId);- if (!state) {- // State expired (Redis TTL) or never persisted. A missing state at- // completion time is a classic way a parent silently strands — but it is- // often transient: a read replica that hasn't seen the park yet, or the- // child outrunning the parent's park before its snapshot lands. Arm the- // bounded verify so a later re-check can resume once the state is visible,- // instead of giving up on the first miss. A genuinely-gone parent just- // exhausts the attempt cap (verify_exhausted) rather than stranding here.- log('[%s] async-tool resume: parent state missing/expired, arming verify', parentOperationId);- asyncToolResumeCounter.add(1, { outcome: 'no_state' });- await this.maybeScheduleAsyncToolVerify(parentOperationId, null, options);- return false;- }-- if (state.status !== 'waiting_for_async_tool') {- // Not parked (yet). Either the op already resumed/finished — nothing to- // do — or the child outran the parent's parking step; the delayed verify- // re-checks once the park has had time to land.- await this.maybeScheduleAsyncToolVerify(parentOperationId, state, options);- return false;- }-- const pending = (state.pendingToolsCalling ?? []) as ChatToolPayload[];- if (pending.length === 0) {- // Parked but no pending tools recorded — usually the parked snapshot's- // `pendingToolsCalling` hasn't finished persisting yet. Warn, report, and- // arm a fallback re-check rather than returning silently (the old bug).- log(- '[%s] async-tool resume: parked op has no pending tools, arming fallback',- parentOperationId,- );- asyncToolResumeCounter.add(1, { outcome: 'no_pending' });- await this.maybeScheduleAsyncToolVerify(parentOperationId, state, options);- return false;- }-- // Barrier: every pending tool must have a fulfilled tool_result message.- const allFulfilled = await this.allPendingToolsFulfilled(- pending,- options?.knownFulfilledMessageId,- );- if (!allFulfilled) {- log('[%s] async-tool barrier not yet satisfied, holding', parentOperationId);- asyncToolResumeCounter.add(1, { outcome: 'barrier_held' });- await this.maybeScheduleAsyncToolVerify(parentOperationId, state, options);- return false;- }-- // Group orchestration's skipCallSupervisor / delegate ends the supervisor- // op without another LLM turn: the same CAS gate flips the parked op, but- // the scheduled step finishes it (`finishAfterAsyncTool`) instead of- // re-entering the LLM (`resumeAsyncTool`). Self-describing so the generic- // verify watchdog resolves it correctly: the option (if any) wins, else the- // hint persisted on the parked tool message's pluginState, else resume.- const onComplete: GroupActionOnComplete =- options?.onComplete ?? (await this.resolveAsyncToolOnComplete(pending));-- // Single-fire guard: only one concurrent completion flips the op.- const won = await new AgentOperationModel(this.serverDB, this.userId).tryResumeFromAsyncTool(- parentOperationId,- );- if (!won) {- log('[%s] lost async-tool resume CAS, no-op', parentOperationId);- asyncToolResumeCounter.add(1, { outcome: 'lost_cas' });- return false;- }-- asyncToolResumeCounter.add(1, { outcome: 'resumed' });-- log(- '[%s] won async-tool resume CAS, scheduling step %d (onComplete: %s)',- parentOperationId,- state.stepCount,- onComplete,- );-- if (this.queueService) {- await this.queueService.scheduleMessage({- context: undefined,- delay: 100,- endpoint: `${this.baseURL}/run`,- operationId: parentOperationId,- payload:- onComplete === 'finish' ? { finishAfterAsyncTool: true } : { resumeAsyncTool: true },- priority: 'high',- stepIndex: state.stepCount,- });- } else {- log('[%s] queue service disabled, skipping async-tool resume schedule', parentOperationId);- }-- return true;- }-- // ==================== Waiting for a client (U4c) ====================-- /**- * Park a step that failed because no client could run its LLM call — the- * provider is reachable only from the user's device and no LobeHub client- * took the call (a schedule, a bot, a CLI run, every tab closed). The run- * waits in `waiting_for_client` on the state the step started from, its- * assistant row says why, and an expiry check is armed. `undefined` when the- * error is not one a client can fix, or nothing could resume or expire the- * park (no queue) — the step then fails as before.- */- private async parkForClientLlm(- operationId: string,- errorState: AgentState,- context: AgentRuntimeContext | undefined,- notAfter?: string,- stepStartState?: AgentState,- ): Promise<AgentState | undefined> {- const reason = getClientLlmWaitableReason(errorState.error);- if (!reason || !this.queueService) return;-- // A client that started the run but predates the wait takes the parked- // call's error as the run's end and settles it locally, while the row- // stays parked under its topic. Fail the step for it as before.- const declaredExecutor = errorState.host?.llmExecutor;- if (declaredExecutor && !declaredExecutor.capabilities?.includes(CLIENT_LLM_WAIT_CAPABILITY)) {- log("[%s] The run's client cannot wait for a client, failing instead", operationId);- return;- }-- const errorBody = (errorState.error as { body?: { provider?: unknown } } | undefined)?.body;- const provider =- (typeof errorBody?.provider === 'string' && errorBody.provider) ||- errorState.modelRuntimeConfig?.provider ||- 'unknown';-- const topicId = errorState.origin?.topicId;- let assistantMessage: { id: string; parentId?: string | null } | undefined;- if (topicId) {- try {- const row = await this.messageModel.findLatestAssistantByOperationId({- operationId,- topicId,- });- if (row?.id) assistantMessage = { id: row.id, parentId: row.parentId };- } catch (error) {- log('[%s] Failed to find the parked call assistant row: %O', operationId, error);- }- }-- // A client picks a wait up by subscribing to the run's stream, which needs- // the run's topic and assistant row. Without them nothing could claim the- // wait, so fail the step as before instead of parking it.- if (!topicId || !assistantMessage) {- log('[%s] No stream anchor to park on, failing instead', operationId);- return;- }-- const wait = buildClientLlmWait({ assistantMessage, context, notAfter, provider, reason });- // A re-park with (almost) nothing left of its wait would arm an expiry that- // can land before this step commits and be overwritten by it. The wait is- // over anyway: fail the step with its actionable error instead.- if (Date.parse(wait.expiresAt) - Date.now() < MIN_CLIENT_LLM_WAIT_REMAINING_MS) {- log('[%s] Client wait already used up, failing instead', operationId);- return;- }- const parkedState: AgentState = {- ...errorState,- // The call never ran, so it does not spend a step: the resume replays it- // through `runtime.step`, which counts it (and applies the step limit)- // then. Keeping the incremented count would count it twice and, at the- // limit, replay it as a forced final answer.- ...(stepStartState && {- forceFinish: stepStartState.forceFinish,- stepCount: stepStartState.stepCount,- }),- clientLlmWait: wait,- error: undefined,- lastModified: wait.parkedAt,- status: 'waiting_for_client',- };-- // Resume, expiry and Stop all key off the durable row, so it must say- // `waiting_for_client` before anything advertises the wait. If it cannot,- // fail the step as before rather than park a run nothing could settle.- try {- const recorded = await this.agentOperationModel.recordCompletion(operationId, {- completionReason: 'waiting_for_client',- status: 'waiting_for_client',- });- if (!recorded) {- log('[%s] No durable row to park on, failing instead', operationId);- return;- }- } catch (error) {- log('[%s] Could not record the client wait, failing instead: %O', operationId, error);- return;- }-- // The expiry can fire at once (a re-park past its deadline), and it acts- // only on the park it names: the parked state and the waiting notice must- // already be in place, or it no-ops — or its terminal error is overwritten- // by the notice — and the run waits with nothing left to end it.- try {- await this.coordinator.saveAgentState(operationId, parkedState);- } catch (error) {- log('[%s] Could not save the parked state, failing instead: %O', operationId, error);- return;- }-- // The notice is the only thing a client that cannot run the provider sees- // (its relay error handler re-reads the server-owned row), so a transient- // failure is retried rather than left as a silent park.- await this.updateAssistantRowWithRetry(operationId, assistantMessage.id, {- error: buildClientLlmWaitMessageError(wait),- });-- try {- await this.queueService.scheduleMessage({- context: undefined,- delay: Math.max(Date.parse(wait.expiresAt) - Date.now(), 0),- endpoint: `${this.baseURL}/run`,- operationId,- payload: { clientLlmWaitExpired: wait.parkedAt },- priority: 'normal',- stepIndex: parkedState.stepCount,- });- } catch (error) {- // Without the expiry the run could wait forever: fail it now instead- // (the run's error then replaces the waiting notice on its row).- log('[%s] Could not arm the client wait expiry, failing instead: %O', operationId, error);- return;- }-- log(- '[%s] Parked in waiting_for_client (provider=%s, reason=%s, until %s)',- operationId,- provider,- reason,- wait.expiresAt,- );- return parkedState;- }-- /**- * Continue a run parked in `waiting_for_client` from the step it parked on.- * The asking client becomes the run's relay executor, so the replayed call- * is delivered to it. Single-fire: concurrent resumes (an automatic one and- * a click) race on the durable row and one wins.- */- async resumeFromClientLlmWait(params: {- llmExecutor?: AgentRunLlmExecutor;- operationId: string;- }): Promise<ResumeClientLlmWaitResult> {- const { llmExecutor, operationId } = params;- const state = await this.coordinator.loadAgentState(operationId);- if (!state || state.status !== 'waiting_for_client') return { resumed: false };- if (state.origin?.userId && state.origin.userId !== this.userId) return { resumed: false };-- // Past its deadline the wait is over even if the expiry is still in flight- // (QStash can deliver late): leave the run to it rather than run the call- // after the advertised time.- const expiresAt = Date.parse(state.clientLlmWait?.expiresAt ?? '');- if (Number.isFinite(expiresAt) && Date.now() >= expiresAt) return { resumed: false };-- const won = await this.agentOperationModel.tryResumeFromClientWait(operationId);- if (!won) return { resumed: false };-- const wait = state.clientLlmWait;- // Past the claim, everything up to the queued step must land, or the run- // goes back to its wait: a `running` row with nothing queued is one that no- // resume, expiry or Stop can reach.- try {- await this.coordinator.saveAgentState(operationId, {- ...state,- host: { ...state.host, ...(llmExecutor && { llmExecutor }) },- lastModified: new Date().toISOString(),- });-- // A Stop that landed after the claim could not settle the `running` row,- // and the save above may have overwritten its `interrupted` state. It- // marks the interrupt before saving, so any such Stop shows here; a later- // one saves after this and the queued step stops on it.- if (await this.coordinator.isInterrupted(operationId)) {- log('[%s] Stopped while being resumed; settling as interrupted', operationId);- const interruptedState: AgentState = {- ...state,- clientLlmWait: undefined,- lastModified: new Date().toISOString(),- status: 'interrupted',- };- await this.coordinator.saveAgentState(operationId, interruptedState);- if (await this.agentOperationModel.settleRunning(operationId, 'interrupted')) {- await this.completionLifecycle.dispatchHooks(- operationId,- interruptedState,- 'interrupted',- );- }- return { resumed: false };- }-- if (wait?.assistantMessageId) {- try {- await this.messageModel.update(wait.assistantMessageId, { error: null });- } catch (error) {- log('[%s] Failed to clear the waiting notice: %O', operationId, error);- }- }-- await this.queueService?.scheduleMessage({- context: undefined,- delay: 100,- endpoint: `${this.baseURL}/run`,- operationId,- payload: { resumeClientLlm: true },- priority: 'high',- stepIndex: state.stepCount,- });- } catch (error) {- log('[%s] Could not hand the run to a client, staying parked: %O', operationId, error);- await this.restoreClientLlmWait(operationId, state);- throw error;- }-- log('[%s] Resumed from waiting_for_client at step %d', operationId, state.stepCount);- return {- assistantMessageId: wait?.assistantMessageId,- resumed: true,- topicId: state.origin?.topicId ?? undefined,- };- }-- /**- * Put a run whose resume claim could not be completed back into its wait.- * Other transitions may have raced the claim, so this re-reads the run- * first. If a Stop moved it on (its settle could not match the claimed- * `running` row), the row is settled to match instead of re-parked. If it is- * still this park, the durable row goes back first — it is what resume,- * expiry and Stop key off — and the expiry is re-armed, because one that- * fired while the row read `running` gave up. Each step is best-effort so- * one failure does not skip the rest.- */- private async restoreClientLlmWait(operationId: string, parkedState: AgentState) {- const wait = parkedState.clientLlmWait;- const current = await this.coordinator.loadAgentState(operationId).catch(() => null);- const stillParked =- current?.status === 'waiting_for_client' &&- current.clientLlmWait?.parkedAt === wait?.parkedAt;-- if (!stillParked) {- if (current?.status === 'interrupted') {- const settled = await this.agentOperationModel- .settleRunning(operationId, 'interrupted')- .catch(() => false);- if (settled) {- await this.completionLifecycle- .dispatchHooks(operationId, current, 'interrupted')- .catch((error) => log('[%s] Failed to finish the stop: %O', operationId, error));- }- }- return;- }-- // The visible wait is only worth restoring once the row is parked again:- // with the row stuck `running`, no resume, expiry or Stop can reach it, and- // the abandoned-run watchdog is what settles it.- if (!(await this.revertClientWaitResumeWithRetry(operationId))) {- log('[%s] Could not re-park the durable row; leaving it to the watchdog', operationId);- return;- }- await this.coordinator- .saveAgentState(operationId, parkedState)- .catch((error) => log('[%s] Failed to restore the parked state: %O', operationId, error));- if (wait?.assistantMessageId) {- await this.messageModel- .update(wait.assistantMessageId, { error: buildClientLlmWaitMessageError(wait) })- .catch((error) => log('[%s] Failed to restore the waiting notice: %O', operationId, error));- }- if (!wait) return;-- // Duplicate expiries are no-ops (they match on `parkedAt` and the row CAS).- if (Date.now() >= Date.parse(wait.expiresAt)) {- await this.expireClientLlmWait(operationId, wait.parkedAt).catch((error) =>- log('[%s] Failed to expire the overdue wait: %O', operationId, error),- );- return;- }- await this.queueService- ?.scheduleMessage({- context: undefined,- delay: Math.max(Date.parse(wait.expiresAt) - Date.now(), 0),- endpoint: `${this.baseURL}/run`,- operationId,- payload: { clientLlmWaitExpired: wait.parkedAt },- priority: 'normal',- stepIndex: parkedState.stepCount,- })- .catch((error) => log('[%s] Failed to re-arm the wait expiry: %O', operationId, error));- }-- /** Put the claimed row back to `waiting_for_client`, riding out a transient DB error. */- private async revertClientWaitResumeWithRetry(operationId: string): Promise<boolean> {- for (const delayMs of CLIENT_WAIT_REVERT_RETRY_DELAYS_MS) {- if (delayMs) await new Promise((resolve) => setTimeout(resolve, delayMs));- try {- // `false` means the row is no longer the claimed `running` one, so it- // is not ours to put back.- return await this.agentOperationModel.revertClientWaitResume(operationId);- } catch (error) {- log('[%s] Failed to re-park the durable row: %O', operationId, error);- }- }- return false;- }-- /**- * Runs of this user parked in `waiting_for_client`, with what a client needs- * to pick one up: the provider it must be able to run, and where the run's- * conversation lives so it can subscribe to the stream before resuming.- */- async listClientLlmWaits(providers?: string[]): Promise<ClientLlmWaitItem[]> {- const rows = await this.agentOperationModel.listWaitingForClient({ providers });- const items = await pMap(- rows,- async (row): Promise<ClientLlmWaitItem | undefined> => {- const state = await this.coordinator.loadAgentState(row.id).catch(() => null);- const wait = state?.clientLlmWait;- if (state?.status !== 'waiting_for_client' || !wait) return;- return {- agentId: state.origin?.agentId ?? undefined,- assistantMessageId: wait.assistantMessageId,- expiresAt: wait.expiresAt,- operationId: row.id,- provider: wait.provider,- threadId: state.origin?.threadId ?? undefined,- topicId: state.origin?.topicId ?? row.topicId ?? undefined,- };- },- { concurrency: 4 },- );- return items.filter((item): item is ClientLlmWaitItem => !!item);- }-- /**- * End a `waiting_for_client` park nobody resumed in time. A no-op unless the- * run is still parked on the very wait that armed this check; the durable- * row CAS keeps a racing resume from being killed.- */- private async expireClientLlmWait(operationId: string, parkedAt: string): Promise<boolean> {- const state = await this.coordinator.loadAgentState(operationId);-- // A redelivery after this expiry already ended the run but its lifecycle- // delivery threw (a critical hook asks QStash to retry): deliver it again,- // like a retried terminal step does.- if (state?.status === 'error' && isClientLlmWaitExpiryOf(state, parkedAt)) {- log('[%s] Redelivering the lifecycle of an expired client wait', operationId);- await this.finishClientLlmWaitExpiry(operationId, state);- return true;- }-- if (state?.status !== 'waiting_for_client' || state.clientLlmWait?.parkedAt !== parkedAt) {- return false;- }-- // Redis still holds this exact park. A row this CAS cannot claim is one a- // resume took (`running`), unless it is already `error`: then an earlier- // delivery of this expiry settled it and failed before finishing (resumes,- // Stop and failing steps all move the Redis state off this park first), so- // finish it now — QStash retries the delivery that threw.- const settled = await this.agentOperationModel.settleClientWait(operationId);- if (!settled) {- const row = await this.agentOperationModel.findById(operationId);- if (row?.status !== 'error') return false;- log('[%s] Finishing a client wait expiry that settled but did not finish', operationId);- }-- await this.endExpiredClientLlmWait(operationId, state, state.clientLlmWait);-- log('[%s] waiting_for_client expired (parked at %s)', operationId, parkedAt);- return true;- }-- /**- * The terminal half of an expiry, once the durable row reads `error`: the- * parked call's row, the Redis state (which ends the stream) and the- * lifecycle. `state` is the run as it was parked on `wait`.- */- private async endExpiredClientLlmWait(- operationId: string,- state: AgentState,- wait: AgentRunClientLlmWait,- ) {- const provider = wait.provider;- const finalState: AgentState = {- ...state,- clientLlmWait: undefined,- error: formatErrorForState(- createClientLlmExecutorUnavailableError(provider, 'wait_timeout', {- waitedSince: wait.parkedAt,- }),- ),- lastModified: new Date().toISOString(),- status: 'error',- };-- // The row gets the terminal error first: the save below ends the stream- // with a `uiMessages` snapshot read from the DB, and an open tab adopts it,- // so writing it later would leave that tab on the waiting notice. The- // lifecycle writes the same error again when it finalizes the run.- // A transient failure is retried here: the lifecycle's later write emits- // no message patch, so a tab that took the stale snapshot would keep the- // dead waiting notice until reload.- const assistantMessageId = wait.assistantMessageId;- if (assistantMessageId && finalState.error) {- const message = this.completionLifecycle.extractErrorMessage(finalState.error);- const error = { ...finalState.error, body: finalState.error.body ?? { message }, message };- await this.updateAssistantRowWithRetry(operationId, assistantMessageId, { error });- }-- // Ends the stream (`agent_runtime_end`) and finalizes the run like any failure.- await this.coordinator.saveAgentState(operationId, finalState);- await this.completionLifecycle.emitSignalEvents(operationId, finalState, 'error');- await this.finishClientLlmWaitExpiry(operationId, finalState);- }-- /**- * Write a client-wait notice or error onto the assistant row, retrying a- * transient failure: what a connected tab shows next is read from this row.- */- private async updateAssistantRowWithRetry(- operationId: string,- messageId: string,- value: Parameters<MessageModel['update']>[1],- ) {- for (let attempt = 1; attempt <= CLIENT_WAIT_ROW_WRITE_ATTEMPTS; attempt += 1) {- try {- await this.messageModel.update(messageId, value);- return;- } catch (error) {- log('[%s] Failed to write the assistant row (%d): %O', operationId, attempt, error);- if (attempt < CLIENT_WAIT_ROW_WRITE_ATTEMPTS) {- await new Promise((resolve) => setTimeout(resolve, 100 * attempt));- }- }- }- }-- /** Lifecycle delivery of an expired client wait; safe to repeat on redelivery. */- private async finishClientLlmWaitExpiry(operationId: string, finalState: AgentState) {- const provider = (finalState.error as { body?: { provider?: string } } | undefined)?.body- ?.provider;- await this.completionLifecycle.dispatchHooks(operationId, finalState, 'error');- await this.traceRecorder.finalize(operationId, {- completionReason: 'error',- error: {- message: `No LobeHub client picked up the ${provider ?? 'local model'} call in time`,- type: String(finalState.error?.type ?? 'ClientLlmExecutorUnavailable'),- },- state: finalState,- });- }-- /**- * Arm the next bounded `verifyAsyncToolBarrier` re-check for a parent op whose- * resume attempt found it not yet resumable. Skipped for terminal states- * (nothing left to resume) and when the caller didn't opt in.- *- * Unlike the original single shot, the watchdog re-arms after each unsatisfied- * check: the verify handler re-enters here with `verifyAttempt + 1`, backing- * off exponentially up to {@link ASYNC_TOOL_VERIFY_MAX_ATTEMPTS}. A transient- * miss (read-replica lag, a sibling dying between backfill and resume) is thus- * retried instead of permanently stranding the parent. Once attempts are- * exhausted the chain stops and the `verify_exhausted` metric fires so the- * orphan is observable. For details see: async sub-agent suspend/resume stability hardening — bounded watchdog retry with exponential backoff.- */- private async maybeScheduleAsyncToolVerify(- parentOperationId: string,- state: AgentState | null,- options?: { scheduleVerifyOnHold?: boolean; verifyAttempt?: number },- ): Promise<void> {- if (!options?.scheduleVerifyOnHold || !this.queueService) return;-- // `state` is null when the parked snapshot is missing/expired at completion- // time (no_state). We can't read a status to skip a terminal op, but the- // bounded attempt cap below keeps a genuinely-gone parent from re-arming- // forever, so it's safe to retry instead of stranding on a transient miss.- const status = state?.status as string | undefined;- if (status === 'done' || status === 'error' || status === 'interrupted') return;-- const attempt = options.verifyAttempt ?? 1;- if (attempt > ASYNC_TOOL_VERIFY_MAX_ATTEMPTS) {- // Bounded retries spent and the parent is still not resumable — give up- // re-arming and report so the stuck wait can be detected, not silently- // accumulated.- log(- '[%s] async-tool barrier verify exhausted after %d attempts, giving up (status: %s)',- parentOperationId,- ASYNC_TOOL_VERIFY_MAX_ATTEMPTS,- status ?? 'missing',- );- asyncToolResumeCounter.add(1, { outcome: 'verify_exhausted' });- return;- }-- const delay = asyncToolVerifyDelayMs(attempt);- log(- '[%s] scheduling async-tool barrier verify attempt %d/%d in %dms (status: %s)',- parentOperationId,- attempt,- ASYNC_TOOL_VERIFY_MAX_ATTEMPTS,- delay,- status ?? 'missing',- );-- try {- await this.queueService.scheduleMessage({- context: undefined,- delay,- endpoint: `${this.baseURL}/run`,- operationId: parentOperationId,- payload: { asyncToolVerifyAttempt: attempt, verifyAsyncToolBarrier: true },- priority: 'high',- stepIndex: state?.stepCount ?? 0,- });- } catch (error) {- log(- '[%s] failed to schedule async-tool barrier verify (non-fatal): %O',- parentOperationId,- error,- );- }- }-- /**- * Stream a `callSubAgent` child's running totals to the client, once per step.- *- * Addressed to the PARENT's operationId, not the child's: the client opens one- * WebSocket per operation and never subscribes to the child's channel. The- * parent's channel is still live because parking at `waiting_for_async_tool`- * deliberately does not publish a stream-end event (see- * `AgentRuntimeCoordinator.STREAM_END_STATUSES`).- *- * Rides `step_complete` rather than a new event type because `AgentStreamEventType`- * is a closed union shared with the out-of-repo gateway worker; `phase` is the- * established discriminator and unknown phases are ignored by older clients.- *- * The three stat fields are read from exactly the same state paths that- * `completeSubAgentBridge` uses for its final backfill, so the live numbers- * converge on the persisted ones instead of jumping when the run ends.- *- * 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?.origin?.lineage?.progressAnchor as- { parentOperationId: string; toolMessageId: string } | undefined;- if (!anchor?.parentOperationId || !anchor.toolMessageId) return;-- try {- await this.streamManager.publishStreamEvent(anchor.parentOperationId, {- data: {- model: state?.modelRuntimeConfig?.model,- phase: 'subagent_progress',- toolMessageId: anchor.toolMessageId,- totalCost: state?.cost?.total,- totalInputTokens: state?.usage?.llm?.tokens?.input,- totalOutputTokens: state?.usage?.llm?.tokens?.output,- totalTokens: state?.usage?.llm?.tokens?.total,- totalToolCalls: state?.usage?.tools?.totalCalls,- },- stepIndex,- type: 'step_complete',- });- } catch (error) {- log('[%s] failed to publish sub-agent progress (non-fatal): %O', state?.operationId, error);- }- }-- /**- * Sub-agent completion bridge for the server `callSubAgent` deferred-tool- * path. Runs when a child sub-agent op reaches a terminal state — invoked- * in-process by the child's `onComplete` hook handler (local mode) or via- * the QStash-delivered `/webhooks/subagent-callback` endpoint (queue mode,- * where in-memory handler hooks don't survive cross-process steps).- *- * 1. Backfill the parent's placeholder tool message with the sub-agent's- * final answer (success) or an error note (failure), plus pluginState- * so the UI render can resolve the isolation thread.- * 2. Resume the parked parent: barrier-check + CAS via- * `tryResumeParentFromAsyncTool`, arming the delayed verify when the- * parent isn't resumable yet.- *- * THROWS on infrastructure failure of either half (state load, backfill,- * resume) so the queue-mode callback returns non-2xx and QStash redelivers- * the whole bridge — the delayed verify alone cannot recover a failed- * backfill, it only re-reads the barrier. Redelivery is safe: the backfill- * rewrites the same content and the resume is CAS-guarded.- *- * Returns true when this call won the resume CAS.- */- async completeSubAgentBridge(params: SubAgentBridgeParams): Promise<boolean> {- const { operationId, parentOperationId, reason, threadId, toolMessageId } = params;- const failed = reason === 'error' || reason === 'interrupted';-- // Infra errors propagate; a null state (expired) degrades to a stub note.- const finalState =- params.finalState ?? (await this.coordinator.loadAgentState(operationId)) ?? undefined;-- log(- '[%s] sub-agent bridge → parent %s (reason: %s, state: %s)',- operationId,- parentOperationId,- reason,- finalState ? 'loaded' : 'missing',- );-- // 1. Backfill the placeholder tool message with the result.- // `updateToolMessage` swallows transaction errors into `success: false`,- // so the flag must be checked — an unfulfilled message would hold the- // parent's barrier forever while the callback acked with 200.- //- // A state loaded via the fallback above arrives without `messages` (the- // persisted Redis blob no longer carries them — see- // AgentStateManager.serializeStateForPersist). Resolve the final leaf from- // the parsed DB conversation, then recover the original row by id so its- // serialized content stays paired with metadata.isMultimodal. An in-process- // params.finalState already carries messages and skips this query.- let lastAssistant: unknown;- if (!failed && finalState && !Array.isArray(finalState.messages)) {- try {- lastAssistant = await this.resolveLastAssistantMessageFromDB(finalState);- } catch (error) {- console.error(- '[%s] sub-agent bridge: failed to resolve final assistant from DB: %O',- operationId,- error,- );- }- }- const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];- lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));- let lastAssistantContent = extractTextFromMessage(lastAssistant);-- // Gated on `!finalState`, not merely an empty `lastAssistantContent`: a- // real (authoritative) final state whose last turn is legitimately- // textless (image-only, or the "preserve an empty leaf" case in- // `normalizeCompletionMessages`) must keep the stub below, not go dig- // through the thread's own message history — a lagging read could- // surface an EARLIER real reply from the same thread and silently show- // stale text instead of the correct empty-answer signal. `!finalState`- // is exactly the case this fallback exists for: heterogeneous (CLI-driven)- // children never populate it at all (see- // `resolveLastAssistantContentFromThread`'s doc comment), so there is no- // authoritative signal here to override.- if (!failed && !finalState && threadId) {- try {- lastAssistantContent = await this.resolveLastAssistantContentFromThread(threadId);- } catch (error) {- console.error(- '[%s] sub-agent bridge: failed to resolve content from thread %s: %O',- operationId,- threadId,- error,- );- }- }- const errorReason = failed- ? formatSubAgentErrorReason(finalState?.error ?? params.errorMessage)- : undefined;- const resultContent = failed- ? errorReason- ? `Sub-agent did not complete (${reason}): ${errorReason}`- : `Sub-agent did not complete (${reason}).`- : lastAssistantContent || 'Sub-agent completed without a textual answer.';- // callSubAgent results carry the sub-agent id so the parent can later send- // this same sub-agent a follow-up (`callSubAgent({ subAgentId })`) — e.g.- // to hand over what it gathered before failing — instead of redoing it.- const content = (await this.isCallSubAgentToolMessage(toolMessageId, threadId))- ? appendSubAgentReference(resultContent, threadId)- : resultContent;-- const { result: completed, blocked } = await this.controlCompletedToolResult({- preserveUsage: true,- operationId: parentOperationId,- toolMessageId,- result: {- content,- success: !failed,- error: failed- ? formatErrorForMetadata(finalState?.error ?? params.errorMessage)- : undefined,- state: {- model: finalState?.modelRuntimeConfig?.model,- status: failed ? 'error' : 'completed',- threadId,- // The child's spend rides on this anchor row so the parent's usage tray can- // account for it. The tray sums per-MESSAGE usage, and the child's own- // assistant messages live in an isolation thread the parent never loads —- // this row is the only place the child's cost surfaces in the parent's own- // message list.- totalCost: finalState?.cost?.total,- totalInputTokens: finalState?.usage?.llm?.tokens?.input,- totalOutputTokens: finalState?.usage?.llm?.tokens?.output,- totalToolCalls: finalState?.usage?.tools?.totalCalls,- totalTokens: finalState?.usage?.llm?.tokens?.total,- },- },- });- const backfill = await this.messageModel.updateToolMessage(toolMessageId, {- content: completed.content,- pluginError: completed.error ?? null,- pluginState: completed.state,- onlyIfEmpty: true,- ...(blocked && { replacePluginState: true }),- });- if (!backfill.success) {- throw new Error(- `Sub-agent bridge: failed to backfill tool message ${toolMessageId} for parent ${parentOperationId}`,- );- }-- // 2. Barrier + CAS + resume the parent op (infra errors propagate too).- // Pass the just-backfilled message id so the barrier trusts this write- // instead of re-reading a possibly-stale replica.- return this.tryResumeParentFromAsyncTool(- { parentOperationId },- { knownFulfilledMessageId: toolMessageId, scheduleVerifyOnHold: true },- );- }-- /**- * Whether the bridged placeholder belongs to `lobe-agent.callSubAgent` (the- * same bridge also serves `callAgent`, whose children cannot be continued).- * Best-effort: a failed lookup only drops the id trailer, never the bridge.- */- private async isCallSubAgentToolMessage(- toolMessageId: string,- threadId: string | undefined,- ): Promise<boolean> {- if (!threadId) return false;- try {- return isCallSubAgentCall(await this.messageModel.findMessagePlugin(toolMessageId));- } catch (error) {- log('[%s] sub-agent bridge: failed to read tool plugin: %O', toolMessageId, error);- return false;- }- }-- /**- * Whether every pending tool call has a fulfilled tool_result message — i.e.- * a tool message exists for its `tool_call_id` with non-empty content or a- * terminal pluginState. Looks up by `tool_call_id` (plugin id === message id).- *- * `knownFulfilledMessageId` short-circuits the per-tool content/state read for- * a placeholder the caller just backfilled in the same request: its terminal- * write is a local fact, so re-reading it (possibly from a lagging read- * replica) would only risk a false negative that strands the parent. The- * plugin row itself predates the park, so the `tool_call_id → plugin.id`- * lookup still resolves; only the freshly written content/state is trusted.- */- private async allPendingToolsFulfilled(- pending: ChatToolPayload[],- knownFulfilledMessageId?: string,- ): Promise<boolean> {- for (const tc of pending) {- const plugin = await this.serverDB.query.messagePlugins.findFirst({- where: (mp, { eq }) => eq(mp.toolCallId, tc.id),- });- if (!plugin) return false;-- // Trust the caller's own just-committed backfill (read-your-writes).- if (knownFulfilledMessageId && plugin.id === knownFulfilledMessageId) continue;-- const message = await this.messageModel.findById(plugin.id);- const pluginState = plugin.state as { status?: string } | null;- const fulfilled =- (!!message?.content && message.content.length > 0) ||- pluginState?.status === 'completed' ||- pluginState?.status === 'error';- if (!fulfilled) return false;- }- return true;- }-- /**- * Resolve the resume disposition for a parked op from the disposition hint- * persisted on its first pending tool message's pluginState. Group- * orchestration stamps `onComplete: 'finish'` there for skipCallSupervisor /- * delegate; everything else (sub-agents, client tools) resolves to `resume`.- * Self-describing so the generic verify watchdog finishes the right ops.- */- private async resolveAsyncToolOnComplete(- pending: ChatToolPayload[],- ): Promise<GroupActionOnComplete> {- // A batched turn can park multiple deferred/client tools. If ANY of them is- // a group action requesting finish (skipCallSupervisor / delegate), the- // orchestration must finish — reading only pending[0] would miss a group- // finish call that isn't the first pending tool and wrongly resume.- for (const tool of pending) {- const plugin = await this.serverDB.query.messagePlugins.findFirst({- where: (mp, { eq }) => eq(mp.toolCallId, tool.id),- });- const pluginState = plugin?.state as { onComplete?: string } | null;- if (pluginState?.onComplete === 'finish') return 'finish';- }- return 'resume';- }-- /**- * Count fulfilled member anchors under a group-management tool call — child- * `role: 'tool'` messages whose content is non-empty or whose pluginState is- * terminal. The K=N member barrier for broadcast / executeAgentTasks: the- * group tool message is only backfilled (satisfying the parked op's- * single-tool barrier) once this reaches the expected member count.- */- private async countFulfilledMemberAnchors(groupToolMessageId: string): Promise<number> {- const children = await this.serverDB.query.messages.findMany({- where: (m, { and, eq }) => and(eq(m.parentId, groupToolMessageId), eq(m.role, 'tool')),- });- let fulfilled = 0;- for (const child of children) {- if (child.content && child.content.length > 0) {- fulfilled += 1;- continue;- }- const plugin = await this.serverDB.query.messagePlugins.findFirst({- where: (mp, { eq }) => eq(mp.id, child.id),- });- const pluginState = plugin?.state as { status?: string } | null;- if (pluginState?.status === 'completed' || pluginState?.status === 'error') fulfilled += 1;- }- return fulfilled;- }-- /**- * Completion bridge for the group orchestration "call agent member" path- * (`lobe-group-management`: speak / broadcast / delegate / executeAgentTask(s)).- * Mirrors {@link completeSubAgentBridge} but enforces a K=N member barrier:- *- * 1. Backfill this member's anchor tool message (in_group → a short receipt,- * since the member already spoke in the shared group conversation;- * isolated → the member's final answer from its hidden thread).- * 2. Multi-member actions: hold until every member anchor is fulfilled, then- * backfill the supervisor's group tool message so the parked op's- * single-tool barrier passes. Single-member actions collapse the anchor- * onto the group tool call, so step 1 already satisfies the barrier.- * 3. Barrier-check + CAS resume/finish the parked supervisor via- * `tryResumeParentFromAsyncTool` (finish disposition read from the group- * tool message's pluginState).- *- * THROWS on infra failure of any backfill so the queue-mode callback returns- * non-2xx and QStash redelivers — backfills are idempotent and the resume is- * CAS-guarded, so redelivery is safe.- */- async completeGroupActionMember(params: GroupActionMemberBridgeParams): Promise<boolean> {- const {- anchorMessageId,- expectedMembers,- groupToolMessageId,- mode,- operationId,- parentOperationId,- reason,- threadId,- } = params;- const failed = reason === 'error' || reason === 'interrupted' || reason === 'timeout';-- // Members answer to the supervisor's approval mode, so a member can park on- // a tool that needs the user's approval. That segment fires `onComplete`- // (so the approval surfaces), but the member has not answered yet: leave its- // anchor pending and the supervisor parked. The approval continuation- // inherits this bridge hook and reports the member's real outcome.- if (reason === 'waiting_for_human') {- log(- '[%s] group-member bridge: member parked for human approval, holding parent %s',- operationId,- parentOperationId,- );- return false;- }-- const finalState =- params.finalState ?? (await this.coordinator.loadAgentState(operationId)) ?? undefined;-- log(- '[%s] group-member bridge → parent %s (mode: %s, reason: %s, %d members)',- operationId,- parentOperationId,- mode,- reason,- expectedMembers,- );-- // 1. Backfill this member's anchor.- // The member's textual answer is only read in delegate mode below; a state- // loaded via the fallback above arrives without `messages` (dropped from- // the persisted Redis blob — see AgentStateManager.serializeStateForPersist),- // so resolve the original final leaf from the DB when we actually need it.- // Keeping the original row preserves the exact content/metadata pairing- // that conversation-flow display grouping intentionally aggregates.- let lastAssistant: unknown;- if (!failed && mode !== 'in_group' && finalState && !Array.isArray(finalState.messages)) {- try {- lastAssistant = await this.resolveLastAssistantMessageFromDB(finalState);- } catch (error) {- console.error(- '[%s] group-member bridge: failed to resolve final assistant from DB: %O',- operationId,- error,- );- }- }- const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];- lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));- let lastAssistantContent = extractTextFromMessage(lastAssistant);-- // Gated on `!finalState`, not merely an empty `lastAssistantContent` —- // see the identical guard (and its full rationale) in- // `completeSubAgentBridge`. A real final state whose last turn is- // legitimately textless must keep the stub below, not risk surfacing a- // stale earlier reply from the thread's own history. `!finalState` is- // exactly the heterogeneous-isolated-member case this fallback exists- // for: it never populates `finalState` at all.- if (!failed && mode !== 'in_group' && !finalState && threadId) {- try {- lastAssistantContent = await this.resolveLastAssistantContentFromThread(threadId);- } catch (error) {- console.error(- '[%s] group-member bridge: failed to resolve content from thread %s: %O',- operationId,- threadId,- error,- );- }- }- const agentLabel = (finalState?.origin?.agentId as string | undefined) ?? 'member';- const memberErrorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;- const anchorContent = failed- ? memberErrorReason- ? `Agent member did not complete (${reason}): ${memberErrorReason}`- : `Agent member did not complete (${reason}).`- : mode === 'in_group'- ? `Agent ${agentLabel} responded in the group.`- : lastAssistantContent || 'Agent member completed without a textual answer.';-- const { result: completed, blocked } = await this.controlCompletedToolResult({- preserveUsage: true,- contextToolMessageId: groupToolMessageId,- operationId: parentOperationId,- toolMessageId: anchorMessageId,- result: {- content: anchorContent,- success: !failed,- error: failed ? formatErrorForMetadata(finalState?.error) : undefined,- state: {- model: finalState?.modelRuntimeConfig?.model,- status: failed ? 'error' : 'completed',- threadId,- // The child's spend rides on this anchor row so the parent's usage tray can- // account for it. The tray sums per-MESSAGE usage, and the child's own- // assistant messages live in an isolation thread the parent never loads —- // this row is the only place the child's cost surfaces in the parent's own- // message list.- totalCost: finalState?.cost?.total,- totalInputTokens: finalState?.usage?.llm?.tokens?.input,- totalOutputTokens: finalState?.usage?.llm?.tokens?.output,- totalToolCalls: finalState?.usage?.tools?.totalCalls,- totalTokens: finalState?.usage?.llm?.tokens?.total,- },- },- });- const anchorBackfill = await this.messageModel.updateToolMessage(anchorMessageId, {- content: completed.content,- pluginError: completed.error ?? null,- pluginState: completed.state,- onlyIfEmpty: true,- ...(blocked && { replacePluginState: true }),- });- if (!anchorBackfill.success) {- throw new Error(- `Group-member bridge: failed to backfill anchor ${anchorMessageId} for parent ${parentOperationId}`,- );- }-- return this.completeGroupMemberBarrier({- anchorMessageId,- expectedMembers,- groupToolMessageId,- parentOperationId,- });- }-- /** Shared by a child's completion and a member that failed before an operation existed. */- async completeGroupMemberBarrier({- anchorMessageId,- expectedMembers,- groupToolMessageId,- parentOperationId,- }: Pick<- GroupActionMemberBridgeParams,- 'anchorMessageId' | 'expectedMembers' | 'groupToolMessageId' | 'parentOperationId'- >): Promise<boolean> {- // 2. K=N member barrier (multi-member actions only — single-member actions- // use the group tool call itself as the anchor, already backfilled above).- if (expectedMembers > 1 && anchorMessageId !== groupToolMessageId) {- const fulfilled = await this.countFulfilledMemberAnchors(groupToolMessageId);- if (fulfilled < expectedMembers) {- log(- '[%s] group-member barrier %d/%d, holding parent %s',- parentOperationId,- fulfilled,- expectedMembers,- parentOperationId,- );- const parentState = await this.coordinator.loadAgentState(parentOperationId);- if (parentState) {- await this.maybeScheduleAsyncToolVerify(parentOperationId, parentState, {- scheduleVerifyOnHold: true,- });- }- return false;- }-- // All members done — backfill the group tool call so the parked op's- // single-tool barrier ([groupTool]) passes. Idempotent across racing- // last-committers; the resume/finish CAS guarantees one transition.- const { result: groupResult, blocked: groupBlocked } = await this.controlCompletedToolResult({- operationId: parentOperationId,- toolMessageId: groupToolMessageId,- result: {- content: `All ${expectedMembers} agent members completed.`,- state: { expectedMembers, status: 'completed' },- success: true,- },- });- const groupBackfill = await this.messageModel.updateToolMessage(groupToolMessageId, {- content: groupResult.content,- pluginError: groupResult.error ?? null,- pluginState: groupResult.state,- onlyIfEmpty: true,- ...(groupBlocked && {- replacePluginState: true,- }),- });- if (!groupBackfill.success) {- throw new Error(- `Group-member bridge: failed to backfill group tool ${groupToolMessageId} for parent ${parentOperationId}`,- );- }- }-- // 3. Barrier + CAS + resume/finish the parked supervisor op.- return this.tryResumeParentFromAsyncTool({ parentOperationId }, { scheduleVerifyOnHold: true });- }-- /**- * Schedule the group-member timeout watchdog. Fired `delayMs` after the member- * op is forked; if the member hasn't finished by then, the watchdog interrupts- * it and bridges a `timeout` completion so the parked supervisor doesn't wait- * forever. No-op when the queue is disabled or the timeout is non-positive.- */- async scheduleGroupMemberTimeout(- params: GroupMemberTimeoutParams,- delayMs: number,- ): Promise<void> {- if (!this.queueService || !(delayMs > 0)) return;- try {- await this.queueService.scheduleMessage({- context: undefined,- delay: delayMs,- endpoint: `${this.baseURL}/run`,- // Keyed on the member op so the /run worker can resolve userId from its- // metadata, same trust chain as every other scheduled step.- operationId: params.memberOperationId,- payload: { groupMemberTimeout: params },- priority: 'normal',- stepIndex: 0,- });- log(- '[%s] scheduled group-member timeout in %dms (parent %s)',- params.memberOperationId,- delayMs,- params.parentOperationId,- );- } catch (error) {- log(- '[%s] failed to schedule group-member timeout (non-fatal): %O',- params.memberOperationId,- error,- );- }- }-- /**- * Enforce a group member's timeout. No-op if the member already reached a- * terminal state (its own completion bridge handles that). Otherwise interrupt- * the member and bridge a `timeout` completion — backfilling its anchor and- * resuming/finishing the parked supervisor via the K=N barrier. The member's- * own interrupt bridge may also fire; both are idempotent (anchor rewrite +- * CAS-guarded resume).- */- private async handleGroupMemberTimeout(- params: GroupMemberTimeoutParams,- ): Promise<AgentExecutionResult> {- const state = await this.coordinator.loadAgentState(params.memberOperationId);- const status = state?.status as string | undefined;- if (!state || status === 'done' || status === 'error' || status === 'interrupted') {- log(- '[%s] group-member timeout: member already terminal (%s), no-op',- params.memberOperationId,- status,- );- return { nextStepScheduled: false, state: {}, success: true };- }-- log(- '[%s] group-member timeout fired, interrupting + bridging timeout to parent %s',- params.memberOperationId,- params.parentOperationId,- );- await this.interruptOperation(params.memberOperationId);-- const resumed = await this.completeGroupActionMember({- anchorMessageId: params.anchorMessageId,- expectedMembers: params.expectedMembers,- finalState: state,- groupToolMessageId: params.groupToolMessageId,- mode: params.mode,- onComplete: params.onComplete,- operationId: params.memberOperationId,- parentOperationId: params.parentOperationId,- reason: 'timeout',- });-- return { nextStepScheduled: resumed, state: {}, success: true };- }-- private async queryMessagesFromDB(state: AgentState) {- let postProcessUrl: ((path: string | null) => Promise<string>) | undefined;- try {- const fileService = new FileService(this.serverDB, this.userId);- postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);- } catch {- postProcessUrl = undefined;- }-- // MODEL, not `messageService.queryMessages`: this read feeds the LLM- // context and must keep every tool result whole. The service read path may- // reduce tool payloads to render-facing view models (see- // `@lobechat/tool-view-model`), which would silently strip the results the- // model is supposed to remember.- return this.messageModel.query(- {- 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.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- // of `query()`'s creator-facing agent-share exclusion.- { allowShareVisitor: true, postProcessUrl },- );- }-- /**- * Reload the conversation messages from the database and flatten them for the- * runtime. Used when resuming a parked op so the next LLM step sees tool- * results written out-of-band (e.g. by a sub-agent completion bridge).- */- private async refreshMessagesFromDB(state: AgentState): Promise<AgentState['messages']> {- const dbMessages = await this.queryMessagesFromDB(state);-- const { flatList } = parse(dbMessages, undefined, { threadId: state.origin?.threadId });- return flatList as AgentState['messages'];- }-- /**- * Use conversation-flow to select the active final assistant leaf, then- * recover that leaf from the original query result. FlatListBuilder moves- * child metadata onto its display-only group/first child, so the parsed leaf- * alone cannot reliably identify serialized multimodal content.- */- private async resolveLastAssistantMessageFromDB(state: AgentState): Promise<unknown> {- const dbMessages = await this.queryMessagesFromDB(state);- const { flatList } = parse(dbMessages, undefined, { threadId: state.origin?.threadId });- const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(flatList));- const lastAssistantId = typeof lastAssistant?.id === 'string' ? lastAssistant.id : undefined;-- return (- (lastAssistantId- ? dbMessages.find((message) => message.id === lastAssistantId)- : undefined) ?? lastAssistant- );- }-- /**- * Fallback content resolution for a heterogeneous (CLI-driven) sub-agent- * child in queue mode. `coordinator.loadAgentState`/`finalState` is always- * empty here: a hetero run never writes into the Redis-backed runtime state- * this class's step loop maintains (only `saveAgentState` calls under the- * homogeneous step loop populate it), and the completion webhook's- * `eventFields` deliberately excludes `lastAssistantContent` to keep the- * QStash payload lean (see `createSubAgentBridgeHook`'s doc comment) —- * `heteroFinish` already resolves the real answer server-side before- * dispatching, but that resolution never reaches this callback.- *- * The child's own conversation is queryable directly by its isolation- * `threadId` regardless — the same source `heteroFinish` itself reads via- * `heteroCurrentMsgId` before completion. Scoping by `threadId` alone is- * sufficient: thread ids are unique, so no `agentId`/`topicId` is needed to- * disambiguate.- */- private async resolveLastAssistantContentFromThread(- threadId: string,- ): Promise<string | undefined> {- const messages = await this.messageModel.query({ threadId }, { allowShareVisitor: true });- const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(messages));- return extractTextFromMessage(lastAssistant) || undefined;- }-- /**- * Overwrite `state.messages` in place with the canonical DB conversation at- * step entry, making the DB the single source of truth for messages.- *- * Guarded against regressions:- * - Ops carrying a non-persisted (ephemeral / suppressed) message — e.g. the- * group-member supervisor instruction, which has no DB row — keep their- * full working set in Redis (see `AgentStateManager.serializeStateForPersist`),- * so leave the loaded array intact instead of clobbering it with a DB-only- * view that would drop the prompt.- * - `state.messages` is guaranteed to end up an array, so a missing-identifier- * early return or an empty/failed read never hands `undefined` to downstream- * consumers (e.g. `shouldCompress(state.messages)`).- * - A populated working set is never replaced with an empty one or on a DB- * error, so a transient read miss can't blank the conversation mid-op.- * Reads once for UI, model hydration and same-step device discovery.- * Undefined rows mean the read was skipped or failed; [] is a successful read.- */- private async queryStepEntryMessages(state: AgentState): Promise<{- messages?: UIChatMessage[];- uiMessages?: UIChatMessage[];- }> {- if (!Array.isArray(state.messages)) state.messages = [];- if (!state.origin?.agentId || !state.origin?.topicId) return {};-- let messages: UIChatMessage[];- try {- // Keep full tool payloads and raw attachment paths. Each consumer derives- // its own view; mid-stream Work summaries are not used by the runtime.- messages = await this.messageModel.query(- {- agentId: state.origin.agentId,- groupId: state.origin.groupId,- skipWorks: true,- threadId: state.origin.threadId,- topicId: state.origin.topicId,- },- { allowShareVisitor: true },- );- } catch (error) {- console.error('[queryStepEntryMessages] Failed to load messages: %O', error);- return {};- }-- const [uiResult] = await Promise.all([- (async () => {- try {- return await this.messageService.prepareUiMessages(messages);- } catch (error) {- console.error('[queryStepEntryMessages] Failed to prepare UI messages: %O', error);- return undefined;- }- })(),- (async () => {- // Transient/id-less input must not be replaced by persisted history.- if (hasNonPersistedMessage(state.messages)) return;- try {- let fileService: FileService | undefined;- try {- fileService = new FileService(this.serverDB, this.userId);- } catch (error) {- // Match the model read's fallback when file storage is unavailable.- console.error('[queryStepEntryMessages] File service unavailable: %O', error);- }- const resolved = fileService- ? await resolveMessageFileUrls(messages, (file) =>- fileService!.getFullFileUrl(file.url),- )- : messages;- const { flatList } = parse(resolved, undefined, { threadId: state.origin?.threadId });- if (flatList.length > 0) state.messages = flatList as AgentState['messages'];- } catch (error) {- console.error('[queryStepEntryMessages] Failed to hydrate runtime messages: %O', error);- }- })(),- ]);- return { messages, uiMessages: uiResult };- }-- private resolveAsyncToolResumeParentMessageId(- messages: AgentState['messages'],- pendingTools: ChatToolPayload[],- ): string | undefined {- const fallbackParentMessageId = messages.at(-1)?.id;- if (pendingTools.length === 0) return fallbackParentMessageId;-- const toolResultMessageIds = new Map<string, string>();-- const collectToolResultIds = (message: unknown) => {- if (!message || typeof message !== 'object') return;-- const candidate = message as {- children?: unknown;- id?: unknown;- tool_call_id?: unknown;- tools?: unknown;- };-- if (typeof candidate.tool_call_id === 'string' && typeof candidate.id === 'string') {- toolResultMessageIds.set(candidate.tool_call_id, candidate.id);- }-- if (Array.isArray(candidate.tools)) {- for (const tool of candidate.tools) {- if (!tool || typeof tool !== 'object') continue;-- const toolPayload = tool as { id?: unknown; result_msg_id?: unknown };- if (typeof toolPayload.id === 'string' && typeof toolPayload.result_msg_id === 'string') {- toolResultMessageIds.set(toolPayload.id, toolPayload.result_msg_id);- }- }- }-- if (Array.isArray(candidate.children)) {- for (const child of candidate.children) {- collectToolResultIds(child);- }- }- };-- for (const message of messages) {- collectToolResultIds(message);- }-- for (let index = pendingTools.length - 1; index >= 0; index -= 1) {- const pendingTool = pendingTools[index];- if (pendingTool.result_msg_id) return pendingTool.result_msg_id;-- const resultMessageId = toolResultMessageIds.get(pendingTool.id);- if (resultMessageId) return resultMessageId;- }-- return fallbackParentMessageId;- }-- /**- * Create Agent Runtime instance- */- private async createAgentRuntime({- abortSignal,- agentState,- operationId,- stepIndex,- tracingContextEngine,- }: {- /** Cancels in-flight tool work when this step's operation is interrupted. */- abortSignal?: AbortSignal;- /**- * Current runtime state, when the caller has it. Only consulted to decide- * whether the early final-answer `visible_output_end` must be suppressed- * (entity-file edits ⇒ completion still has to export + register file- * Works, so loading should cover that window).- */- agentState?: any;- operationId: string;- stepIndex: number;- tracingContextEngine?: (input: unknown, output: unknown, metadata?: unknown) => void;- }) {- const state = agentState as AgentState | undefined;- const modelRuntimeConfig = state?.modelRuntimeConfig;- const contextWindowTokens =- modelRuntimeConfig?.model && modelRuntimeConfig?.provider- ? await getModelPropertyWithFallback<number | undefined>(- modelRuntimeConfig.model,- 'contextWindowTokens',- modelRuntimeConfig.provider,- )- : undefined;-- const world = state?.world;- const origin = state?.origin;- const plan = state?.plan;- const principal = state?.principal;-- // Create Agent instance — use custom factory if provided, otherwise default to GeneralChatAgent- const generalConfig = {- agentConfig: world?.agent,- compressionConfig: {- enabled: world?.agent?.chatConfig?.enableContextCompression ?? true,- maxWindowToken: contextWindowTokens ?? undefined,- },- dynamicInterventionAudits: {- ...dynamicInterventionAudits,- [DASHBOARD_DRY_RUN_AUDIT]: createWidgetDryRunAudit(- this.serverDB,- origin?.userId ?? this.userId,- this.workspaceId,- ),- },- modelRuntimeConfig,- operationId,- userId: origin?.userId,- };-- if (- origin?.trigger === RequestTrigger.Eval &&- plan?.eval?.toolForwarding &&- !hookDispatcher.hasHook(operationId, EVAL_TOOL_FORWARDING_HOOK_ID)- ) {- hookDispatcher.register(operationId, [- createEvalToolForwardingHook(plan.eval.toolForwarding, plan.eval.caseId),- ]);- }-- const agent = this.agentFactory- ? this.agentFactory(generalConfig)- : new GeneralChatAgent(generalConfig);-- // Create streaming executor context- const executorContext: RuntimeExecutorContext = {- abortSignal,- // The factory may be a Graph-aware dispatcher that still returns the- // default agent for ordinary conversations. Keep the early visible- // output end behavior tied to the actual agent, not factory presence.- //- // Additionally suppressed once the run edited entity-format files:- // completion still exports + registers them as `file` Works BEFORE the- // terminal snapshot (see `CompletionLifecycle.registerFileWorks`), and- // an early hint would end the visible loading seconds before that card- // can exist. Deferring to the terminal `visible_output_end` lets loading- // cover the export and the card land with `agent_runtime_end`.- agentShareVisitor: principal?.actor?.shareVisitor,- allowEarlyFinalAnswerVisibleOutputEnd:- agent instanceof GeneralChatAgent && !stateHasEntityFileEdits(agentState),- botContext: principal?.actor?.bot,- execSubAgent: this.delegate.execSubAgent,- execVirtualSubAgent: this.delegate.execVirtualSubAgent,- execGroupMember: this.delegate.execGroupMember,- onGroupMemberResult: (params) => this.completeGroupMemberBarrier(params),- hookDispatcher,- loadAgentState: this.coordinator.loadAgentState.bind(this.coordinator),- messageModel: this.messageModel,- modelRuntimeConfig,- operationId,- serverDB: this.serverDB,- stepIndex,- stream: plan?.stream,- streamManager: this.streamManager,- toolExecutionService: this.toolExecutionService,- topicId: origin?.topicId,- tracingContextEngine,- userId: origin?.userId,- workspaceId: this.workspaceId,- };-- // Create Agent Runtime instance- const runtime = new AgentRuntime(agent as any, {- executors: createRuntimeExecutors(executorContext),- });-- return { agent, runtime };- }-- /**- * Compute device context from DB messages at step boundary.- * Uses findInMessages visitor to scan tool messages for device activation.- */- private async computeDeviceContext(state: any, entryMessages?: UIChatMessage[]) {- try {- const dbMessages =- entryMessages ??- (await this.messageModel.query(- {- 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.origin?.groupId,- threadId: state.origin?.threadId,- topicId: state.origin?.topicId,- },- { allowShareVisitor: true },- ));-- return findInMessages(- dbMessages,- (msg) => {- const activeDeviceId = msg.pluginState?.metadata?.activeDeviceId;- if (activeDeviceId) {- return {- activeDeviceId,- devicePlatform: msg.pluginState?.metadata?.devicePlatform as string | undefined,- deviceSystemInfo: msg.pluginState?.metadata?.deviceSystemInfo as- Record<string, string> | undefined,- };- }- },- { role: 'tool' },- );- } catch (error) {- log('computeDeviceContext error: %O', error);- }-- return undefined;- }-- /**- * Decide whether to continue execution- */- private shouldContinueExecution(state: any, context?: any): boolean {- // Completed- if (state.status === 'done') return false;-- // Needs human intervention- if (state.status === 'waiting_for_human') return false;-- // Parked waiting for an async tool result (client tool / sub-agent)- if (state.status === 'waiting_for_async_tool') return false;-- // Parked waiting for a client to run the next LLM call- if (state.status === 'waiting_for_client') return false;-- // Error occurred- if (state.status === 'error') return false;-- // Interrupted- if (state.status === 'interrupted') return false;-- // maxSteps is handled by runtime.step() which sets forceFinish → status:'done'- // No redundant check here — trust the runtime state machine-- // Exceeded cost limit- if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) {- return state.costLimit.onExceeded !== 'stop';- }-- // No next context- if (!context) return false;-- return true;- }-- /**- * Identify a provider redelivery that must replay a completed approval- * lifecycle instead of being acknowledged as an ordinary stale step.- *- * `pendingApprovalBatch` is the durable, sealed runtime marker written before- * Review publication. The QStash retry header distinguishes a failed request- * redelivery from a benign duplicate that arrived after a successful ACK.- */- private shouldReplayPendingInterventionLifecycle(- state: AgentState,- stepIndex: number,- externalRetryCount: number,- ): boolean {- const checkpoint = state.metadata?.[INTERVENTION_LIFECYCLE_CHECKPOINT_KEY] as- InterventionLifecycleCheckpoint | undefined;-- return (- externalRetryCount > 0 &&- state.status === 'waiting_for_human' &&- state.pendingApprovalBatch?.sealed === true &&- // A missing checkpoint is a rollout-compatible pending state. Once a- // successful lifecycle writes `completed`, a lost HTTP response can be- // ACKed without publishing the Review or onComplete hook a second time.- (!checkpoint || (checkpoint.stepIndex === stepIndex && checkpoint.state === 'pending'))- );- }-- /**- * Checkpoint a fully delivered Review + onComplete lifecycle before the step- * request returns. This closes the common response-loss window: QStash may- * redeliver, but the stale-step guard can ACK a completed checkpoint without- * duplicating either side effect. The Review itself remains batch-idempotent- * for the smaller crash window before this checkpoint is saved.- */- private async recordInterventionLifecycleCompletion(- operationId: string,- state: AgentState,- stepIndex: number,- ): Promise<void> {- state.metadata = {- ...state.metadata,- [INTERVENTION_LIFECYCLE_CHECKPOINT_KEY]: {- state: 'completed',- stepIndex,- } satisfies InterventionLifecycleCheckpoint,- };-- try {- await this.coordinator.saveAgentState(operationId, state);- } catch (error) {- // The Review and hook are already delivered. Do not turn a best-effort- // dedup checkpoint failure into an agent error; a rare later redelivery- // safely retries the batch-idempotent Review and at-least-once hook.- log(- '[%s][%d] Failed to save intervention lifecycle checkpoint: %O',- operationId,- stepIndex,- error,- );- }- }-- /**- * Calculate step delay- */- private calculateStepDelay(stepResult: any): number {- const baseDelay = 50;-- // If there are tool calls, add longer delay- if (stepResult.events?.some((e: any) => e.type === 'tool_result')) {- return baseDelay + 50;- }-- // If there are errors, use exponential backoff- if (stepResult.events?.some((e: any) => e.type === 'error')) {- return Math.min(baseDelay * 2, 1000);- }-- return baseDelay;- }-- /**- * Calculate priority- */- private calculatePriority(stepResult: any): 'high' | 'normal' | 'low' {- // If human intervention needed, high priority- if (stepResult.newState?.status === 'waiting_for_human') {- return 'high';- }-- // If there are errors, normal priority- if (stepResult.events?.some((e: any) => e.type === 'error')) {- return 'normal';- }-- return 'normal';- }-- /**- * Determine operation completion reason- */- private determineCompletionReason(state: AgentState): StepCompletionReason {- if (state.status === 'error') return 'error';- if (state.status === 'interrupted') return 'interrupted';- if (state.status === 'waiting_for_human') return 'waiting_for_human';- if (state.status === 'waiting_for_async_tool') return 'waiting_for_async_tool';- if (state.status === 'waiting_for_client') return 'waiting_for_client';- // Checked ahead of 'done' on purpose: a run the repeat guard cut short ends- // in exactly that status, having emitted a turn with no tool calls. Reading- // it as a plain 'done' is what made these runs uncountable.- if (state.toolCallRepeatGuard?.stoppedByRepeatLimit) return 'tool_call_repeat_limit';- if (state.status === 'done') return 'done';- if (state.maxSteps && state.stepCount >= state.maxSteps) return 'max_steps';- if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) return 'cost_limit';- return 'done';- }-- /**- * Synchronously execute Agent operation until completion- *- * Used in test scenarios, doesn't depend on QueueService, executes all steps directly in the current process.- *- * @param operationId Operation ID- * @param options Execution options- * @returns Final state- *- * @example- * ```ts- * // Create operation (without auto-starting queue)- * const result = await service.createOperation({ ...params, autoStart: false });- *- * // Synchronously execute to completion- * const finalState = await service.executeSync(result.operationId);- * expect(finalState.status).toBe('done');- * ```- */- async executeSync(- operationId: string,- options?: {- /** Initial context (if not provided, inferred from state) */- initialContext?: AgentRuntimeContext;- /** Maximum step limit to prevent infinite loops, defaults to 9999 */- maxSteps?: number;- /** Callback after each step execution (for debugging) */- onStepComplete?: (stepIndex: number, state: AgentState) => void;- },- ): Promise<AgentState> {- const { maxSteps = 999, onStepComplete, initialContext } = options ?? {};-- log('[%s] Starting sync execution (maxSteps: %d)', operationId, maxSteps);-- // Load initial state- const initialState = await this.coordinator.loadAgentState(operationId);- if (!initialState) {- throw new Error(`Agent state not found for operation ${operationId}`);- }-- let state: AgentState = initialState;-- // Build initial context- // Priority: explicit initialContext param > saved initialContext in state > default- let context: AgentRuntimeContext | undefined =- initialContext ??- (state as any).initialContext ??- ({- payload: {},- phase: 'user_input' as const,- session: {- messageCount: state.messages?.length ?? 0,- sessionId: operationId,- status: state.status,- stepCount: state.stepCount,- },- } as AgentRuntimeContext);-- let stepIndex = state.stepCount;-- // Execution loop- while (stepIndex < maxSteps) {- // Check termination conditions- if (state.status === 'done' || state.status === 'error' || state.status === 'interrupted') {- log('[%s] Sync execution finished with status: %s', operationId, state.status);- break;- }-- // Parked on a pause (human intervention or an async tool / sub-agent- // result) — the result is delivered out-of-band, so sync execution- // can't resume it- if (isParkedStatus(state.status)) {- log('[%s] Sync execution paused: %s', operationId, state.status);- break;- }-- // Execute one step- log('[%s][%d] Start executing...', operationId, stepIndex);- const result = await this.executeStep({- context,- operationId,- stepIndex,- });-- state = result.state as AgentState;- context = result.stepResult.nextContext;- stepIndex++;-- // Callback- if (onStepComplete) {- onStepComplete(stepIndex, state);- }-- // Check if should continue- if (!this.shouldContinueExecution(state, context)) {- log('[%s] Sync execution stopped: shouldContinue=false', operationId);- break;- }- }-- if (stepIndex >= maxSteps) {- log('[%s] Sync execution stopped: reached maxSteps (%d)', operationId, maxSteps);- // If stopped due to executeSync's maxSteps limit, need to manually dispatch onComplete hooks- // Note: If stopped due to state.maxSteps being reached, onComplete has already been called in executeStep- if (state.status !== 'done' && state.status !== 'error') {- await this.completionLifecycle.emitSignalEvents(operationId, state, 'max_steps');- await this.completionLifecycle.dispatchHooks(operationId, state, 'max_steps');- }- }-- return state;- }-- /**- * Get Coordinator instance (for testing)- */- getCoordinator(): AgentRuntimeCoordinator {- return this.coordinator;- }-}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/asyncToolResume.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/asyncToolResume.test.tsnew file mode 100644index 00000000000..726fd97336d--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/asyncToolResume.test.ts@@ -0,0 +1,496 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentOperationModel } from '@/database/models/agentOperation';++import { hookDispatcher } from '../../hooks';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockQueueService: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator, mockQueueService } = setUpService(+ AgentRuntimeService,+ mockUserId,+ ));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('tryResumeParentFromAsyncTool', () => {+ const parentOpId = 'parent-op-async';++ const fulfilledPlugin = { id: 'msg-tc1', state: { status: 'completed' }, toolCallId: 'tc1' };++ const stubFulfilled = () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 3,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(fulfilledPlugin) },+ };+ (service as any).messageModel.findById = vi.fn().mockResolvedValue({ content: 'answer' });+ };++ it('wins the CAS and schedules the resume step when all pending tools are fulfilled', async () => {+ stubFulfilled();+ const casSpy = vi+ .spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool')+ .mockResolvedValue(true);++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(true);+ expect(casSpy).toHaveBeenCalledWith(parentOpId);+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: parentOpId,+ payload: { resumeAsyncTool: true },+ priority: 'high',+ stepIndex: 3,+ }),+ );+ });++ it('holds (no CAS, no schedule) when a pending tool is not yet fulfilled', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },+ };+ const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(false);+ expect(casSpy).not.toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('does not schedule when it loses the CAS to a concurrent sibling', async () => {+ stubFulfilled();+ vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool').mockResolvedValue(false);++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('skips when the parent is no longer parked', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'running',+ stepCount: 1,+ });+ const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(false);+ expect(casSpy).not.toHaveBeenCalled();+ });++ it('arms the first verify (attempt 1, 15s) when the parent has not parked yet and scheduleVerifyOnHold is set', async () => {+ // Child completed before the parent's parking step persisted its state.+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'running',+ stepCount: 2,+ });++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ delay: 15_000,+ operationId: parentOpId,+ payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },+ stepIndex: 2,+ }),+ );+ });++ it('arms a verify when the barrier is unsatisfied and scheduleVerifyOnHold is set', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },+ };++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },+ }),+ );+ });++ it('re-arms the next verify with exponential backoff while the barrier holds', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },+ };++ // A verify handler running as attempt 2 re-arms attempt 3 (60s).+ await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true, verifyAttempt: 3 },+ );++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ delay: 60_000,+ payload: { asyncToolVerifyAttempt: 3, verifyAsyncToolBarrier: true },+ }),+ );+ });++ it('stops re-arming once the bounded attempts are exhausted', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },+ };++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true, verifyAttempt: 6 },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('trusts a just-backfilled message id without re-reading it (read-your-writes)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 3,+ });+ // Plugin row exists (created at park) but its state still reads stale.+ const findById = vi.fn().mockResolvedValue({ content: '' });+ (service as any).serverDB.query = {+ messagePlugins: {+ findFirst: vi.fn().mockResolvedValue({ id: 'msg-tc1', state: null, toolCallId: 'tc1' }),+ },+ };+ (service as any).messageModel.findById = findById;+ const casSpy = vi+ .spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool')+ .mockResolvedValue(true);++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { knownFulfilledMessageId: 'msg-tc1' },+ );++ expect(won).toBe(true);+ expect(casSpy).toHaveBeenCalledWith(parentOpId);+ // The stale read must be skipped — barrier trusted the local backfill.+ expect(findById).not.toHaveBeenCalled();+ });++ it('arms a fallback verify when a parked op has no pending tools', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'waiting_for_async_tool',+ stepCount: 4,+ });+ const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(casSpy).not.toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },+ stepIndex: 4,+ }),+ );+ });++ it('does not arm a verify for terminal parent states', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'done',+ stepCount: 5,+ });++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('arms a verify when the parent state is missing/expired and scheduleVerifyOnHold is set', async () => {+ // Redis read replica hasn't seen the park yet, or the child outran the+ // parent's park. A missing state must retry, not strand on the first miss.+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(casSpy).not.toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: parentOpId,+ payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },+ // No state to read stepCount from — falls back to 0.+ stepIndex: 0,+ }),+ );+ });++ it('does not arm a verify on missing state when scheduleVerifyOnHold is not set', async () => {+ // The clean-done bridge path resumes without opting into the watchdog;+ // a missing state there must stay a silent no-op, not schedule a re-check.+ mockCoordinator.loadAgentState.mockResolvedValue(null);++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('stops re-arming on missing state once the bounded attempts are exhausted', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true, verifyAttempt: 6 },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('schedules a finish step when the parked tool requests onComplete=finish (skipCallSupervisor / delegate)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 4,+ });+ (service as any).serverDB.query = {+ messagePlugins: {+ findFirst: vi.fn().mockResolvedValue({+ id: 'msg-tc1',+ state: { onComplete: 'finish', status: 'completed' },+ toolCallId: 'tc1',+ }),+ },+ };+ (service as any).messageModel.findById = vi.fn().mockResolvedValue({ content: 'answer' });+ vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool').mockResolvedValue(true);++ const won = await service.tryResumeParentFromAsyncTool({ parentOperationId: parentOpId });++ expect(won).toBe(true);+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({ payload: { finishAfterAsyncTool: true }, stepIndex: 4 }),+ );+ });+ });++ describe('loadGroupMemberBridge', () => {+ const bridge = {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'isolated',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ threadId: 'thd-1',+ };++ it('reads the member and its bridge from the live runtime snapshot', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ host: { hooks: [{ id: 'group-member-bridge', webhook: { body: bridge } }] },+ origin: {+ agentId: 'agt-carol',+ groupId: 'cg-1',+ lineage: { orchestrationRole: 'member' },+ threadId: 'thd-1',+ topicId: 'tpc-1',+ },+ });++ expect(await service.loadGroupMemberBridge('op-carol')).toEqual({+ agentId: 'agt-carol',+ bridge,+ groupId: 'cg-1',+ threadId: 'thd-1',+ topicId: 'tpc-1',+ });+ });++ it('falls back to the durable row once the snapshot has expired', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ agentId: 'agt-carol',+ chatGroupId: 'cg-1',+ metadata: { groupMemberBridge: bridge },+ threadId: 'thd-1',+ topicId: 'tpc-1',+ });++ expect(await service.loadGroupMemberBridge('op-carol')).toEqual({+ agentId: 'agt-carol',+ bridge,+ groupId: 'cg-1',+ threadId: 'thd-1',+ topicId: 'tpc-1',+ });+ });++ it('is undefined for a run that is not a group member', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ agentId: 'agt-solo',+ metadata: {},+ });++ expect(await service.loadGroupMemberBridge('op-solo')).toBeUndefined();+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/completion.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/completion.test.tsnew file mode 100644index 00000000000..72fb1427bdc--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/completion.test.ts@@ -0,0 +1,354 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockDb: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator, mockDb } = setUpService(AgentRuntimeService, mockUserId));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('constructor', () => {+ it('should initialize with default base URL', () => {+ delete process.env.AGENT_RUNTIME_BASE_URL;+ const newService = new AgentRuntimeService(mockDb, mockUserId);+ expect((newService as any).baseURL).toBe('http://localhost:3210/api/agent');+ });++ it('should initialize with custom base URL from environment', () => {+ process.env.AGENT_RUNTIME_BASE_URL = 'http://custom:3000';+ const newService = new AgentRuntimeService(mockDb, mockUserId);+ expect((newService as any).baseURL).toBe('http://custom:3000/api/agent');+ });+ });++ describe('determineCompletionReason', () => {+ const reasonFor = (state: Record<string, any>) =>+ (service as any).determineCompletionReason(state);++ it('should report a plain completion as done', () => {+ expect(reasonFor({ status: 'done', stepCount: 3 })).toBe('done');+ });++ // The guard finalizes the turn without tool calls, which is indistinguishable+ // from a real answer by status alone — so these runs were all filed as 'done'+ // and could not be counted.+ it('should name a run the tool-call repeat guard cut short', () => {+ expect(+ reasonFor({+ status: 'done',+ stepCount: 250,+ toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },+ }),+ ).toBe('tool_call_repeat_limit');+ });++ it('should let a real failure outrank the repeat-guard marker', () => {+ expect(+ reasonFor({+ status: 'error',+ stepCount: 250,+ toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },+ }),+ ).toBe('error');+ expect(+ reasonFor({+ status: 'interrupted',+ stepCount: 250,+ toolCallRepeatGuard: { counts: {}, stoppedByRepeatLimit: true },+ }),+ ).toBe('interrupted');+ });++ it('should ignore a guard that counted repeats without ever stopping', () => {+ expect(+ reasonFor({ status: 'done', stepCount: 3, toolCallRepeatGuard: { counts: { sig: 4 } } }),+ ).toBe('done');+ });++ it('should still report the step and cost caps', () => {+ expect(reasonFor({ status: 'running', maxSteps: 10, stepCount: 10 })).toBe('max_steps');+ expect(+ reasonFor({+ status: 'running',+ stepCount: 3,+ cost: { total: 5 },+ costLimit: { maxTotalCost: 5 },+ }),+ ).toBe('cost_limit');+ });+ });++ describe('private methods', () => {+ describe('shouldContinueExecution', () => {+ it('should return false for completed status', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'done' },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return false for a plain interrupt with nothing left to settle', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'interrupted' },+ { phase: 'tool_result' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return false when waiting for human input', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'waiting_for_human' },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should not check maxSteps — delegated to runtime.step()', () => {+ // maxSteps is handled by runtime.step() which sets forceFinish → status:'done'+ // shouldContinueExecution only checks status, not maxSteps+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'running', maxSteps: 10, stepCount: 10 },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(true);+ });++ it('should continue when forceFinish is active even at maxSteps', () => {+ // When runtime sets forceFinish, the service must allow one more step+ // for the LLM to produce a final text response without tools+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'running', maxSteps: 5, stepCount: 6, forceFinish: true },+ { phase: 'llm_result' },+ );+ expect(shouldContinue).toBe(true);+ });++ it('should return false when cost limit exceeded with stop action', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ {+ status: 'running',+ cost: { total: 1 },+ costLimit: { maxTotalCost: 0.5, onExceeded: 'stop' },+ },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return true when cost limit exceeded with continue action', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ {+ status: 'running',+ cost: { total: 1 },+ costLimit: { maxTotalCost: 0.5, onExceeded: 'continue' },+ },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(true);+ });++ it('should return false when no context provided', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'running' },+ null,+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return true for normal running state', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'running' },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(true);+ });+ });++ describe('calculateStepDelay', () => {+ it('should return base delay for normal step', () => {+ const delay = (service as any).calculateStepDelay({+ events: [{ type: 'llm_response' }],+ });+ expect(delay).toBe(50);+ });++ it('should return longer delay for tool calls', () => {+ const delay = (service as any).calculateStepDelay({+ events: [{ type: 'tool_result' }],+ });+ expect(delay).toBe(100);+ });++ it('should return exponential backoff delay for errors', () => {+ const delay = (service as any).calculateStepDelay({+ events: [{ type: 'error' }],+ });+ expect(delay).toBe(100);+ });+ });++ describe('calculatePriority', () => {+ it('should return high priority for human input needed', () => {+ const priority = (service as any).calculatePriority({+ newState: { status: 'waiting_for_human' },+ events: [],+ });+ expect(priority).toBe('high');+ });++ it('should return normal priority for errors', () => {+ const priority = (service as any).calculatePriority({+ newState: { status: 'running' },+ events: [{ type: 'error' }],+ });+ expect(priority).toBe('normal');+ });++ it('should return normal priority by default', () => {+ const priority = (service as any).calculatePriority({+ newState: { status: 'running' },+ events: [{ type: 'llm_response' }],+ });+ expect(priority).toBe('normal');+ });+ });+ });++ describe('setQueuedMessages', () => {+ it('writes the flag for an operation owned by the caller', async () => {+ mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: mockUserId });+ mockCoordinator.setQueuedMessages.mockResolvedValue(undefined);++ await expect(service.setQueuedMessages('op-1', true)).resolves.toBe(true);++ expect(mockCoordinator.setQueuedMessages).toHaveBeenCalledWith('op-1', true);+ });++ it("refuses another user's operation", async () => {+ mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: 'someone-else' });++ await expect(service.setQueuedMessages('op-1', true)).resolves.toBe(false);++ expect(mockCoordinator.setQueuedMessages).not.toHaveBeenCalled();+ });++ it('refuses an unknown operation', async () => {+ mockCoordinator.getOperationMetadata.mockResolvedValue(null);++ await expect(service.setQueuedMessages('op-missing', false)).resolves.toBe(false);++ expect(mockCoordinator.setQueuedMessages).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.relayExecutor.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.relayExecutor.test.tsnew file mode 100644index 00000000000..9723dbc2e6e--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.relayExecutor.test.ts@@ -0,0 +1,753 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentOperationModel } from '@/database/models/agentOperation';++import { hookDispatcher } from '../../hooks';+import { type OperationCreationParams } from '../../types';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockQueueService: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator, mockQueueService } = setUpService(+ AgentRuntimeService,+ mockUserId,+ ));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('createOperation', () => {+ const mockParams: OperationCreationParams = {+ operationId: 'test-operation-1',+ initialContext: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: true,+ },+ session: { sessionId: 'test-operation-1', status: 'idle', stepCount: 0, messageCount: 0 },+ },+ appContext: {},+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ toolSet: { manifestMap: {} },+ userId: 'user-123',+ autoStart: true,+ initialMessages: [],+ };++ describe('relay executor (host.llmExecutor)', () => {+ const executor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', providers: ['ollama'] };+ // A parent run of the caller's own.+ const ownParent = (host: Record<string, unknown>) => ({+ host,+ origin: { userId: mockUserId },+ });++ it('stores the executor the client declared', async () => {+ await service.createOperation({ ...mockParams, autoStart: false, llmExecutor: executor });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host.llmExecutor).toEqual(executor);+ });++ it("lets a group member, mirrored onto its parent's channel, inherit the parent's executor", async () => {+ await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));+ mockCoordinator.saveAgentState.mockClear();++ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, orchestrationRole: 'member' },+ autoStart: false,+ parentOperationId: 'parent-op',+ });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host.llmExecutor).toEqual({+ ...executor,+ channelOperationId: 'parent-op',+ });+ });++ it("lets an independent sub-agent inherit the parent's executor, relaying on the parent's channel", async () => {+ await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));+ mockCoordinator.saveAgentState.mockClear();++ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, isSubAgent: true },+ autoStart: false,+ parentOperationId: 'parent-op',+ });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ // The tab only subscribes to the parked parent's channel, so the+ // child's `llm_execute` has to ride that one.+ expect(savedState.host.llmExecutor).toEqual({+ ...executor,+ channelOperationId: 'parent-op',+ });+ });++ it("keeps a nested child on the channel the executor's tab subscribed to", async () => {+ await mockCoordinator.saveAgentState(+ 'parent-op',+ ownParent({ llmExecutor: { ...executor, channelOperationId: 'root-op' } }),+ );+ mockCoordinator.saveAgentState.mockClear();++ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, isSubAgent: true },+ autoStart: false,+ parentOperationId: 'parent-op',+ });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host.llmExecutor).toEqual({+ ...executor,+ channelOperationId: 'root-op',+ });+ });++ it('relays on its own channel when the client declared the executor itself', async () => {+ await mockCoordinator.saveAgentState('parent-op', ownParent({ llmExecutor: executor }));+ mockCoordinator.saveAgentState.mockClear();++ const own = { ...executor, clientId: 'tab-b' };+ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, isSubAgent: true },+ autoStart: false,+ llmExecutor: own,+ parentOperationId: 'parent-op',+ });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host.llmExecutor).toEqual(own);+ });++ it("does not inherit the executor of another user's run", async () => {+ // A client names `parentOperationId`; a foreign run's executor would+ // hand this child's LLM payload to that user's tab.+ await mockCoordinator.saveAgentState('foreign-op', {+ host: { llmExecutor: executor },+ origin: { userId: 'someone-else' },+ });+ mockCoordinator.saveAgentState.mockClear();++ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, isSubAgent: true },+ autoStart: false,+ parentOperationId: 'foreign-op',+ });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host).not.toHaveProperty('llmExecutor');+ });++ it("does not inherit the executor of the user's run in another workspace", async () => {+ // The same user's run elsewhere relays with that workspace's providers.+ await mockCoordinator.saveAgentState('other-workspace-op', {+ host: { llmExecutor: executor },+ origin: { userId: mockUserId, workspaceId: 'ws-other' },+ });+ mockCoordinator.saveAgentState.mockClear();++ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, isSubAgent: true },+ autoStart: false,+ parentOperationId: 'other-workspace-op',+ });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host).not.toHaveProperty('llmExecutor');+ });++ it('carries no executor for a run nobody declared one for', async () => {+ await service.createOperation({ ...mockParams, autoStart: false });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host).not.toHaveProperty('llmExecutor');+ });+ });++ it('should create operation successfully with autoStart=true', async () => {+ mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');++ const result = await service.createOperation(mockParams);++ expect(result).toEqual({+ success: true,+ operationId: 'test-operation-1',+ autoStarted: true,+ messageId: 'message-123',+ });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ operationId: 'test-operation-1',+ status: 'idle',+ stepCount: 0,+ messages: [],+ modelRuntimeConfig: mockParams.modelRuntimeConfig,+ operationToolSet: expect.objectContaining({ manifestMap: {} }),+ origin: expect.objectContaining({ userId: mockParams.userId }),+ world: expect.objectContaining({ agent: mockParams.agentConfig }),+ }),+ );++ expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith('test-operation-1', {+ agentConfig: mockParams.agentConfig,+ modelRuntimeConfig: mockParams.modelRuntimeConfig,+ userId: mockParams.userId,+ });++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 0,+ context: mockParams.initialContext,+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high',+ delay: 50,+ });+ });++ it('freezes the builder editing target on the run origin', async () => {+ await service.createOperation({+ ...mockParams,+ appContext: {+ editingAgentId: 'agt_target',+ editingGroupId: 'grp_target',+ scope: 'agent_builder',+ },+ });++ const [, state] = mockCoordinator.saveAgentState.mock.calls[0];+ expect(state.origin).toMatchObject({+ editingAgentId: 'agt_target',+ editingGroupId: 'grp_target',+ });+ });++ it('records the approval mode as a run policy', async () => {+ await service.createOperation({+ ...mockParams,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ const [, state] = mockCoordinator.saveAgentState.mock.calls[0];+ expect(state.principal.policy.userIntervention).toEqual({ approvalMode: 'headless' });+ // Mirrored at the top level for the rolling-deploy window: a worker on the+ // pre-slot build reads only that, and would park this headless run.+ expect(state.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ });++ it('stores the run tool set once, on the operation slot', async () => {+ const manifestMap = { 'lobe-web-browsing': { identifier: 'lobe-web-browsing' } };++ await service.createOperation({+ ...mockParams,+ toolSet: {+ enabledToolIds: ['lobe-web-browsing'],+ executorMap: {},+ manifestMap,+ sourceMap: { 'lobe-web-browsing': 'builtin' },+ tools: [{ function: { name: 'search' }, type: 'function' }],+ } as unknown as OperationCreationParams['toolSet'],+ });++ const [, state] = mockCoordinator.saveAgentState.mock.calls[0];+ expect(state.operationToolSet.manifestMap).toEqual(manifestMap);+ // Manifests are the heaviest thing on the state and it is re-serialized at+ // every step, so the legacy top-level mirrors are not written any more.+ for (const mirror of ['toolExecutorMap', 'toolManifestMap', 'toolSourceMap', 'tools']) {+ expect(mirror in state).toBe(false);+ }+ });++ it('does not require durable storage for an environment-only result hook', async () => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error('db down'),+ );++ await expect(service.createOperation(mockParams)).resolves.toBeDefined();+ });++ it('requires durable storage for a caller result hook', async () => {+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error('db down'),+ );++ await expect(+ service.createOperation({+ ...mockParams,+ hooks: [+ {+ id: 'caller',+ type: 'afterToolCall',+ webhook: {+ url: 'https://hooks.example/caller',+ responseHandling: 'toolCall',+ },+ },+ ],+ }),+ ).rejects.toThrow('Failed to durably persist afterToolCall');+ });++ // Codex P1 on #20093: the member bridge lived only in the 2h runtime+ // snapshot, so a late approval continued the supervisor instead.+ it("keeps a durable copy of a group member's completion bridge on the row", async () => {+ const recordStart = vi+ .spyOn(AgentOperationModel.prototype, 'recordStart')+ .mockResolvedValue(undefined);+ const bridge = {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ };++ await service.createOperation({+ ...mockParams,+ hooks: [+ {+ handler: vi.fn(),+ id: 'group-member-bridge',+ type: 'onComplete',+ webhook: { body: bridge, url: '/api/agent/webhooks/group-member-callback' },+ },+ ],+ } as any);++ expect(recordStart.mock.calls[0][0].metadata).toMatchObject({ groupMemberBridge: bridge });+ });++ // Codex P2 on #20093: a transient start-row failure used to be swallowed,+ // so the member ran without the durable bridge its Stop / late approval need.+ it('refuses to start a group member whose bridge row could not be persisted', async () => {+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error('db down'),+ );++ await expect(+ service.createOperation({+ ...mockParams,+ hooks: [+ {+ handler: vi.fn(),+ id: 'group-member-bridge',+ type: 'onComplete',+ webhook: {+ body: {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ },+ url: '/api/agent/webhooks/group-member-callback',+ },+ },+ ],+ } as any),+ ).rejects.toThrow('Failed to durably persist group member');+ });++ it('keeps the frozen model facts on the run state but out of durable storage', async () => {+ const recordStart = vi+ .spyOn(AgentOperationModel.prototype, 'recordStart')+ .mockResolvedValue(undefined);+ const modelFacts = {+ cards: [{ abilities: { vision: true }, id: 'gpt-4', providerId: 'openai' }],+ model: 'gpt-4',+ provider: 'openai',+ };++ await service.createOperation({+ ...mockParams,+ modelRuntimeConfig: { ...mockParams.modelRuntimeConfig, modelFacts },+ });++ // The steps read the snapshot back off the state.+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ modelRuntimeConfig: expect.objectContaining({ modelFacts }),+ }),+ );+ // The row that outlives the run, and the metadata copy, stay as small as+ // they were: both only ever surface model / provider.+ expect(recordStart.mock.calls[0][0].modelRuntimeConfig).toEqual({ model: 'gpt-4' });+ expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({ modelRuntimeConfig: { model: 'gpt-4' } }),+ );+ });++ it('waits for dependent records before dispatch without losing the prepared context', async () => {+ let release!: () => void;+ const prepared = new Promise<void>((resolve) => {+ release = resolve;+ });+ const onOperationCreated = vi.fn<(operationId: string) => Promise<void>>(+ async () => prepared,+ );+ const initialContext = {+ ...mockParams.initialContext,+ payload: {+ assistantMessageId: 'repair-assistant',+ parentMessageId: 'verify-card',+ },+ } as OperationCreationParams['initialContext'];+ const creation = service.createOperation({+ ...mockParams,+ initialContext,+ onOperationCreated,+ });+ try {+ await vi.waitFor(() =>+ expect(onOperationCreated).toHaveBeenCalledWith(mockParams.operationId),+ );+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ } finally {+ release();+ }+ await creation;+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({ context: initialContext }),+ );+ });++ it('does not dispatch when dependent record preparation fails', async () => {+ await expect(+ service.createOperation({+ ...mockParams,+ onOperationCreated: async () => {+ throw new Error('Plan unavailable');+ },+ }),+ ).rejects.toThrow('Plan unavailable');+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('should create operation successfully with autoStart=false', async () => {+ const params = { ...mockParams, autoStart: false };++ const result = await service.createOperation(params);++ expect(result).toEqual({+ success: true,+ operationId: 'test-operation-1',+ autoStarted: false,+ messageId: undefined,+ });++ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('should handle errors during operation creation', async () => {+ mockCoordinator.saveAgentState.mockRejectedValueOnce(new Error('Database error'));++ await expect(service.createOperation(mockParams)).rejects.toThrow('Database error');+ });++ it('should pass maxSteps to initial state when provided', async () => {+ mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');++ await service.createOperation({ ...mockParams, maxSteps: 25 });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ maxSteps: 25,+ }),+ );+ });++ it('should place evalContext on the world snapshot when provided', async () => {+ mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');++ const evalContext = { envPrompt: 'You are in a test environment' };+ await service.createOperation({ ...mockParams, evalContext });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ world: expect.objectContaining({ eval: evalContext }),+ }),+ );+ });++ it('should persist the system-message context on the world snapshot', async () => {+ mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');++ const projectInstructions = [{ content: 'Use bun.', source: 'AGENTS.md' }];+ const connectorOwnershipNote = 'Gmail runs on Alice’s account.';+ await service.createOperation({+ ...mockParams,+ connectorOwnershipNote,+ projectInstructions,+ });++ // Steps can be claimed by another worker, so anything the context engine+ // needs has to survive on the persisted operation state — in the typed+ // `world` slot, which is the only place the engine reads it from.+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ world: expect.objectContaining({ connectorOwnershipNote, projectInstructions }),+ }),+ );+ });++ it('should persist the operation expertise snapshot in runtime state', async () => {+ mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');+ const expertise = {+ contentHash: 'stable-hash',+ domains: [{ id: 'domain-1', lessonIds: ['lesson-1'] }],+ renderedContext: '<expertise>stable</expertise>',+ schemaVersion: 1,+ };++ await service.createOperation({+ ...mockParams,+ enableExpertise: true,+ expertise,+ });++ // What the model is told about the run lives on the world slot, with the+ // top-level mirror kept for pre-slot workers during a rolling deploy.+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ enableExpertise: true,+ expertise,+ world: expect.objectContaining({ enableExpertise: true, expertise }),+ }),+ );+ });++ it('should restore tools activated in a previous operation into initial state', async () => {+ const taskManifest = { identifier: 'lobe-task' } as any;+ const initialMessages = [+ {+ content: 'Successfully activated tools: lobe-task',+ id: 'tool-message-1',+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },+ role: 'tool',+ },+ ] as any;++ await service.createOperation({+ ...mockParams,+ autoStart: false,+ initialMessages,+ initialStepCount: 3,+ toolSet: {+ ...mockParams.toolSet,+ activatableToolIds: ['lobe-task'],+ manifestMap: { 'lobe-task': taskManifest },+ },+ });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ activatedStepTools: [+ {+ activatedAtStep: 3,+ id: 'lobe-task',+ manifest: taskManifest,+ source: 'discovery',+ },+ ],+ }),+ );+ });++ it('should not restore historical tools that current run gates reject', async () => {+ await service.createOperation({+ ...mockParams,+ autoStart: false,+ initialMessages: [+ {+ content: 'Successfully activated tools: lobe-task',+ id: 'tool-message-1',+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },+ role: 'tool',+ },+ ] as any,+ toolSet: {+ ...mockParams.toolSet,+ // The broad discovery map may still contain the manifest in chat/custom+ // mode or for a model without function calling support.+ activatableToolIds: [],+ manifestMap: { 'lobe-task': { identifier: 'lobe-task' } as any },+ },+ });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({ activatedStepTools: undefined }),+ );+ });++ it('should abort before creating operation when signal is already aborted', async () => {+ const controller = new AbortController();+ controller.abort(new Error('startup aborted'));++ await expect(+ service.createOperation({+ ...mockParams,+ signal: controller.signal,+ }),+ ).rejects.toMatchObject({+ message: 'startup aborted',+ name: 'AbortError',+ });++ expect(mockCoordinator.createAgentOperation).not.toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('should cleanup partially created operation when aborted before scheduling', async () => {+ const controller = new AbortController();+ const originalCreateAgentOperation =+ mockCoordinator.createAgentOperation.getMockImplementation();++ mockCoordinator.createAgentOperation.mockImplementationOnce(async (...args: any[]) => {+ await originalCreateAgentOperation?.(...args);+ controller.abort(new Error('startup aborted'));+ });++ await expect(+ service.createOperation({+ ...mockParams,+ hooks: [{ handler: vi.fn(), id: 'hook-1', type: 'onComplete' }],+ signal: controller.signal,+ }),+ ).rejects.toMatchObject({+ message: 'startup aborted',+ name: 'AbortError',+ });++ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ expect(mockCoordinator.deleteAgentOperation).toHaveBeenCalledWith('test-operation-1');+ expect(hookDispatcher.hasHooks('test-operation-1')).toBe(false);+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.tsnew file mode 100644index 00000000000..aa2444c12fd--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts@@ -0,0 +1,206 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { type OperationCreationParams } from '../../types';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator } = setUpService(AgentRuntimeService, mockUserId));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('createOperation', () => {+ const mockParams: OperationCreationParams = {+ operationId: 'test-operation-1',+ initialContext: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: true,+ },+ session: { sessionId: 'test-operation-1', status: 'idle', stepCount: 0, messageCount: 0 },+ },+ appContext: {},+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ toolSet: { manifestMap: {} },+ userId: 'user-123',+ autoStart: true,+ initialMessages: [],+ };++ it.each([undefined, 'parent-operation'])(+ 'persists only caller hooks for a run with parent %s',+ async (parentOperationId) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'http://webhook-service/ingress');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-env-secret');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall, afterToolCall, beforeToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');+ const hooks = [+ {+ id: 'internal-callback',+ type: 'afterToolCall' as const,+ webhook: { url: 'http://webhook-service/internal' },+ },+ ];+ await service.createOperation({+ ...mockParams,+ autoStart: false,+ parentOperationId,+ hooks,+ });+ const state = await mockCoordinator.loadAgentState(mockParams.operationId);+ expect(state.host.hooks).toEqual(hooks);+ expect(JSON.stringify(state.host.hooks)).not.toContain('synthetic-env-secret');+ expect(hookDispatcher.hasHooks(mockParams.operationId)).toBe(true);+ },+ );++ it.each([undefined, false, true])(+ 'persists the snapshot opt-in for resumed steps (%s)',+ async (includeFinalState) => {+ await service.createOperation({ ...mockParams, autoStart: false, includeFinalState });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host.includeFinalState === true).toBe(includeFinalState === true);+ },+ );++ describe('file Works declaration (host.acceptsFileWorks)', () => {+ it('stores the declaration the client made', async () => {+ await service.createOperation({ ...mockParams, acceptsFileWorks: true, autoStart: false });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host.acceptsFileWorks).toBe(true);+ });++ it("lets a group member inherit its supervisor's declaration", async () => {+ await mockCoordinator.saveAgentState('parent-op', { host: { acceptsFileWorks: true } });+ mockCoordinator.saveAgentState.mockClear();++ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, orchestrationRole: 'member' },+ autoStart: false,+ parentOperationId: 'parent-op',+ });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host.acceptsFileWorks).toBe(true);+ });++ it.each([undefined, false])('carries no declaration for %s', async (acceptsFileWorks) => {+ await service.createOperation({ ...mockParams, acceptsFileWorks, autoStart: false });+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(savedState.host).not.toHaveProperty('acceptsFileWorks');+ });+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.tsnew file mode 100644index 00000000000..0d81c7128ef--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/evalToolForwarding.test.ts@@ -0,0 +1,247 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { AgentRuntimeService, createEvalToolForwardingHook } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ setUpService(AgentRuntimeService, mockUserId);+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('eval tool forwarding hook', () => {+ const event = {+ apiName: 'search_tweets',+ args: { query: 'test' },+ callIndex: 2,+ identifier: 'twitter',+ mock: vi.fn(),+ operationId: 'op-forwarding',+ stepIndex: 3,+ };++ beforeEach(() => {+ event.mock.mockReset();+ mockSsrfSafeFetch.mockReset();+ });++ it('forwards the beforeToolCall payload and preserves the returned tool result', async () => {+ const timeoutSpy = vi.spyOn(global, 'setTimeout');+ const result = { content: 'fixture result', state: { source: 'mock' }, success: true };+ mockSsrfSafeFetch.mockResolvedValue(+ new Response(JSON.stringify({ data: result, success: true })),+ );+ const hook = createEvalToolForwardingHook({+ twitter: { endpoint: 'https://mock.test/tool-calls' },+ });++ await hook.handler!(event as any);++ expect(mockSsrfSafeFetch).toHaveBeenCalledWith(+ 'https://mock.test/tool-calls',+ expect.objectContaining({ method: 'POST' }),+ );+ expect(JSON.parse(mockSsrfSafeFetch.mock.calls[0][1].body)).toEqual({+ data: { apiName: 'search_tweets', args: { query: 'test' }, identifier: 'twitter' },+ metadata: { callIndex: 2, operationId: 'op-forwarding', stepIndex: 3 },+ type: 'toolCall',+ });+ expect(timeoutSpy).toHaveBeenCalledWith(expect.any(Function), 15_000);+ expect(event.mock).toHaveBeenCalledWith(result);+ timeoutSpy.mockRestore();+ });++ it('includes the dataset case id in forwarding metadata', async () => {+ const result = { content: 'fixture result', success: true };+ mockSsrfSafeFetch.mockResolvedValue(+ new Response(JSON.stringify({ data: result, success: true })),+ );+ const hook = createEvalToolForwardingHook(+ { twitter: { endpoint: 'https://mock.test/tool-calls' } },+ 'case-42',+ );++ await hook.handler!(event as any);++ expect(JSON.parse(mockSsrfSafeFetch.mock.calls[0][1].body)).toMatchObject({+ metadata: { caseId: 'case-42' },+ });+ });++ it('mocks a failed result without executing the real tool', async () => {+ mockSsrfSafeFetch.mockResolvedValue(+ new Response(JSON.stringify({ error: 'fixture unavailable', success: false })),+ );+ const hook = createEvalToolForwardingHook({+ twitter: { endpoint: 'https://mock.test/tool-calls' },+ });++ await hook.handler!(event as any);++ expect(event.mock).toHaveBeenCalledWith({+ content: 'fixture unavailable',+ error: 'fixture unavailable',+ success: false,+ });+ });++ it('mocks a placeholder when a successful response has no tool result', async () => {+ mockSsrfSafeFetch.mockResolvedValue(new Response(JSON.stringify({ success: true })));+ const hook = createEvalToolForwardingHook({+ twitter: { endpoint: 'https://mock.test/tool-calls' },+ });++ await hook.handler!(event as any);++ expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });+ });++ it('mocks a placeholder when a successful response has an invalid tool result', async () => {+ mockSsrfSafeFetch.mockResolvedValue(+ new Response(JSON.stringify({ data: { content: 1, success: true }, success: true })),+ );+ const hook = createEvalToolForwardingHook({+ twitter: { endpoint: 'https://mock.test/tool-calls' },+ });++ await hook.handler!(event as any);++ expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });+ });++ it('mocks a failed result when the forwarding response is not JSON', async () => {+ mockSsrfSafeFetch.mockResolvedValue(new Response('not-json'));+ const hook = createEvalToolForwardingHook({+ twitter: { endpoint: 'https://mock.test/tool-calls' },+ });++ await hook.handler!(event as any);++ expect(event.mock).toHaveBeenCalledWith({+ content: expect.stringContaining('SyntaxError'),+ error: expect.any(SyntaxError),+ success: false,+ });+ });++ it('mocks transport failures', async () => {+ mockSsrfSafeFetch.mockRejectedValue('SSRF blocked');+ const hook = createEvalToolForwardingHook({+ twitter: { endpoint: 'https://mock.test/tool-calls' },+ });++ await hook.handler!(event as any);++ expect(event.mock).toHaveBeenCalledWith({+ content: 'SSRF blocked',+ error: 'SSRF blocked',+ success: false,+ });+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.credentials.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.credentials.test.tsnew file mode 100644index 00000000000..de205f76ab9--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.credentials.test.ts@@ -0,0 +1,682 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { type AgentExecutionParams } from '../../types';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockStreamManager: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator, mockStreamManager } = setUpService(+ AgentRuntimeService,+ mockUserId,+ ));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('executeStep', () => {+ const mockParams: AgentExecutionParams = {+ operationId: 'test-operation-1',+ stepIndex: 1,+ context: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: false,+ },+ session: {+ sessionId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messageCount: 1,+ },+ },+ };++ const mockState = {+ operationId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messages: [],+ events: [],+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ status: 'running',+ totalCost: 0,+ totalSteps: 1,+ };++ beforeEach(() => {+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ });++ describe('frozen credential snapshot', () => {+ const frozen = {+ credentials: [{ key: 'OPENAI', name: 'OpenAI', type: 'apiKey' }],+ workspaceId: undefined,+ };++ /**+ * Snapshot the state AT the save, not the object afterwards: the runtime+ * keeps mutating `newState`, so a later clear would otherwise read back as+ * if it had been persisted.+ */+ const runStepWithToolCall = async (apiName: string) => {+ const stateWithSnapshot = { ...mockState, operationCredentials: frozen };+ mockCoordinator.loadAgentState.mockResolvedValue(stateWithSnapshot);++ let persisted: string | undefined;+ mockCoordinator.saveStepResult.mockImplementationOnce(async (_id: string, result: any) => {+ persisted = JSON.stringify(result.newState);+ });++ const mockRuntime = {+ step: vi.fn().mockResolvedValue({+ events: [],+ newState: { ...stateWithSnapshot, status: 'running', stepCount: 2 },+ nextContext: {+ payload: { toolCall: { apiName, identifier: 'lobe-creds' } },+ phase: 'tool_result',+ },+ }),+ };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await service.executeStep(mockParams);++ expect(persisted).toBeDefined();+ return JSON.parse(persisted!);+ };++ it('drops the snapshot in the state it persists after the run saves a credential', async () => {+ const persistedState = await runStepWithToolCall('requestCredsInput');++ expect(persistedState.operationCredentials).toBeUndefined();+ });++ it('keeps the snapshot when the creds call only read', async () => {+ const persistedState = await runStepWithToolCall('injectCredsToSandbox');++ expect(persistedState.operationCredentials).toEqual({+ credentials: frozen.credentials,+ });+ });+ });++ it('should resume async tools with the last pending tool result as parentMessageId', async () => {+ const pendingTools = [+ {+ apiName: 'callSubAgent',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'agent-management',+ type: 'default',+ },+ {+ apiName: 'callSubAgent',+ arguments: '{}',+ id: 'tool-call-2',+ identifier: 'agent-management',+ type: 'default',+ },+ ];+ const parkedState = {+ ...mockState,+ interruption: {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ reason: 'async_tool',+ },+ pendingToolsCalling: pendingTools,+ status: 'waiting_for_async_tool',+ };+ const refreshedMessages = [+ { content: 'use tools', id: 'user-msg-1', role: 'user' },+ {+ children: [+ {+ id: 'assistant-msg-1',+ role: 'assistant',+ tools: [+ { ...pendingTools[0], result_msg_id: 'tool-msg-1' },+ { ...pendingTools[1], result_msg_id: 'tool-msg-2' },+ ],+ },+ ],+ id: 'assistant-group-1',+ role: 'assistantGroup',+ },+ ];+ const mockStepResult = {+ events: [],+ newState: { ...parkedState, pendingToolsCalling: [], status: 'done', stepCount: 2 },+ nextContext: null,+ };+ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };++ mockCoordinator.loadAgentState.mockResolvedValue(parkedState);+ vi.spyOn(service as any, 'refreshMessagesFromDB').mockResolvedValue(refreshedMessages);+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await service.executeStep({ ...mockParams, resumeAsyncTool: true });++ expect(mockRuntime.step).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: refreshedMessages,+ pendingToolsCalling: [],+ status: 'running',+ }),+ expect.objectContaining({+ payload: { parentMessageId: 'tool-msg-2' },+ phase: 'user_input',+ }),+ );+ });++ // Approving a callSubAgent starts a resume op that seeds its assistant+ // placeholder, runs the tool, then parks on the deferred sub-agent. The+ // resumed turn must fill that seed; a second assistant left the seed as an+ // empty "…" branch that hid the real answer.+ it('fills the seeded assistant placeholder when resuming from an async tool', async () => {+ const parkedState = {+ ...mockState,+ interruption: {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ reason: 'async_tool',+ },+ pendingAssistantMessageId: 'seeded-assistant-1',+ pendingToolsCalling: [+ {+ apiName: 'callSubAgent',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'lobe-agent',+ type: 'builtin',+ },+ ],+ status: 'waiting_for_async_tool',+ };+ const refreshedMessages = [+ { content: 'research', id: 'user-msg-1', role: 'user' },+ {+ id: 'assistant-msg-1',+ role: 'assistant',+ tools: [{ id: 'tool-call-1', result_msg_id: 'tool-msg-1' }],+ },+ ];+ const mockRuntime = {+ step: vi.fn().mockResolvedValue({+ events: [],+ newState: { ...parkedState, pendingToolsCalling: [], status: 'done', stepCount: 2 },+ nextContext: null,+ }),+ };++ mockCoordinator.loadAgentState.mockResolvedValue(parkedState);+ vi.spyOn(service as any, 'refreshMessagesFromDB').mockResolvedValue(refreshedMessages);+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await service.executeStep({ ...mockParams, resumeAsyncTool: true });++ expect(mockRuntime.step).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ payload: { assistantMessageId: 'seeded-assistant-1', parentMessageId: 'tool-msg-1' },+ phase: 'user_input',+ }),+ );+ });++ it('should handle missing agent state', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);++ await expect(service.executeStep(mockParams)).rejects.toThrow(+ 'Agent state not found for operation test-operation-1',+ );+ });++ it('should handle execution errors', async () => {+ const error = new Error('Runtime error');+ const mockRuntime = { step: vi.fn().mockRejectedValue(error) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await expect(service.executeStep(mockParams)).rejects.toThrow('Runtime error');++ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {+ type: 'error',+ stepIndex: 1,+ data: {+ stepIndex: 1,+ phase: 'step_execution',+ error: 'Runtime error',+ errorType: '500',+ },+ });+ });++ it('should dispatch onComplete hook with error in finalState when execution fails', async () => {+ const error = new Error('Runtime error');+ const mockRuntime = { step: vi.fn().mockRejectedValue(error) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ await expect(service.executeStep(mockParams)).rejects.toThrow('Runtime error');++ // Verify onComplete hooks dispatched with error in finalState as ChatMessageError+ expect(dispatchSpy).toHaveBeenCalledWith(+ 'test-operation-1',+ 'onComplete',+ expect.objectContaining({+ operationId: 'test-operation-1',+ reason: 'error',+ finalState: expect.objectContaining({+ error: expect.objectContaining({+ type: 500, // ChatErrorType.InternalServerError+ message: 'Runtime error',+ body: expect.objectContaining({ name: 'Error' }),+ }),+ }),+ }),+ undefined,+ );++ dispatchSpy.mockRestore();+ });++ it('should dispatch onComplete hook with ChatCompletionErrorPayload in finalState', async () => {+ // Simulate LLM error format: { errorType: 'InvalidProviderAPIKey', error: { ... } }+ const llmError = {+ errorType: 'InvalidProviderAPIKey',+ error: { status: 401 },+ provider: 'openai',+ };+ const mockRuntime = { step: vi.fn().mockRejectedValue(llmError) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ await expect(service.executeStep(mockParams)).rejects.toEqual(llmError);++ // Verify error is formatted correctly with type from errorType+ expect(dispatchSpy).toHaveBeenCalledWith(+ 'test-operation-1',+ 'onComplete',+ expect.objectContaining({+ operationId: 'test-operation-1',+ reason: 'error',+ finalState: expect.objectContaining({+ error: expect.objectContaining({+ type: 'InvalidProviderAPIKey',+ message: 'InvalidProviderAPIKey',+ body: expect.objectContaining({ status: 401 }),+ }),+ }),+ }),+ undefined,+ );++ dispatchSpy.mockRestore();+ });++ it('should save error state to coordinator for later retrieval (inMemory mode fix)', async () => {+ const error = new Error('Test error for inMemory mode');+ const mockRuntime = { step: vi.fn().mockRejectedValue(error) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ // Spy on coordinator.saveAgentState to verify it's called with error state+ const saveStateSpy = vi.spyOn((service as any).coordinator, 'saveAgentState');++ await expect(service.executeStep(mockParams)).rejects.toThrow('Test error for inMemory mode');++ // Verify saveAgentState is called with error state before onComplete+ expect(saveStateSpy).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ error: expect.objectContaining({+ type: 500, // ChatErrorType.InternalServerError+ message: 'Test error for inMemory mode',+ }),+ status: 'error',+ }),+ );+ });++ it('should handle human intervention', async () => {+ const paramsWithIntervention = {+ ...mockParams,+ humanInput: { type: 'text', content: 'user input' },+ approvedToolCall: { toolName: 'calculator', args: {} },+ rejectionReason: 'Not safe',+ };++ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'done' },+ nextContext: null,+ events: [],+ };++ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });+ const processSpy = vi.spyOn((service as any).humanIntervention, 'process').mockResolvedValue({+ newState: mockState,+ nextContext: mockParams.context,+ });++ const result = await service.executeStep(paramsWithIntervention);++ expect(processSpy).toHaveBeenCalledWith(mockState, {+ approvedToolCall: paramsWithIntervention.approvedToolCall,+ humanInput: paramsWithIntervention.humanInput,+ rejectAndContinue: undefined,+ rejectionReason: paramsWithIntervention.rejectionReason,+ toolMessageId: undefined,+ });++ expect(result.success).toBe(true);+ expect(result.nextStepScheduled).toBe(false); // Should not schedule next step when status is 'done'+ });++ it('should detect interruption that occurred during step execution', async () => {+ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'running' },+ nextContext: mockParams.context,+ events: [],+ };++ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ // Initial load returns running state; the post-step interrupt check+ // reads the sentinel instead of the state blob+ mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);+ mockCoordinator.isInterrupted.mockResolvedValueOnce(true);++ const result = await service.executeStep(mockParams);++ // The step result should reflect the interrupted status+ expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));+ expect(result.nextStepScheduled).toBe(false);+ // saveStepResult should be called with interrupted state+ expect(mockCoordinator.saveStepResult).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ newState: expect.objectContaining({ status: 'interrupted' }),+ }),+ );+ });++ it('should detect an interruption written by an old worker without a sentinel', async () => {+ const mockStepResult = {+ events: [],+ newState: { ...mockState, status: 'running', stepCount: 2 },+ nextContext: mockParams.context,+ };++ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });+ mockCoordinator.loadAgentState+ .mockResolvedValueOnce(mockState)+ .mockResolvedValueOnce({ ...mockState, status: 'interrupted' });+ mockCoordinator.isInterrupted.mockResolvedValueOnce(false);++ const result = await service.executeStep(mockParams);++ expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));+ expect(result.nextStepScheduled).toBe(false);+ expect(mockCoordinator.loadAgentState).toHaveBeenCalledTimes(2);+ expect(mockCoordinator.saveStepResult).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ newState: expect.objectContaining({ status: 'interrupted' }),+ }),+ );+ });++ it('should abort a long step when an old worker writes only interrupted state', async () => {+ vi.useFakeTimers();+ const mockStepResult = {+ events: [],+ newState: { ...mockState, status: 'running', stepCount: 2 },+ nextContext: mockParams.context,+ };++ try {+ vi.spyOn(service as any, 'createAgentRuntime').mockImplementation(function (+ ...args: unknown[]+ ) {+ const { abortSignal } = args[0] as { abortSignal: AbortSignal };+ return {+ runtime: {+ step: vi.fn(function () {+ return new Promise((resolve) => {+ abortSignal.addEventListener('abort', () => resolve(mockStepResult), {+ once: true,+ });+ });+ }),+ },+ };+ });+ mockCoordinator.loadAgentState+ .mockResolvedValueOnce(mockState)+ .mockResolvedValue({ ...mockState, status: 'interrupted' });+ mockCoordinator.isInterrupted.mockResolvedValue(false);++ const execution = service.executeStep(mockParams);+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(30_000);+ const result = await execution;++ expect(result.state).toEqual(expect.objectContaining({ status: 'interrupted' }));+ expect(result.nextStepScheduled).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('should resolve pending client tools when interruption races the parked result', async () => {+ const completedTool = {+ apiName: 'calculate',+ arguments: '{}',+ id: 'completed-server-tool-call',+ identifier: 'server-tool',+ type: 'default' as const,+ };+ const pendingTool = {+ apiName: 'search',+ arguments: '{}',+ id: 'client-tool-call',+ identifier: 'client-tool',+ type: 'default' as const,+ };+ const parkedResult = {+ events: [{ type: 'interrupted' as const }],+ newState: {+ ...mockState,+ messages: [+ {+ content: 'Completed server result',+ role: 'tool' as const,+ tool_call_id: completedTool.id,+ },+ ],+ pendingToolsCalling: [pendingTool],+ status: 'waiting_for_async_tool' as const,+ stepCount: 2,+ },+ nextContext: undefined,+ };+ const resolvedResult = {+ events: [{ type: 'done' as const }],+ newState: {+ ...parkedResult.newState,+ messages: [+ ...parkedResult.newState.messages,+ {+ content: 'Tool execution was aborted by user.',+ role: 'tool' as const,+ tool_call_id: pendingTool.id,+ },+ ],+ status: 'done' as const,+ },+ };+ const mockRuntime = {+ step: vi.fn().mockResolvedValueOnce(parkedResult).mockResolvedValueOnce(resolvedResult),+ };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });+ mockCoordinator.loadAgentState.mockResolvedValueOnce(mockState);+ mockCoordinator.isInterrupted.mockResolvedValueOnce(true);++ const mixedBatchContext = {+ ...mockParams.context!,+ payload: {+ ...(mockParams.context!.payload as Record<string, unknown>),+ hasToolsCalling: true,+ toolsCalling: [completedTool, pendingTool],+ },+ phase: 'llm_result' as const,+ };+ const result = await service.executeStep({ ...mockParams, context: mixedBatchContext });++ expect(result.state).toEqual(+ expect.objectContaining({+ messages: expect.arrayContaining([+ expect.objectContaining({+ content: 'Completed server result',+ tool_call_id: completedTool.id,+ }),+ expect.objectContaining({ tool_call_id: pendingTool.id }),+ ]),+ status: 'interrupted',+ }),+ );+ expect(mockRuntime.step).toHaveBeenCalledTimes(2);+ expect(mockRuntime.step).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: 'interrupted' }),+ expect.objectContaining({+ payload: expect.objectContaining({ toolsCalling: [pendingTool] }),+ phase: 'llm_result',+ }),+ );+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.tsnew file mode 100644index 00000000000..029d3621fdb--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.test.ts@@ -0,0 +1,497 @@+/**+ * @vitest-environment node+ */+import { getModelPropertyWithFallback } from '@lobechat/model-runtime';+import type { UIChatMessage } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { type AgentExecutionParams } from '../../types';+import { AgentRuntimeService } from '..';+import { buildPersistedToolChain, setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockStreamManager: any;+ let mockQueueService: any;+ let mockDb: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator, mockStreamManager, mockQueueService, mockDb } = setUpService(+ AgentRuntimeService,+ mockUserId,+ ));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('executeStep', () => {+ const mockParams: AgentExecutionParams = {+ operationId: 'test-operation-1',+ stepIndex: 1,+ context: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: false,+ },+ session: {+ sessionId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messageCount: 1,+ },+ },+ };++ const mockState = {+ operationId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messages: [],+ events: [],+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ status: 'running',+ totalCost: 0,+ totalSteps: 1,+ };++ beforeEach(() => {+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ });++ it('acks a delayed delivery after the durable operation was abandoned', async () => {+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ id: mockParams.operationId,+ status: 'abandoned',+ });++ const result = await service.executeStep(mockParams);++ expect(result).toEqual({+ nextStepScheduled: false,+ state: { status: 'interrupted' },+ stepResult: null,+ success: true,+ });+ expect(mockCoordinator.tryClaimStep).not.toHaveBeenCalled();+ });++ it('should pass resolved contextWindowTokens into compressionConfig', async () => {+ vi.mocked(getModelPropertyWithFallback).mockResolvedValueOnce(200_000);++ let capturedConfig: any;+ const serviceWithFactory = new AgentRuntimeService(mockDb, mockUserId, {+ agentFactory: (config) => {+ capturedConfig = config;+ return { runner: vi.fn() } as any;+ },+ });++ await (serviceWithFactory as any).createAgentRuntime({+ agentState: {+ world: { agent: { chatConfig: { enableContextCompression: true } } as any },+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },+ },+ operationId: 'test-operation-1',+ stepIndex: 1,+ });++ expect(getModelPropertyWithFallback).toHaveBeenCalledWith(+ 'gpt-4o-mini',+ 'contextWindowTokens',+ 'openai',+ );+ expect(capturedConfig).toEqual(+ expect.objectContaining({+ compressionConfig: expect.objectContaining({+ enabled: true,+ maxWindowToken: 200_000,+ }),+ }),+ );+ });++ it('should fall back to undefined maxWindowToken when model lookup misses', async () => {+ vi.mocked(getModelPropertyWithFallback).mockResolvedValueOnce(undefined);++ let capturedConfig: any;+ const serviceWithFactory = new AgentRuntimeService(mockDb, mockUserId, {+ agentFactory: (config) => {+ capturedConfig = config;+ return { runner: vi.fn() } as any;+ },+ });++ await (serviceWithFactory as any).createAgentRuntime({+ agentState: {+ world: { agent: { chatConfig: { enableContextCompression: true } } as any },+ modelRuntimeConfig: { model: 'unknown-model', provider: 'openai' },+ },+ operationId: 'test-operation-1',+ stepIndex: 1,+ });++ expect(capturedConfig).toEqual(+ expect.objectContaining({+ compressionConfig: expect.objectContaining({+ enabled: true,+ maxWindowToken: undefined,+ }),+ }),+ );+ });++ it.each([false, true])(+ 'reuses the entry read for device discovery (device=%s)',+ async (withDevice) => {+ const state = {+ ...mockState,+ messages: [],+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ };+ mockCoordinator.loadAgentState.mockResolvedValue(state);+ const dbMessages = buildPersistedToolChain('full model answer');+ dbMessages[0].imageList = [{ id: 'file-1', url: 'raw/image', alt: 'image' }];+ if (withDevice) {+ dbMessages[0] = {+ ...dbMessages[0],+ role: 'tool',+ pluginState: { metadata: { activeDeviceId: 'device-1', devicePlatform: 'darwin' } },+ };+ }+ const query = (service as any).messageModel.query.mockResolvedValue(dbMessages);+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue([]);+ const step = vi.fn().mockImplementation(async (input) => ({+ events: [],+ newState: { ...input, stepCount: 2 },+ nextContext: mockParams.context,+ }));+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });++ const result = await service.executeStep(mockParams);++ expect(result.success).toBe(true);+ expect(query).toHaveBeenCalledTimes(1);+ expect(JSON.stringify(step.mock.calls[0][0].messages)).toContain('full model answer');+ expect(JSON.stringify(step.mock.calls[0][0].messages)).toContain('model:raw/image');+ expect(dbMessages[0].imageList?.[0].url).toBe('raw/image');+ expect(step.mock.calls[0][0].binding?.device?.id).toBe(withDevice ? 'device-1' : undefined);+ },+ );++ // The executors read the device id through the same gate, so binding one for+ // a run that may not touch a device buys nothing — and its working directory+ // and system info would ride into the prompt variables.+ it.each([+ { policy: { deviceAccess: { canUseDevice: false, reason: 'external-bot' } }, why: 'policy' },+ { plan: { execution: { kind: 'sandbox', target: 'sandbox' } }, why: 'plan' },+ ])('does not adopt a device the run may not use ($why)', async ({ plan, policy }) => {+ const state = {+ ...mockState,+ messages: [],+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ ...(plan && { plan }),+ ...(policy && { principal: { policy } }),+ };+ mockCoordinator.loadAgentState.mockResolvedValue(state);+ const dbMessages = buildPersistedToolChain('answer');+ dbMessages[0] = {+ ...dbMessages[0],+ pluginState: {+ metadata: {+ activeDeviceId: 'device-1',+ devicePlatform: 'darwin',+ deviceSystemInfo: { workingDirectory: '/Users/someone/secret' },+ },+ },+ role: 'tool',+ };+ (service as any).messageModel.query.mockResolvedValue(dbMessages);+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue([]);+ const step = vi.fn().mockImplementation(async (input) => ({+ events: [],+ newState: { ...input, stepCount: 2 },+ nextContext: mockParams.context,+ }));+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });++ const result = await service.executeStep(mockParams);++ expect(result.success).toBe(true);+ expect(step.mock.calls[0][0].binding?.device).toBeUndefined();+ });++ describe('activateDevice after a device is already bound', () => {+ const activation = (id: string, deviceId: string): UIChatMessage =>+ ({+ content: `Device "${deviceId}" activated successfully.`,+ createdAt: 3,+ id,+ pluginState: { metadata: { activeDeviceId: deviceId } },+ role: 'tool',+ updatedAt: 3,+ }) as UIChatMessage;++ const runStep = async (execution: Record<string, unknown>) => {+ const state = {+ ...mockState,+ binding: { device: { id: 'device-a' } },+ messages: [],+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ plan: { execution },+ };+ mockCoordinator.loadAgentState.mockResolvedValue(state);+ // The model activated device-a first, then device-b.+ (service as any).messageModel.query.mockResolvedValue([+ ...buildPersistedToolChain('answer'),+ activation('activate-a', 'device-a'),+ activation('activate-b', 'device-b'),+ ]);+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue([]);+ const step = vi.fn().mockImplementation(async (input) => ({+ events: [],+ newState: { ...input, stepCount: 2 },+ nextContext: mockParams.context,+ }));+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });++ const result = await service.executeStep(mockParams);+ expect(result.success).toBe(true);+ return step.mock.calls[0][0].binding?.device?.id;+ };++ it('follows the latest activation while the plan leaves the device open', async () => {+ const deviceId = await runStep({+ kind: 'device-unrouted',+ reason: 'ambiguous-online-devices',+ target: 'auto',+ });++ expect(deviceId).toBe('device-b');+ });++ it('keeps a locked run on its device even if history names another one', async () => {+ const deviceId = await runStep({ deviceId: 'device-a', kind: 'device', target: 'device' });++ expect(deviceId).toBe('device-a');+ });+ });++ it('shares one DB read while UI preparation is still pending', async () => {+ const state = {+ ...mockState,+ messages: [],+ origin: { agentId: 'agent-1', topicId: 'topic-1' },+ };+ mockCoordinator.loadAgentState.mockResolvedValue(state);+ const query = (service as any).messageModel.query.mockResolvedValue([]);+ let resolveUi!: (messages: []) => void;+ const uiRead = vi.spyOn((service as any).messageService, 'prepareUiMessages').mockReturnValue(+ new Promise((resolve) => {+ resolveUi = resolve;+ }),+ );+ const step = vi.fn().mockResolvedValue({+ events: [],+ newState: { ...state, stepCount: 2 },+ nextContext: mockParams.context,+ });+ vi.spyOn(service as any, 'createAgentRuntime').mockResolvedValue({ runtime: { step } });+ const running = service.executeStep(mockParams);+ let startedBeforeUiResolved: boolean;+ try {+ await vi.waitFor(() => expect(uiRead).toHaveBeenCalled());+ startedBeforeUiResolved = query.mock.calls.length > 0;+ expect(step).not.toHaveBeenCalled();+ } finally {+ resolveUi([]);+ await running;+ }+ expect(startedBeforeUiResolved).toBe(true);+ expect(query).toHaveBeenCalledTimes(1);+ });++ it('keeps ephemeral input while preparing the persisted UI snapshot', async () => {+ const messages = [{ role: 'user', content: 'transient prompt' }];+ const state = { ...mockState, messages, origin: { agentId: 'agent', topicId: 'topic' } };+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain('stored answer'),+ );+ const ui = [{ id: 'ui', role: 'assistant', content: 'UI answer' }];+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockResolvedValue(ui);++ const result = await (service as any).queryStepEntryMessages(state);++ expect(state.messages).toBe(messages);+ expect(result.uiMessages).toEqual(ui);+ expect(result.messages).toHaveLength(4);+ });++ it('hydrates the model even when UI preparation fails', async () => {+ const state = { ...mockState, messages: [], origin: { agentId: 'agent', topicId: 'topic' } };+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain('stored answer'),+ );+ vi.spyOn((service as any).messageService, 'prepareUiMessages').mockRejectedValue(+ new Error('UI failed'),+ );+ vi.spyOn(console, 'error').mockImplementation(() => {});++ const result = await (service as any).queryStepEntryMessages(state);++ expect(JSON.stringify(state.messages)).toContain('stored answer');+ expect(result.uiMessages).toBeUndefined();+ expect(result.messages).toHaveLength(4);+ });++ it('should execute step successfully', async () => {+ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'running' },+ nextContext: mockParams.context,+ events: [],+ };++ // Mock runtime.step+ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ const result = await service.executeStep(mockParams);++ expect(result).toEqual({+ success: true,+ state: mockStepResult.newState,+ stepResult: expect.objectContaining(mockStepResult),+ nextStepScheduled: true,+ });++ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {+ type: 'step_start',+ stepIndex: 1,+ data: {},+ });++ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {+ type: 'step_complete',+ stepIndex: 1,+ data: {+ stepIndex: 1,+ nextStepScheduled: false, // Published before nextStepScheduled is updated+ },+ });++ expect(mockCoordinator.saveStepResult).toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.toolResults.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.toolResults.test.tsnew file mode 100644index 00000000000..fe7254e9a4e--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/executeStep.toolResults.test.ts@@ -0,0 +1,322 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { type AgentExecutionParams } from '../../types';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator } = setUpService(AgentRuntimeService, mockUserId));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('executeStep - tool result extraction', () => {+ const mockParams: AgentExecutionParams = {+ operationId: 'test-operation-1',+ stepIndex: 1,+ context: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: false,+ },+ session: {+ sessionId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messageCount: 1,+ },+ },+ };++ const mockState = {+ operationId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messages: [],+ events: [],+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ status: 'running',+ totalCost: 0,+ totalSteps: 1,+ };++ beforeEach(() => {+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ });++ it('should extract tool output from data field for single tool_result', async () => {+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'running' },+ nextContext: {+ phase: 'tool_result',+ payload: {+ data: 'Search found 3 results for "weather"',+ executionTime: 120,+ isSuccess: true,+ toolCall: { identifier: 'lobe-web-browsing', apiName: 'search', id: 'tc-1' },+ toolCallId: 'tc-1',+ },+ session: {+ sessionId: 'test-operation-1',+ status: 'running',+ stepCount: 2,+ messageCount: 2,+ },+ },+ events: [],+ };++ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await service.executeStep(mockParams);++ expect(dispatchSpy).toHaveBeenCalledWith(+ 'test-operation-1',+ 'afterStep',+ expect.objectContaining({+ toolsResult: [+ expect.objectContaining({+ apiName: 'search',+ identifier: 'lobe-web-browsing',+ output: 'Search found 3 results for "weather"',+ }),+ ],+ }),+ undefined,+ );++ dispatchSpy.mockRestore();+ });++ it('should extract tool output from data field for tools_batch_result', async () => {+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'running' },+ nextContext: {+ phase: 'tools_batch_result',+ payload: {+ parentMessageId: 'msg-1',+ toolCount: 2,+ toolResults: [+ {+ data: 'Result from tool A',+ executionTime: 100,+ isSuccess: true,+ toolCall: { identifier: 'builtin', apiName: 'searchA', id: 'tc-1' },+ toolCallId: 'tc-1',+ },+ {+ data: { items: [1, 2, 3] },+ executionTime: 200,+ isSuccess: true,+ toolCall: { identifier: 'lobe-skills', apiName: 'activateSkill', id: 'tc-2' },+ toolCallId: 'tc-2',+ },+ ],+ },+ session: {+ sessionId: 'test-operation-1',+ status: 'running',+ stepCount: 2,+ messageCount: 3,+ },+ },+ events: [],+ };++ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await service.executeStep(mockParams);++ expect(dispatchSpy).toHaveBeenCalledWith(+ 'test-operation-1',+ 'afterStep',+ expect.objectContaining({+ toolsResult: [+ expect.objectContaining({+ apiName: 'searchA',+ identifier: 'builtin',+ output: 'Result from tool A',+ }),+ expect.objectContaining({+ apiName: 'activateSkill',+ identifier: 'lobe-skills',+ output: JSON.stringify({ items: [1, 2, 3] }),+ }),+ ],+ }),+ undefined,+ );++ dispatchSpy.mockRestore();+ });++ it('should handle tool result with undefined data', async () => {+ const dispatchSpy = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined);++ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'running' },+ nextContext: {+ phase: 'tool_result',+ payload: {+ data: undefined,+ toolCall: { identifier: 'builtin', apiName: 'noop', id: 'tc-1' },+ toolCallId: 'tc-1',+ },+ session: {+ sessionId: 'test-operation-1',+ status: 'running',+ stepCount: 2,+ messageCount: 2,+ },+ },+ events: [],+ };++ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await service.executeStep(mockParams);++ expect(dispatchSpy).toHaveBeenCalledWith(+ 'test-operation-1',+ 'afterStep',+ expect.objectContaining({+ toolsResult: [+ expect.objectContaining({+ apiName: 'noop',+ identifier: 'builtin',+ output: undefined,+ }),+ ],+ }),+ undefined,+ );++ dispatchSpy.mockRestore();+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/groupMember.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/groupMember.test.tsnew file mode 100644index 00000000000..e499a57e636--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/groupMember.test.ts@@ -0,0 +1,579 @@+/**+ * @vitest-environment node+ */+import type { MockInstance } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { AgentRuntimeService } from '..';+import { buildPersistedToolChain, setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator } = setUpService(AgentRuntimeService, mockUserId));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('completeGroupActionMember', () => {+ const memberState = {+ messages: [+ { content: 'question', role: 'user' },+ { content: 'final answer', role: 'assistant' },+ ],+ origin: { agentId: 'agent-a' },+ modelRuntimeConfig: { model: 'gpt-test' },+ status: 'done',+ usage: { llm: { tokens: { total: 42 } }, tools: { totalCalls: 2 } },+ };++ let updateToolMessage: ReturnType<typeof vi.fn>;+ let resumeSpy: MockInstance<AgentRuntimeService['tryResumeParentFromAsyncTool']>;++ beforeEach(() => {+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ metadata: { _hooks: [] },+ });+ updateToolMessage = vi.fn().mockResolvedValue({ success: true });+ (service as any).messageModel.updateToolMessage = updateToolMessage;+ resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);+ });++ // G-05 follow-through: a member that inherits manual approval parks on+ // `waiting_for_human`; that is a pause, not an answer, so the supervisor+ // must stay parked until the approval continuation reports back.+ it.each(['in_group', 'isolated'] as const)(+ 'holds the supervisor while a %s member waits for approval',+ async (mode) => {+ const won = await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ finalState: { ...memberState, status: 'waiting_for_human' } as any,+ groupToolMessageId: 'grp-tool-1',+ mode,+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'waiting_for_human',+ });++ expect(won).toBe(false);+ expect(updateToolMessage).not.toHaveBeenCalled();+ expect(resumeSpy).not.toHaveBeenCalled();+ },+ );++ it('single in-group member: backfills a receipt onto the group tool and resumes', async () => {+ const won = await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ finalState: memberState as any,+ groupToolMessageId: 'grp-tool-1',+ mode: 'in_group',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ });++ expect(won).toBe(true);+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({+ content: 'Agent agent-a responded in the group.',+ pluginState: expect.objectContaining({ status: 'completed' }),+ }),+ );+ expect(resumeSpy).toHaveBeenCalledWith(+ { parentOperationId: 'parent-1' },+ { scheduleVerifyOnHold: true },+ );+ });++ it('single isolated member: backfills the final answer', async () => {+ await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ finalState: memberState as any,+ groupToolMessageId: 'grp-tool-1',+ mode: 'isolated',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({ content: 'final answer' }),+ );+ });++ it('single isolated member: extracts the final answer from an assistantGroup', async () => {+ await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ finalState: {+ ...memberState,+ messages: [+ { content: 'question', role: 'user' },+ {+ children: [+ {+ content: '',+ id: 'assistant-tools',+ tools: [+ {+ id: 'tool-call-1',+ result: { content: 'tool result', id: 'tool-result-1' },+ },+ ],+ },+ { content: 'grouped member answer', id: 'assistant-final' },+ ],+ content: '',+ id: 'assistant-group',+ role: 'assistantGroup',+ },+ ],+ } as any,+ groupToolMessageId: 'grp-tool-1',+ mode: 'isolated',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({ content: 'grouped member answer' }),+ );+ });++ it('single isolated member: extracts serialized multimodal text after DB rehydration', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...memberState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain(+ JSON.stringify([+ { text: 'persisted member answer', type: 'text' },+ { image: 'https://example.com/image.png', type: 'image' },+ ]),+ { isMultimodal: true },+ ),+ );++ await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ groupToolMessageId: 'grp-tool-1',+ mode: 'isolated',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({ content: 'persisted member answer' }),+ );+ });++ // Regression: same as completeSubAgentBridge's hetero case — a+ // heterogeneous isolated member never populates the coordinator's+ // runtime state at all, so `loadAgentState` genuinely resolves `null`.+ // Recover the real answer from the member's own isolation thread instead+ // of falling through to the "no textual answer" stub.+ it('single isolated member: recovers the answer from the isolation thread when the coordinator has no state at all (hetero)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain('hello from the CLI'),+ );++ await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ groupToolMessageId: 'grp-tool-1',+ mode: 'isolated',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ threadId: 'thread-1',+ });++ expect((service as any).messageModel.query).toHaveBeenCalledWith(+ { threadId: 'thread-1' },+ { allowShareVisitor: true },+ );+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({ content: 'hello from the CLI' }),+ );+ });++ // Mirrors completeSubAgentBridge's identical Codex-flagged regression:+ // the thread fallback must be gated on `!finalState`, not merely an+ // empty `lastAssistantContent` — a real finalState whose last turn is+ // legitimately textless must keep the stub, not risk a stale earlier+ // reply from the thread's own history.+ it('single isolated member: does not query the thread when a real finalState already says the final turn is textless', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...memberState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain(+ JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),+ { isMultimodal: true },+ ),+ );+ const threadFallbackSpy = vi.spyOn(service as any, 'resolveLastAssistantContentFromThread');++ await service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ groupToolMessageId: 'grp-tool-1',+ mode: 'isolated',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ threadId: 'thread-1',+ });++ expect(threadFallbackSpy).not.toHaveBeenCalled();+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({ content: 'Agent member completed without a textual answer.' }),+ );+ });++ it('multi-member: holds (no group-tool backfill, no resume) until the barrier is met', async () => {+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn() },+ messages: {+ findMany: vi+ .fn()+ .mockResolvedValue([{ content: 'a note', id: 'anchor-0', role: 'tool' }]),+ },+ };+ mockCoordinator.loadAgentState.mockResolvedValue({+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });++ const won = await service.completeGroupActionMember({+ anchorMessageId: 'anchor-0',+ expectedMembers: 2,+ finalState: memberState as any,+ groupToolMessageId: 'grp-tool-1',+ mode: 'in_group',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ });++ expect(won).toBe(false);+ expect(updateToolMessage).toHaveBeenCalledWith('anchor-0', expect.anything());+ expect(updateToolMessage).not.toHaveBeenCalledWith('grp-tool-1', expect.anything());+ expect(resumeSpy).not.toHaveBeenCalled();+ });++ it('multi-member: last completion backfills the group tool and resumes', async () => {+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn() },+ messages: {+ findMany: vi.fn().mockResolvedValue([+ { content: 'a', id: 'anchor-0', role: 'tool' },+ { content: 'b', id: 'anchor-1', role: 'tool' },+ ]),+ },+ };++ const won = await service.completeGroupActionMember({+ anchorMessageId: 'anchor-1',+ expectedMembers: 2,+ finalState: memberState as any,+ groupToolMessageId: 'grp-tool-1',+ mode: 'in_group',+ onComplete: 'resume',+ operationId: 'child-2',+ parentOperationId: 'parent-1',+ reason: 'done',+ });++ expect(won).toBe(true);+ expect(updateToolMessage).toHaveBeenCalledWith('anchor-1', expect.anything());+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'grp-tool-1',+ expect.objectContaining({+ content: 'All 2 agent members completed.',+ pluginState: expect.objectContaining({ status: 'completed' }),+ }),+ );+ expect(resumeSpy).toHaveBeenCalled();+ });++ it('completes a multi-member empty-reason denial and retains it after callback replay', async () => {+ const privateContent = 'synthetic-private-member-answer';+ const defaultReason = 'Blocked by afterToolCall hook.';+ const anchors = [+ { id: 'anchor-0', content: '', state: {} },+ { id: 'anchor-1', content: '', state: {} },+ ];+ const group = { id: 'grp-tool-1', parentId: 'assistant', content: '', state: {} };+ const rows = [...anchors, group];+ (service as any).serverDB.query = {+ messages: { findMany: vi.fn(async () => anchors) },+ messagePlugins: { findFirst: vi.fn().mockResolvedValue({ state: {} }) },+ };+ (service as any).messageModel.findById = vi.fn(async (id) =>+ rows.find((row) => row.id === id),+ );+ (service as any).messageModel.findMessagePlugin = vi.fn(async (id) => ({+ id,+ toolCallId: 'group-call',+ identifier: 'lobe-group-management',+ apiName: 'executeAgentTasks',+ arguments: '{}',+ }));+ updateToolMessage.mockImplementation(async (id, value) => {+ const row = rows.find((row) => row.id === id)!;+ if (row.content && value.onlyIfEmpty) return { success: true, applied: false };+ row.content = value.content;+ row.state = value.pluginState;+ return { success: true, applied: true };+ });+ mockCoordinator.loadAgentState.mockResolvedValue({+ operationId: 'parent-1',+ stepCount: 1,+ status: 'waiting_for_async_tool',+ host: {+ hooks: [+ {+ id: 'after-control',+ type: 'afterToolCall',+ webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },+ },+ ],+ },+ });+ const fetchHook = vi+ .spyOn(globalThis, 'fetch')+ .mockImplementation(+ async () => new Response(JSON.stringify({ decision: 'deny', reason: '' })),+ );+ const complete = (anchorMessageId: string) =>+ service.completeGroupActionMember({+ anchorMessageId,+ expectedMembers: 2,+ finalState: {+ ...memberState,+ messages: [{ role: 'assistant', content: privateContent }],+ } as any,+ groupToolMessageId: group.id,+ mode: 'isolated',+ onComplete: 'resume',+ operationId: `child-${anchorMessageId}`,+ parentOperationId: 'parent-1',+ reason: 'done',+ });+ try {+ expect(await complete('anchor-0')).toBe(false);+ expect(resumeSpy).not.toHaveBeenCalled();+ expect(await complete('anchor-1')).toBe(true);+ expect(resumeSpy).toHaveBeenCalledTimes(1);+ expect(fetchHook).toHaveBeenCalledTimes(3);+ expect(rows.every((row) => row.content === defaultReason)).toBe(true);+ expect(JSON.stringify(rows)).not.toContain(privateContent);++ mockCoordinator.loadAgentState.mockResolvedValue(null);+ await complete('anchor-0');+ expect(fetchHook).toHaveBeenCalledTimes(3);+ expect(rows.every((row) => row.content === defaultReason)).toBe(true);+ expect(JSON.stringify(rows)).not.toContain(privateContent);+ } finally {+ fetchHook.mockRestore();+ }+ });++ it('throws when the anchor backfill fails so the webhook redelivers', async () => {+ updateToolMessage.mockResolvedValue({ success: false });++ await expect(+ service.completeGroupActionMember({+ anchorMessageId: 'grp-tool-1',+ expectedMembers: 1,+ finalState: memberState as any,+ groupToolMessageId: 'grp-tool-1',+ mode: 'in_group',+ onComplete: 'resume',+ operationId: 'child-1',+ parentOperationId: 'parent-1',+ reason: 'done',+ }),+ ).rejects.toThrow(/failed to backfill anchor/);+ expect(resumeSpy).not.toHaveBeenCalled();+ });+ });++ describe('group member timeout watchdog', () => {+ const timeoutParams = {+ anchorMessageId: 'anchor-1',+ expectedMembers: 1,+ groupToolMessageId: 'grp-tool-1',+ memberOperationId: 'member-op-1',+ mode: 'isolated' as const,+ onComplete: 'resume' as const,+ parentOperationId: 'parent-1',+ };++ it('no-ops when the member already reached a terminal state', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({ status: 'done' });+ const interruptSpy = vi.spyOn(service, 'interruptOperation');+ const bridgeSpy = vi.spyOn(service, 'completeGroupActionMember');++ const result = await service.executeStep({+ groupMemberTimeout: timeoutParams,+ operationId: 'member-op-1',+ stepIndex: 0,+ } as any);++ expect(result.success).toBe(true);+ expect(result.nextStepScheduled).toBe(false);+ expect(interruptSpy).not.toHaveBeenCalled();+ expect(bridgeSpy).not.toHaveBeenCalled();+ });++ it('interrupts the member and bridges a timeout when it is still running', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({ status: 'running' });+ const interruptSpy = vi.spyOn(service, 'interruptOperation').mockResolvedValue(true);+ const bridgeSpy = vi.spyOn(service, 'completeGroupActionMember').mockResolvedValue(true);++ const result = await service.executeStep({+ groupMemberTimeout: timeoutParams,+ operationId: 'member-op-1',+ stepIndex: 0,+ } as any);++ expect(interruptSpy).toHaveBeenCalledWith('member-op-1');+ expect(bridgeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ onComplete: 'resume',+ operationId: 'member-op-1',+ parentOperationId: 'parent-1',+ reason: 'timeout',+ }),+ );+ expect(result.nextStepScheduled).toBe(true);+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/interrupt.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/interrupt.test.tsnew file mode 100644index 00000000000..2b93e20615e--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/interrupt.test.ts@@ -0,0 +1,473 @@+/**+ * @vitest-environment node+ */+import type { MockInstance } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentOperationModel } from '@/database/models/agentOperation';++import { hookDispatcher } from '../../hooks';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockDb: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator, mockDb } = setUpService(AgentRuntimeService, mockUserId));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('interruptOperation', () => {+ let findOperation: MockInstance<AgentOperationModel['findById']>;++ beforeEach(() => {+ findOperation = vi.spyOn(AgentOperationModel.prototype, 'findById');+ mockDb.select.mockReturnValue({+ from: vi.fn().mockReturnValue({+ where: vi.fn().mockReturnValue({ limit: vi.fn().mockResolvedValue([]) }),+ }),+ });+ });++ afterEach(() => {+ findOperation.mockRestore();+ });++ it('should interrupt a running operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ operationId: 'op-1',+ status: 'running',+ stepCount: 3,+ lastModified: new Date().toISOString(),+ });++ const result = await service.interruptOperation('op-1');++ expect(result).toBe(true);+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'op-1',+ expect.objectContaining({+ status: 'interrupted',+ lastModified: expect.any(String),+ }),+ );+ expect(mockCoordinator.markInterrupted).toHaveBeenCalledWith('op-1');+ // Sentinel must land before the state save: the step-boundary check+ // reads only the sentinel, so state-first ordering would let a check+ // between the two writes miss the interrupt and clobber it.+ expect(mockCoordinator.markInterrupted.mock.invocationCallOrder[0]).toBeLessThan(+ mockCoordinator.saveAgentState.mock.invocationCallOrder[0],+ );+ });++ it('should interrupt a waiting_for_human operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ operationId: 'op-2',+ status: 'waiting_for_human',+ stepCount: 1,+ });++ const result = await service.interruptOperation('op-2');++ expect(result).toBe(true);+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'op-2',+ expect.objectContaining({ status: 'interrupted' }),+ );+ });++ it('should return false when state and owned operation are not found', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);++ const result = await service.interruptOperation('non-existent');++ expect(result).toBe(false);+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();+ expect(mockCoordinator.markInterrupted).not.toHaveBeenCalled();+ });++ it('should acknowledge cancellation when operation already done', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ operationId: 'op-done',+ status: 'done',+ stepCount: 5,+ });++ const result = await service.interruptOperation('op-done');++ expect(result).toBe(true);+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();+ });++ it('should acknowledge cancellation when operation already in error state', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ operationId: 'op-err',+ status: 'error',+ stepCount: 2,+ });++ const result = await service.interruptOperation('op-err');++ expect(result).toBe(true);+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();+ });++ it('should acknowledge cancellation when operation already interrupted', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ operationId: 'op-int',+ status: 'interrupted',+ stepCount: 4,+ });++ const result = await service.interruptOperation('op-int');++ expect(result).toBe(true);+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();+ });++ it.each(['done', 'error', 'interrupted', 'abandoned'] as const)(+ 'acknowledges an expired runtime state when the owned operation is %s',+ async (status) => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ findOperation.mockResolvedValue({+ id: 'op-expired',+ status,+ } as Awaited<ReturnType<AgentOperationModel['findById']>>);+ expect(await service.interruptOperation('op-expired')).toBe(true);+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();+ expect(mockCoordinator.markInterrupted).not.toHaveBeenCalled();+ },+ );++ it.each(['idle', 'running', 'waiting_for_human', 'waiting_for_async_tool'] as const)(+ 'does not treat missing runtime state as stopped when the owned operation is %s',+ async (status) => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ findOperation.mockResolvedValue({+ id: 'op-active',+ status,+ } as Awaited<ReturnType<AgentOperationModel['findById']>>);+ expect(await service.interruptOperation('op-active')).toBe(false);+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();+ expect(mockCoordinator.markInterrupted).not.toHaveBeenCalled();+ },+ );++ describe('running operation whose runtime state is gone', () => {+ let settleStale: MockInstance<AgentOperationModel['settleStaleRunning']>;++ beforeEach(() => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ settleStale = vi.spyOn(AgentOperationModel.prototype, 'settleStaleRunning');+ });++ afterEach(() => {+ settleStale.mockRestore();+ });++ it('retires a dead operation so the stop is confirmed', async () => {+ const updatedAt = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);+ findOperation.mockResolvedValue({+ id: 'op-dead',+ status: 'running',+ updatedAt,+ } as Awaited<ReturnType<AgentOperationModel['findById']>>);+ settleStale.mockResolvedValue(true);++ expect(await service.interruptOperation('op-dead')).toBe(true);+ expect(settleStale).toHaveBeenCalledWith('op-dead', expect.any(Date));+ const staleBefore = settleStale.mock.calls[0][1];+ expect(staleBefore.getTime()).toBeGreaterThan(updatedAt.getTime());+ expect(staleBefore.getTime()).toBeLessThan(Date.now() - 5 * 60 * 1000);+ });++ it('keeps refusing while the lease is fresh', async () => {+ findOperation.mockResolvedValue({+ id: 'op-live',+ status: 'running',+ updatedAt: new Date(Date.now() - 60 * 1000),+ } as Awaited<ReturnType<AgentOperationModel['findById']>>);++ expect(await service.interruptOperation('op-live')).toBe(false);+ expect(settleStale).not.toHaveBeenCalled();+ });++ it('keeps refusing when a heartbeat wins the retirement race', async () => {+ findOperation.mockResolvedValue({+ id: 'op-race',+ status: 'running',+ updatedAt: new Date(Date.now() - 60 * 60 * 1000),+ } as Awaited<ReturnType<AgentOperationModel['findById']>>);+ settleStale.mockResolvedValue(false);++ expect(await service.interruptOperation('op-race')).toBe(false);+ });+ });+ });++ // Stream events at step / operation boundaries should carry the canonical+ // UIChatMessage[] snapshot so the client can use the pushed payload as+ // Source of Truth instead of refetching from DB.+ describe('queryUiMessages', () => {+ const stubMessageService = (svc: any, queryMessages: ReturnType<typeof vi.fn>) => {+ svc.messageServiceInstance = { queryMessages };+ };++ it('returns messageService.queryMessages result when agentId + topicId are present', async () => {+ const stubMessages = [{ id: 'msg_x', role: 'user' }];+ const queryMessages = vi.fn().mockResolvedValue(stubMessages);+ stubMessageService(service, queryMessages);++ const result = await service.queryUiMessages({+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages).toHaveBeenCalledWith(+ { agentId: 'agt_1', topicId: 'tpc_1' },+ expect.anything(),+ );+ expect(result).toEqual(stubMessages);+ });++ it('assembles a share visitor run snapshot under the visitor share Work scope', async () => {+ // Regression: the visitor's Works are registered under their share scope,+ // which the ordinary scope never resolves. Without it the terminal+ // snapshot carried no Work card, so a sandbox-exported pptx only showed+ // its card after the visitor reloaded the page.+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ principal: {+ actor: { shareVisitor: { shareId: 'share_1', visitorUserId: 'visitor_1' } },+ },+ } as any);++ expect(queryMessages).toHaveBeenCalledWith(+ expect.objectContaining({ includeFileWorks: true, topicId: 'tpc_1' }),+ {+ allowShareVisitor: true,+ workAccessScope: {+ shareId: 'share_1',+ topicId: 'tpc_1',+ type: 'agentShare',+ visitorUserId: 'visitor_1',+ },+ },+ );+ });++ it('keeps the ordinary Work scope and file-Work gate for a non-share run', async () => {+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({ origin: { agentId: 'agt_1', topicId: 'tpc_1' } } as any);++ expect(queryMessages.mock.calls[0][0].includeFileWorks).toBeUndefined();+ expect(queryMessages.mock.calls[0][1]).toEqual({ allowShareVisitor: true });+ });++ it('includes file Works for an ordinary run whose client declared it renders them', async () => {+ // Regression: an ordinary run's terminal snapshot/patch dropped the+ // exported pptx card until the user reloaded the conversation.+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ host: { acceptsFileWorks: true },+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages.mock.calls[0][0].includeFileWorks).toBe(true);+ expect(queryMessages.mock.calls[0][1]).toEqual({ allowShareVisitor: true });+ });++ it.each([undefined, 'visitor_1'])(+ 'includes visitor rows (visitor=%s)',+ async (visitorUserId) => {+ // Regression: `MessageModel.query()` hides share-visitor messages by+ // default. A visitor run executes under the creator's identity, so+ // without the opt-in the terminal snapshot for the visitor's topic is+ // `[]` and the client replaces the conversation it just streamed with+ // nothing.+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ principal: visitorUserId ? { actor: { shareVisitor: { visitorUserId } } } : undefined,+ } as any);++ // The pushed snapshot always carries whole tool payloads now: it only+ // reaches a client that did not ask for protocol 2, which has no way to+ // fetch an omitted payload back.+ expect(queryMessages).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ allowShareVisitor: true }),+ );+ },+ );++ it('scopes the snapshot to the run thread when the operation is a subtopic run', async () => {+ // Regression: without `threadId` the snapshot is the topic's MAIN+ // conversation, and the client writes it into the thread's bucket at+ // step_start / agent_runtime_end — wiping the turn the run just produced,+ // so a freshly created subtopic renders the main conversation instead.+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ origin: { agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' }),+ expect.anything(),+ );+ });++ it('leaves threadId unset for a main-conversation run', async () => {+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages.mock.calls[0][0].threadId).toBeUndefined();+ });++ it('returns undefined when agentId or topicId is missing (skips empty-array push)', async () => {+ const queryMessages = vi.fn();+ stubMessageService(service, queryMessages);++ const noAgent = await service.queryUiMessages({+ origin: { topicId: 'tpc_1' },+ } as any);+ const noTopic = await service.queryUiMessages({+ origin: { agentId: 'agt_1' },+ } as any);+ const noMeta = await service.queryUiMessages({} as any);++ expect(noAgent).toBeUndefined();+ expect(noTopic).toBeUndefined();+ expect(noMeta).toBeUndefined();+ expect(queryMessages).not.toHaveBeenCalled();+ });++ it('returns undefined and never throws when DB query fails (stream events must not fail the step)', async () => {+ const queryMessages = vi.fn().mockRejectedValue(new Error('db down'));+ stubMessageService(service, queryMessages);++ const result = await service.queryUiMessages({+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(result).toBeUndefined();+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/operationQueries.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/operationQueries.test.tsnew file mode 100644index 00000000000..9f389306adf--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/operationQueries.test.ts@@ -0,0 +1,512 @@+/**+ * @vitest-environment node+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { type StartExecutionParams } from '../../types';+import { AgentRuntimeService } from '..';+import { setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockStreamManager: any;+ let mockQueueService: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator, mockStreamManager, mockQueueService } = setUpService(+ AgentRuntimeService,+ mockUserId,+ ));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('getOperationStatus', () => {+ const mockState = {+ operationId: 'test-operation-1',+ status: 'running',+ stepCount: 5,+ messages: [{ content: 'msg1' }, { content: 'msg2' }],+ cost: { total: 0.1 },+ usage: { tokens: 100 },+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ createdAt: new Date(Date.now() - 3600000).toISOString(), // 1 hour ago+ lastActiveAt: new Date(Date.now() - 1800000).toISOString(), // 30 minutes ago+ };++ beforeEach(() => {+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ });++ it('should get operation status successfully', async () => {+ const result = await service.getOperationStatus({+ operationId: 'test-operation-1',+ includeHistory: false,+ });++ expect(result).toEqual({+ operationId: 'test-operation-1',+ currentState: expect.objectContaining({+ status: 'running',+ stepCount: 5,+ cost: { total: 0.1 },+ usage: { tokens: 100 },+ }),+ metadata: mockMetadata,+ isActive: true,+ isCompleted: false,+ hasError: false,+ needsHumanInput: false,+ stats: {+ totalSteps: 5,+ totalMessages: 2,+ totalCost: 0.1,+ uptime: expect.any(Number),+ lastActiveTime: expect.any(Number),+ },+ });+ });++ it('should include history when requested', async () => {+ const mockHistory = [{ stepIndex: 1, timestamp: Date.now() }];+ const mockEvents = [{ type: 'step_start', timestamp: Date.now() }];++ mockCoordinator.getExecutionHistory.mockResolvedValue(mockHistory);+ mockStreamManager.getStreamHistory.mockResolvedValue(mockEvents);++ const result = await service.getOperationStatus({+ operationId: 'test-operation-1',+ includeHistory: true,+ historyLimit: 20,+ });++ expect(result?.executionHistory).toEqual(mockHistory);+ expect(result?.recentEvents).toEqual(mockEvents.slice(0, 10));+ });++ it('should return null for missing operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ mockCoordinator.getOperationMetadata.mockResolvedValue(null);++ const result = await service.getOperationStatus({+ operationId: 'nonexistent-operation',+ });++ expect(result).toBeNull();+ });++ it('should handle different operation statuses', async () => {+ // Test waiting_for_human status+ const waitingState = { ...mockState, status: 'waiting_for_human' };+ mockCoordinator.loadAgentState.mockResolvedValue(waitingState);++ const result = await service.getOperationStatus({+ operationId: 'test-operation-1',+ });++ expect(result?.isActive).toBe(true);+ expect(result?.needsHumanInput).toBe(true);+ });+ });++ describe('getPendingInterventions', () => {+ it('should get pending interventions for specific operation', async () => {+ const mockState = {+ status: 'waiting_for_human',+ pendingToolsCalling: [{ toolName: 'calculator', args: {} }],+ stepCount: 3,+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ modelRuntimeConfig: { model: 'gpt-4' },+ };++ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);++ const result = await service.getPendingInterventions({+ operationId: 'test-operation-1',+ });++ expect(result).toEqual({+ totalCount: 1,+ timestamp: expect.any(String),+ pendingInterventions: [+ {+ operationId: 'test-operation-1',+ type: 'tool_approval',+ status: 'waiting_for_human',+ stepCount: 3,+ lastModified: mockState.lastModified,+ userId: 'user-123',+ modelRuntimeConfig: { model: 'gpt-4' },+ pendingToolsCalling: mockState.pendingToolsCalling,+ },+ ],+ });+ });++ it('should get pending interventions for user', async () => {+ const mockOperations = ['operation-1', 'operation-2'];+ mockCoordinator.getActiveOperations.mockResolvedValue(mockOperations);++ // Mock metadata for filtering by userId+ mockCoordinator.getOperationMetadata+ .mockResolvedValueOnce({ userId: 'user-123' })+ .mockResolvedValueOnce({ userId: 'other-user' });++ // Mock states - only first operation needs intervention+ mockCoordinator.loadAgentState+ .mockResolvedValueOnce({+ status: 'waiting_for_human',+ pendingHumanPrompt: 'Please confirm',+ stepCount: 2,+ lastModified: new Date().toISOString(),+ })+ .mockResolvedValueOnce({+ status: 'running',+ stepCount: 1,+ lastModified: new Date().toISOString(),+ });++ const result = await service.getPendingInterventions({+ userId: 'user-123',+ });++ expect(result.totalCount).toBe(1);+ expect(result.pendingInterventions[0]).toEqual({+ operationId: 'operation-1',+ type: 'human_prompt',+ status: 'waiting_for_human',+ pendingHumanPrompt: 'Please confirm',+ stepCount: 2,+ lastModified: expect.any(String),+ userId: undefined, // getOperationMetadata is not called due to the way operations are filtered+ modelRuntimeConfig: undefined,+ });+ });++ it('should return empty list when no interventions needed', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ status: 'running',+ stepCount: 1,+ });+ mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: 'user-123' });++ const result = await service.getPendingInterventions({+ operationId: 'test-operation-1',+ });++ expect(result).toEqual({+ totalCount: 0,+ timestamp: expect.any(String),+ pendingInterventions: [],+ });+ });+ });++ describe('startExecution', () => {+ const mockParams: StartExecutionParams = {+ operationId: 'test-operation-1',+ context: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: false,+ },+ session: { sessionId: 'test-operation-1', status: 'idle', stepCount: 0, messageCount: 0 },+ },+ priority: 'high',+ delay: 500,+ };++ const mockState = {+ operationId: 'test-operation-1',+ status: 'idle',+ stepCount: 2,+ messages: [{ content: 'msg1' }],+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ };++ beforeEach(() => {+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockQueueService.scheduleMessage.mockResolvedValue('message-456');+ });++ it('should start execution successfully', async () => {+ const result = await service.startExecution(mockParams);++ expect(result).toEqual({+ success: true,+ scheduled: true,+ operationId: 'test-operation-1',+ messageId: 'message-456',+ });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ status: 'running',+ lastModified: expect.any(String),+ }),+ );++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 2,+ context: mockParams.context,+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high',+ delay: 500,+ });+ });++ it('should create default context when none provided', async () => {+ const paramsWithoutContext = { ...mockParams };+ delete paramsWithoutContext.context;++ await service.startExecution(paramsWithoutContext);++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 2,+ context: expect.objectContaining({+ phase: 'user_input',+ payload: expect.objectContaining({+ isFirstMessage: true,+ message: [{ content: '' }], // message is now an array+ }),+ session: expect.objectContaining({+ sessionId: 'test-operation-1',+ status: 'idle',+ stepCount: 2,+ messageCount: 1,+ }),+ }),+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high', // Uses the provided priority from params+ delay: 500, // Uses the provided delay from params+ });+ });++ it('should handle operation not found', async () => {+ mockCoordinator.getOperationMetadata.mockResolvedValue(null);++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 not found',+ );+ });++ it('should handle already running operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...mockState,+ status: 'running',+ });++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 is already running',+ );+ });++ it('should handle completed operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...mockState,+ status: 'done',+ });++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 is already completed',+ );+ });++ it('should handle error state operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...mockState,+ status: 'error',+ });++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 is in error state',+ );+ });++ it('should reject restarting an interrupted operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...mockState,+ status: 'interrupted',+ });++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 is interrupted',+ );+ expect(mockCoordinator.saveAgentState).not.toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });+ });++ describe('processHumanIntervention', () => {+ it('should process human intervention successfully', async () => {+ mockQueueService.scheduleMessage.mockResolvedValue('message-789');++ const result = await service.processHumanIntervention({+ operationId: 'test-operation-1',+ stepIndex: 2,+ action: 'approve',+ approvedToolCall: { toolName: 'calculator', args: {} },+ });++ expect(result).toEqual({+ messageId: 'message-789',+ });++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 2,+ context: undefined,+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high',+ delay: 100,+ payload: {+ approvedToolCall: { toolName: 'calculator', args: {} },+ humanInput: undefined,+ rejectionReason: undefined,+ },+ });+ });++ it('should handle different intervention actions', async () => {+ mockQueueService.scheduleMessage.mockResolvedValue('message-890');++ await service.processHumanIntervention({+ operationId: 'test-operation-1',+ stepIndex: 3,+ action: 'input',+ humanInput: { type: 'text', content: 'user response' },+ });++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ humanInput: { type: 'text', content: 'user response' },+ }),+ }),+ );+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.tsnew file mode 100644index 00000000000..524ac3e5dc4--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/subAgentBridge.test.ts@@ -0,0 +1,702 @@+/**+ * @vitest-environment node+ */+import type { MockInstance } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../../hooks';+import { AgentRuntimeService } from '..';+import { buildPersistedToolChain, setUpService } from './testUtils';++vi.mock('@lobechat/model-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++const { ssrfSafeFetch: mockSsrfSafeFetch } = vi.hoisted(() => ({ ssrfSafeFetch: vi.fn() }));++vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: mockSsrfSafeFetch }));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', (...args) =>+ import('./testUtils').then((m) => (m.libsTrustedClientModule as (...a: any[]) => any)(...args)),+);++// Mock database and models+vi.mock('@/server/services/file', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesFileModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/message', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsMessageModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/database/models/agent', (...args) =>+ import('./testUtils').then((m) => (m.databaseModelsAgentModule as (...a: any[]) => any)(...args)),+);++vi.mock('@/database/models/plugin', (...args) =>+ import('./testUtils').then((m) =>+ (m.databaseModelsPluginModule as (...a: any[]) => any)(...args),+ ),+);++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesModelRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverServicesSearchModule as (...a: any[]) => any)(...args),+ ),+);++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+vi.mock('@/server/modules/AgentRuntime/factory', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeFactoryModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/modules/AgentRuntime/redis', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeRedisModule as (...a: any[]) => any)(...args),+ ),+);++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+vi.mock('@/server/modules/AgentRuntime', (...args) =>+ import('./testUtils').then((m) =>+ (m.serverModulesAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+vi.mock('@lobechat/agent-runtime', (...args) =>+ import('./testUtils').then((m) =>+ (m.lobechatAgentRuntimeModule as (...a: any[]) => any)(...args),+ ),+);++vi.mock('@/server/services/queue', (...args) =>+ import('./testUtils').then((m) => (m.serverServicesQueueModule as (...a: any[]) => any)(...args)),+);++// Mock Mecha module+vi.mock('@/server/modules/Mecha', (...args) =>+ import('./testUtils').then((m) => (m.serverModulesMechaModule as (...a: any[]) => any)(...args)),+);++// Mock model-bank+vi.mock('model-bank', (...args) =>+ import('./testUtils').then((m) => (m.modelBankModule as (...a: any[]) => any)(...args)),+);++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ ({ service, mockCoordinator } = setUpService(AgentRuntimeService, mockUserId));+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ delete process.env.AGENT_RUNTIME_BASE_URL;+ hookDispatcher.unregister('test-operation-1');+ });++ describe('completeSubAgentBridge', () => {+ const bridgeParams = {+ operationId: 'child-op-1',+ parentOperationId: 'parent-op-1',+ reason: 'done',+ threadId: 'thread-1',+ toolMessageId: 'tool-msg-1',+ };++ const childState = {+ messages: [+ { content: 'question', role: 'user' },+ { content: 'final answer', role: 'assistant' },+ ],+ modelRuntimeConfig: { model: 'gpt-test' },+ status: 'done',+ usage: { llm: { tokens: { total: 42 } }, tools: { totalCalls: 2 } },+ };++ let updateToolMessage: ReturnType<typeof vi.fn>;+ let resumeSpy: MockInstance<AgentRuntimeService['tryResumeParentFromAsyncTool']>;++ beforeEach(() => {+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ metadata: { _hooks: [] },+ });+ updateToolMessage = vi.fn().mockResolvedValue({ success: true });+ (service as any).messageModel.updateToolMessage = updateToolMessage;+ resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);+ });++ it('backfills the tool message from finalState and resumes with scheduleVerifyOnHold', async () => {+ const won = await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: childState as any,+ });++ expect(won).toBe(true);+ expect(updateToolMessage).toHaveBeenCalledWith('tool-msg-1', {+ onlyIfEmpty: true,+ content: 'final answer',+ pluginError: null,+ pluginState: {+ model: 'gpt-test',+ status: 'completed',+ threadId: 'thread-1',+ totalToolCalls: 2,+ totalTokens: 42,+ },+ });+ expect(resumeSpy).toHaveBeenCalledWith(+ { parentOperationId: 'parent-op-1' },+ { knownFulfilledMessageId: 'tool-msg-1', scheduleVerifyOnHold: true },+ );+ });++ it.each([+ {+ reason: 'The child result is restricted by policy.',+ expected: 'The child result is restricted by policy.',+ },+ { reason: '', expected: 'Blocked by afterToolCall hook.' },+ ])(+ 'gates deferred output before backfill and parent resume, including callback replay, reason=$reason',+ async ({ reason, expected: denialReason }) => {+ const privateContent = 'synthetic-private-child-answer';+ const stored = {+ id: 'tool-msg-1',+ identifier: 'lobe-agent',+ apiName: 'callSubAgent',+ arguments: '{"instruction":"original"}',+ toolCallId: 'native-child',+ state: {},+ };+ (service as any).messageModel.findMessagePlugin = vi.fn(async () => stored);+ (service as any).messageModel.findById = vi+ .fn()+ .mockResolvedValue({ id: 'tool-msg-1', parentId: 'assistant' });+ const fetchHook = vi+ .spyOn(globalThis, 'fetch')+ .mockImplementation(+ async () => new Response(JSON.stringify({ decision: 'deny', reason })),+ );+ const hooks = [+ {+ id: 'after-control',+ type: 'afterToolCall',+ webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },+ },+ ];+ mockCoordinator.loadAgentState.mockResolvedValue({+ operationId: 'parent-op-1',+ stepCount: 3,+ host: { hooks },+ });+ updateToolMessage.mockImplementation(async (_id, value) => {+ if ((stored as any).content && value.onlyIfEmpty)+ return { success: true, applied: false };+ (stored as any).content = value.content;+ stored.state = value.pluginState;+ (service as any).messageModel.findById.mockResolvedValue({+ id: 'tool-msg-1',+ parentId: 'assistant',+ content: value.content,+ });+ return { success: true };+ });+ try {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: {+ ...childState,+ messages: [{ role: 'assistant', content: privateContent }],+ } as any,+ });+ expect(JSON.parse(String(fetchHook.mock.calls[0][1]?.body))).toMatchObject({+ args: { instruction: 'original' },+ toolCallId: 'native-child',+ result: { content: expect.stringContaining(privateContent) },+ });+ expect(JSON.stringify(updateToolMessage.mock.calls)).not.toContain(privateContent);+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({+ content: denialReason,+ pluginError: 'hook_denied',+ pluginState: expect.objectContaining({+ phase: 'afterToolCall',+ reason: denialReason,+ type: 'blocked',+ }),+ replacePluginState: true,+ onlyIfEmpty: true,+ }),+ );+ expect(resumeSpy).toHaveBeenCalledTimes(1);+ // A duplicate callback cannot restore the raw child answer after configuration removal.+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: {+ ...childState,+ messages: [{ role: 'assistant', content: privateContent }],+ } as any,+ });+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect((stored as any).content).toBe(denialReason);+ expect(stored.state).toMatchObject({ reason: denialReason, type: 'blocked' });+ expect(JSON.stringify(stored.state)).not.toContain(privateContent);+ } finally {+ fetchHook.mockRestore();+ }+ },+ );++ it('ends a callSubAgent result with the sub-agent id so the parent can continue it', async () => {+ (service as any).messageModel.findMessagePlugin = vi+ .fn()+ .mockResolvedValue({ apiName: 'callSubAgent', identifier: 'lobe-agent' });++ await service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any });+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error: { message: 'Budget exceeded' } } as any,+ reason: 'error',+ });++ expect(updateToolMessage).toHaveBeenNthCalledWith(+ 1,+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer\n\n<sub_agent id="thread-1" />' }),+ );+ expect(updateToolMessage).toHaveBeenNthCalledWith(+ 2,+ 'tool-msg-1',+ expect.objectContaining({+ content: expect.stringMatching(+ /^Sub-agent did not complete \(error\): .*\n\n<sub_agent id="thread-1" \/>$/,+ ),+ }),+ );+ });++ it('leaves callAgent results without a sub-agent id', async () => {+ (service as any).messageModel.findMessagePlugin = vi+ .fn()+ .mockResolvedValue({ apiName: 'callAgent', identifier: 'lobe-agent-management' });++ await service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer' }),+ );+ });++ it('loads the child state from the coordinator when finalState is not passed (webhook path)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(childState);++ await service.completeSubAgentBridge(bridgeParams);++ expect(mockCoordinator.loadAgentState).toHaveBeenCalledWith('child-op-1');+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer' }),+ );+ });++ // Regression: a heterogeneous (CLI-driven) child never populates the+ // coordinator's Redis-backed runtime state at all — `loadAgentState`+ // genuinely resolves `null` for it, unlike the standard-runtime case+ // above where it resolves a real (if message-stripped) state object.+ // Without a thread-scoped fallback this always fell through to "Sub-agent+ // completed without a textual answer.", even though the CLI produced a+ // real reply — because the webhook's `eventFields` deliberately excludes+ // `lastAssistantContent` (see `createSubAgentBridgeHook`) and hetero never+ // writes into the coordinator, so nothing else could ever supply it.+ it('recovers the answer from the isolation thread when the coordinator has no state at all (hetero)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain('hello from the CLI'),+ );++ await service.completeSubAgentBridge(bridgeParams);++ expect((service as any).messageModel.query).toHaveBeenCalledWith(+ { threadId: 'thread-1' },+ { allowShareVisitor: true },+ );+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'hello from the CLI' }),+ );+ });++ it('extracts a grouped final answer after webhook state is rehydrated from the DB', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...childState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain('final answer after tool use'),+ );++ await service.completeSubAgentBridge(bridgeParams);++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer after tool use' }),+ );+ });++ it('extracts text from serialized multimodal content after DB query and group parsing', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...childState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain(+ JSON.stringify([+ { text: 'persisted multimodal answer', type: 'text' },+ { image: 'https://example.com/image.png', type: 'image' },+ ]),+ { isMultimodal: true },+ ),+ );++ await service.completeSubAgentBridge(bridgeParams);++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'persisted multimodal answer' }),+ );+ });++ it('uses the no-text fallback for an image-only serialized final assistant', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...childState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain(+ JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),+ { isMultimodal: true },+ ),+ );++ await service.completeSubAgentBridge(bridgeParams);++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),+ );+ });++ // Regression for a Codex review finding on the thread-fallback above: it+ // must be gated on `!finalState` (no authoritative state at all — the+ // heterogeneous case), not merely an empty `lastAssistantContent`.+ // Otherwise a REAL, authoritative finalState whose last turn is+ // legitimately textless would still trigger the thread re-query, and a+ // lagging read that surfaces an EARLIER real reply from the same thread+ // would silently show stale text instead of the correct empty-answer+ // stub.+ it('does not query the thread when a real finalState already says the final turn is textless', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...childState,+ messages: undefined,+ });+ (service as any).messageModel.query.mockResolvedValue(+ buildPersistedToolChain(+ JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),+ { isMultimodal: true },+ ),+ );+ const threadFallbackSpy = vi.spyOn(service as any, 'resolveLastAssistantContentFromThread');++ await service.completeSubAgentBridge(bridgeParams);++ expect(threadFallbackSpy).not.toHaveBeenCalled();+ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),+ );+ });++ it('extracts text parts from the grouped final assistant content', async () => {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: {+ ...childState,+ messages: [+ {+ children: [+ {+ content: [+ { text: 'final answer', type: 'text' },+ { image_url: { url: 'https://example.com/image.png' }, type: 'image_url' },+ ],+ id: 'assistant-final',+ },+ ],+ content: '',+ id: 'assistant-group',+ role: 'assistantGroup',+ },+ ],+ } as any,+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'final answer' }),+ );+ });++ it('does not fall back to stale text when the grouped final assistant is empty', async () => {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: {+ ...childState,+ messages: [+ { content: 'stale answer', id: 'assistant-stale', role: 'assistant' },+ { content: 'follow-up', id: 'user-follow-up', role: 'user' },+ {+ children: [{ content: '', id: 'assistant-final' }],+ content: '',+ id: 'assistant-group',+ role: 'assistantGroup',+ },+ ],+ } as any,+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),+ );+ });++ it('writes an error note + pluginError when the child failed, surfacing the real reason', async () => {+ // The parent agent's LLM only sees `content`; without the inlined reason it+ // gets the opaque generic note and cannot tell why the dispatch failed+ // (issue #16257). The structured error still rides on pluginError.+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error: { message: 'boom' } } as any,+ reason: 'error',+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({+ content: 'Sub-agent did not complete (error): boom',+ pluginError: { message: 'boom' },+ pluginState: expect.objectContaining({ status: 'error' }),+ }),+ );+ });++ it('falls back to the generic note when the failed child has no error detail', async () => {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error: undefined } as any,+ reason: 'error',+ });++ expect(updateToolMessage).toHaveBeenCalledWith(+ 'tool-msg-1',+ expect.objectContaining({+ content: 'Sub-agent did not complete (error).',+ pluginState: expect.objectContaining({ status: 'error' }),+ }),+ );+ });++ // A watchdog-abandoned child's reloaded state has no error; the abandon+ // hand-off passes it explicitly. Without it the parent got a bare "(error).".+ it('explains a watchdog-abandoned child from the hand-off error message', async () => {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ errorMessage: 'Operation abandoned: inactivity_watchdog',+ finalState: { ...childState, error: undefined } as any,+ reason: 'error',+ });++ const call = updateToolMessage.mock.calls.at(-1)?.[1];+ expect(call.content).toBe(+ 'Sub-agent did not complete (error): the sub-agent stopped making progress and the platform ended it (inactivity_watchdog). ' ++ 'Anything it already did (searches, pages read, documents written) is kept in its thread.',+ );+ expect(call.pluginError).toEqual({ message: 'Operation abandoned: inactivity_watchdog' });+ });++ // "Budget exceeded" alone reads like a per-sub-agent allowance, so parents+ // retried or fanned out more sub-agents against the same exhausted limit.+ describe('billing-limit failures', () => {+ const budgetError = (type: string, budgetTypeAtError?: string) => ({+ body: {+ budget: {+ availableCredits: 24_659,+ budgetTypeAtError,+ requiredCredits: 50_638,+ },+ message: 'Budget exceeded',+ },+ message: 'Budget exceeded',+ type,+ });+ const bridgeContent = async (error: unknown) => {+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error } as any,+ reason: 'error',+ });+ return updateToolMessage.mock.calls.at(-1)?.[1];+ };++ it('explains a personal credit shortfall without quoting the balance', async () => {+ const error = budgetError('InsufficientBudgetForModel', 'subscription');+ const call = await bridgeContent(error);++ expect(call.content).toBe(+ 'Sub-agent did not complete (error): stopped by a LobeHub billing limit (InsufficientBudgetForModel): ' ++ "the account's LobeHub credits are too low for this model; the account owner has to top up or upgrade. " ++ 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents on the same model will not get past it; ' ++ 'a sub-agent that runs on a less expensive model may still fit. ' ++ 'Otherwise finish with what you already have and tell the user about the limit.',+ );+ expect(call.content).not.toMatch(/24659|24,659|50638/);+ expect(call.pluginError).toEqual(error);+ });++ it.each([+ [+ 'workspace',+ "the workspace's shared LobeHub credits can't cover this model's estimated cost",+ ],+ [+ 'workspace_member',+ "this member's workspace credit allowance can't cover this model's estimated cost",+ ],+ ])('names the %s allowance as the one to raise', async (scope, expected) => {+ const call = await bridgeContent(budgetError('InsufficientBudgetForModel', scope));++ expect(call.content).toContain(expected);+ expect(call.content).not.toContain('top up');+ });++ it('points plan-limit failures at the plan, not at credits', async () => {+ const call = await bridgeContent(budgetError('SubscriptionPlanLimit', 'subscription'));++ expect(call.content).toContain(+ 'plan limit was reached or the plan does not cover this model',+ );+ });++ // InsufficientBudgetForModel still leaves credits in the allowance, so a+ // cheaper model can fit; only an exhausted plan makes every dispatch futile.+ it('keeps the cheaper-model path open for a model-cost shortfall only', async () => {+ const shortfall = await bridgeContent(+ budgetError('InsufficientBudgetForModel', 'workspace_member'),+ );+ expect(shortfall.content).toContain('on the same model will not get past it');+ expect(shortfall.content).toContain('less expensive model may still fit');++ const exhausted = await bridgeContent(budgetError('FreePlanLimit', 'workspace'));+ expect(exhausted.content).toContain("the workspace's shared LobeHub credits are used up");+ expect(exhausted.content).toContain('more sub-agents will not get past it');+ expect(exhausted.content).not.toContain('less expensive model');+ });+ });++ it('truncates an oversized child error so it cannot bloat the parent context', async () => {+ const huge = 'x'.repeat(500);+ await service.completeSubAgentBridge({+ ...bridgeParams,+ finalState: { ...childState, error: { message: huge } } as any,+ reason: 'error',+ });++ const call = updateToolMessage.mock.calls.at(-1)?.[1];+ expect(call.content).toBe(`Sub-agent did not complete (error): ${'x'.repeat(300)}…`);+ });++ it('throws when the backfill reports success: false so the webhook path redelivers', async () => {+ // updateToolMessage swallows transaction errors into { success: false } —+ // acking 200 here would strand the parent: the barrier stays unsatisfied+ // and QStash never retries an acknowledged delivery.+ updateToolMessage.mockResolvedValue({ success: false });++ await expect(+ service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any }),+ ).rejects.toThrow(/failed to backfill/);+ expect(resumeSpy).not.toHaveBeenCalled();+ });++ it('propagates backfill infrastructure errors for the same redelivery', async () => {+ updateToolMessage.mockRejectedValue(new Error('db down'));++ await expect(+ service.completeSubAgentBridge({ ...bridgeParams, finalState: childState as any }),+ ).rejects.toThrow('db down');+ expect(resumeSpy).not.toHaveBeenCalled();+ });+ });++ describe('resolveAsyncToolOnComplete', () => {+ it('returns finish when ANY pending tool requests finish (not just the first)', async () => {+ // First pending tool resumes; a later one is a group finish action. The+ // disposition must scan all pending tools, not only pending[0].+ (service as any).serverDB.query = {+ messagePlugins: {+ findFirst: vi+ .fn()+ .mockResolvedValueOnce({ state: { status: 'completed' } })+ .mockResolvedValueOnce({ state: { onComplete: 'finish', status: 'completed' } }),+ },+ };++ const result = await (service as any).resolveAsyncToolOnComplete([+ { id: 'tc1' },+ { id: 'tc2' },+ ]);++ expect(result).toBe('finish');+ });++ it('returns resume when no pending tool requests finish', async () => {+ (service as any).serverDB.query = {+ messagePlugins: {+ findFirst: vi.fn().mockResolvedValue({ state: { status: 'completed' } }),+ },+ };++ const result = await (service as any).resolveAsyncToolOnComplete([+ { id: 'tc1' },+ { id: 'tc2' },+ ]);++ expect(result).toBe('resume');+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/testUtils.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/testUtils.tsnew file mode 100644index 00000000000..6779d008a12--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/testUtils.ts@@ -0,0 +1,275 @@+/**+ * Shared fixtures for the AgentRuntimeService scenario tests: the module mock+ * factories (each test file keeps its own `vi.mock` calls and points them+ * here) and the per-test service setup.+ */+import type { UIChatMessage } from '@lobechat/types';+import type * as ModelBankModule from 'model-bank';+import { vi } from 'vitest';++import type { AgentRuntimeService } from '..';++/** The `importOriginal` a `vi.mock` factory receives. */+type ImportOriginal = <T = unknown>() => Promise<T>;++export const lobechatModelRuntimeModule = () => ({+ // RuntimeExecutors (loaded transitively) resolves extend params via this+ // helper; an empty result keeps the runtime payload unchanged.+ applyModelExtendParams: vi.fn(function () {+ return {};+ }),+ getModelPropertyWithFallback: vi.fn(),+ // `llmErrorClassification.ts` reads these at module-load time; an empty+ // spec map is fine here because this suite never exercises the runtime+ // retry classifier path.+ ERROR_CODE_SPECS: {},+ getErrorCodeSpec: () => undefined,+ refineErrorCode: () => undefined,+});++// Mock trusted client to avoid server-side env access+export const libsTrustedClientModule = () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+});++// Mock database and models+export const serverServicesFileModule = () => ({+ FileService: vi.fn().mockImplementation(function () {+ return {+ getFullFileUrl: vi.fn(async (path: string) => `model:${path}`),+ getFileAccessUrl: vi.fn(async (file: { id: string }) => `ui:${file.id}`),+ };+ }),+});++export const databaseModelsMessageModule = () => ({+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ findById: vi.fn().mockResolvedValue(undefined),+ findMessagePlugin: vi.fn().mockResolvedValue(undefined),+ query: vi.fn().mockResolvedValue([]),+ };+ }),+});++export const databaseModelsAgentModule = () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return {+ getAgentConfigById: vi.fn(),+ };+ }),+});++export const databaseModelsPluginModule = () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return {+ query: vi.fn().mockResolvedValue([]),+ };+ }),+});++// Mock ModelRuntime to avoid server-side env access+export const serverModulesModelRuntimeModule = () => ({+ initializeRuntimeOptions: vi.fn(),+ ApiKeyManager: vi.fn().mockImplementation(function () {+ return {+ getApiKey: vi.fn(),+ getAllApiKeys: vi.fn(),+ };+ }),+});++// Mock search service to avoid server-side env access+export const serverServicesSearchModule = () => ({+ SearchService: vi.fn().mockImplementation(function () {+ return {+ search: vi.fn(),+ };+ }),+ searchService: {+ search: vi.fn(),+ },+});++// Mock factory and redis dependencies to break env import chains,+// so the barrel can be imported with real AgentRuntimeCoordinator + InMemory backends+export const serverModulesAgentRuntimeFactoryModule = async () => {+ const { InMemoryAgentStateManager } =+ await import('@/server/modules/AgentRuntime/InMemoryAgentStateManager');+ const { InMemoryStreamEventManager } =+ await import('@/server/modules/AgentRuntime/InMemoryStreamEventManager');+ return {+ createAgentStateManager: () => new InMemoryAgentStateManager(),+ createStreamEventManager: () => new InMemoryStreamEventManager(),+ isRedisAvailable: () => false,+ };+};++export const serverModulesAgentRuntimeRedisModule = () => ({+ createAgentRuntimeRedisClient: vi.fn().mockReturnValue(null),+ getAgentRuntimeRedisClient: vi.fn().mockReturnValue(null),+});++// Use real AgentRuntimeCoordinator with InMemory backends; only mock unrelated exports+export const serverModulesAgentRuntimeModule = async (importOriginal: ImportOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return {+ ...actual,+ createRuntimeExecutors: vi.fn(),+ };+};++// Spread the real module and override only `AgentRuntime` (to stub `.step()`).+// Keeps the real status predicates + package-hosted executors (e.g. `finish`),+// so this mock survives future executor migrations without edits.+export const lobechatAgentRuntimeModule = async (importOriginal: ImportOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ AgentRuntime: vi.fn().mockImplementation(function (_agent, _options) {+ return {+ step: vi.fn(),+ };+ }),+});++export const serverServicesQueueModule = () => ({+ QueueService: vi.fn().mockImplementation(function () {+ return {+ getImpl: vi.fn().mockReturnValue(null),+ scheduleMessage: vi.fn(),+ };+ }),+});++// Mock Mecha module+export const serverModulesMechaModule = () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({+ tools: [],+ enabledToolIds: [],+ filteredTools: [],+ }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([]),+});++// Mock model-bank+export const modelBankModule = async (importOriginal: ImportOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ id: 'gpt-4o-mini',+ providerId: 'openai',+ abilities: {+ functionCall: true,+ vision: true,+ video: false,+ },+ },+ ],+ };+};++export const buildPersistedToolChain = (+ finalContent: string,+ finalMetadata?: Record<string, unknown>,+): UIChatMessage[] => [+ {+ content: 'question',+ createdAt: 1,+ id: 'user-1',+ role: 'user',+ updatedAt: 1,+ },+ {+ content: '',+ createdAt: 2,+ id: 'assistant-tools',+ parentId: 'user-1',+ role: 'assistant',+ tools: [+ {+ apiName: 'command_execution',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'codex',+ result_msg_id: 'tool-result-1',+ type: 'default',+ },+ ],+ updatedAt: 2,+ },+ {+ content: 'tool result',+ createdAt: 3,+ id: 'tool-result-1',+ parentId: 'assistant-tools',+ role: 'tool',+ tool_call_id: 'tool-call-1',+ updatedAt: 3,+ },+ {+ content: finalContent,+ createdAt: 4,+ id: 'assistant-final',+ metadata: finalMetadata,+ parentId: 'tool-result-1',+ role: 'assistant',+ updatedAt: 4,+ },+];++export interface ServiceTestContext {+ mockCoordinator: any;+ mockDb: any;+ mockQueueService: any;+ mockStreamManager: any;+ service: AgentRuntimeService;+}++/**+ * Build a service backed by the in-memory coordinator and stream manager, with+ * every coordinator and stream-manager method spied. Takes the class so this+ * module stays type-only towards it (the mock factories above load first).+ */+export const setUpService = (+ Service: typeof AgentRuntimeService,+ mockUserId: string,+): ServiceTestContext => {+ vi.clearAllMocks();+ process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';++ // Mock database+ const mockDb: any = {+ select: vi.fn(),+ insert: vi.fn(),+ update: vi.fn(),+ delete: vi.fn(),+ };++ const service = new Service(mockDb, mockUserId);++ // Get real instances (backed by InMemory implementations)+ const mockCoordinator = (service as any).coordinator;+ const mockStreamManager = (service as any).streamManager;+ const mockQueueService = (service as any).queueService;++ // Auto-spy all coordinator methods so tests can use .mockResolvedValue() / .toHaveBeenCalledWith()+ for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(mockCoordinator))) {+ if (key !== 'constructor' && typeof mockCoordinator[key] === 'function') {+ vi.spyOn(mockCoordinator, key);+ }+ }+ // Auto-spy all streamManager methods+ for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(mockStreamManager))) {+ if (key !== 'constructor' && typeof mockStreamManager[key] === 'function') {+ vi.spyOn(mockStreamManager, key);+ }+ }++ return { mockCoordinator, mockDb, mockQueueService, mockStreamManager, service };+};diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/asyncTool.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/asyncTool.tsnew file mode 100644index 00000000000..b35730ed7f8--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/asyncTool.ts@@ -0,0 +1,304 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { asyncToolResumeCounter } from '@lobechat/observability-otel/modules/agent-runtime';+import { type ChatToolPayload } from '@lobechat/types';+import debug from 'debug';++import { AgentOperationModel } from '@/database/models/agentOperation';++import { type GroupActionOnComplete } from '../types';+import { ASYNC_TOOL_VERIFY_MAX_ATTEMPTS } from './constants';+import type { AgentRuntimeServiceContext } from './types';+import { asyncToolVerifyDelayMs } from './utils';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type AsyncToolDeps = Pick<+ AgentRuntimeServiceContext,+ | 'allPendingToolsFulfilled'+ | 'baseURL'+ | 'coordinator'+ | 'maybeScheduleAsyncToolVerify'+ | 'messageModel'+ | 'queueService'+ | 'resolveAsyncToolOnComplete'+ | 'serverDB'+ | 'userId'+>;++/**+ * Completion-bridge entry point for async sub-agent tools.+ *+ * Called once per sub-op completion (the bridge already backfilled that+ * sub-op's tool message). Implements the K=N barrier + single-fire resume:+ *+ * 1. The parent must still be parked (`waiting_for_async_tool`).+ * 2. Every tool in this turn's `pendingToolsCalling` must be fulfilled —+ * the true gate, since the LLM can only continue once every tool_result+ * message row is present (covers mixed sub-agent + client-tool batches).+ * 3. Atomically claim the resume via a status CAS; only the winner proceeds.+ * 4. Schedule the parent's next step (`resumeAsyncTool`), which re-enters+ * the LLM with the refreshed tool results.+ *+ * Returns true only for the CAS winner that scheduled the resume.+ *+ * `options.scheduleVerifyOnHold` arms a one-shot delayed re-check+ * (`verifyAsyncToolBarrier`) when the parent is found not yet resumable.+ * Sub-agent completions set it to cover the child finishing before the+ * parent's parked state is persisted, and transient failures around the+ * last completion (a sibling dying between backfill and resume, a DB+ * hiccup during the barrier read). Pure concurrency needs no cover: each+ * completion checks the barrier only after committing its own backfill, so+ * the last committer always sees every earlier one. The re-check itself+ * never re-arms, so retries stay bounded.+ */+export async function tryResumeParentFromAsyncTool(+ deps: AsyncToolDeps,+ params: { parentOperationId: string },+ options?: {+ /**+ * Message id of a tool placeholder the caller just backfilled to a+ * terminal state. Trusted by the barrier as fulfilled without re-reading+ * `message_plugins` — closes the read-your-writes gap where the barrier+ * query hits a read replica that hasn't seen the just-committed write.+ */+ knownFulfilledMessageId?: string;+ /**+ * Group orchestration disposition (skipCallSupervisor / delegate → finish).+ * When omitted, resolved from the parked tool message's pluginState.+ */+ onComplete?: GroupActionOnComplete;+ scheduleVerifyOnHold?: boolean;+ /** 1-based watchdog attempt to arm when the parent isn't resumable yet. */+ verifyAttempt?: number;+ },+): Promise<boolean> {+ const { parentOperationId } = params;++ const state = await deps.coordinator.loadAgentState(parentOperationId);+ if (!state) {+ // State expired (Redis TTL) or never persisted. A missing state at+ // completion time is a classic way a parent silently strands — but it is+ // often transient: a read replica that hasn't seen the park yet, or the+ // child outrunning the parent's park before its snapshot lands. Arm the+ // bounded verify so a later re-check can resume once the state is visible,+ // instead of giving up on the first miss. A genuinely-gone parent just+ // exhausts the attempt cap (verify_exhausted) rather than stranding here.+ log('[%s] async-tool resume: parent state missing/expired, arming verify', parentOperationId);+ asyncToolResumeCounter.add(1, { outcome: 'no_state' });+ await deps.maybeScheduleAsyncToolVerify(parentOperationId, null, options);+ return false;+ }++ if (state.status !== 'waiting_for_async_tool') {+ // Not parked (yet). Either the op already resumed/finished — nothing to+ // do — or the child outran the parent's parking step; the delayed verify+ // re-checks once the park has had time to land.+ await deps.maybeScheduleAsyncToolVerify(parentOperationId, state, options);+ return false;+ }++ const pending = (state.pendingToolsCalling ?? []) as ChatToolPayload[];+ if (pending.length === 0) {+ // Parked but no pending tools recorded — usually the parked snapshot's+ // `pendingToolsCalling` hasn't finished persisting yet. Warn, report, and+ // arm a fallback re-check rather than returning silently (the old bug).+ log(+ '[%s] async-tool resume: parked op has no pending tools, arming fallback',+ parentOperationId,+ );+ asyncToolResumeCounter.add(1, { outcome: 'no_pending' });+ await deps.maybeScheduleAsyncToolVerify(parentOperationId, state, options);+ return false;+ }++ // Barrier: every pending tool must have a fulfilled tool_result message.+ const allFulfilled = await deps.allPendingToolsFulfilled(+ pending,+ options?.knownFulfilledMessageId,+ );+ if (!allFulfilled) {+ log('[%s] async-tool barrier not yet satisfied, holding', parentOperationId);+ asyncToolResumeCounter.add(1, { outcome: 'barrier_held' });+ await deps.maybeScheduleAsyncToolVerify(parentOperationId, state, options);+ return false;+ }++ // Group orchestration's skipCallSupervisor / delegate ends the supervisor+ // op without another LLM turn: the same CAS gate flips the parked op, but+ // the scheduled step finishes it (`finishAfterAsyncTool`) instead of+ // re-entering the LLM (`resumeAsyncTool`). Self-describing so the generic+ // verify watchdog resolves it correctly: the option (if any) wins, else the+ // hint persisted on the parked tool message's pluginState, else resume.+ const onComplete: GroupActionOnComplete =+ options?.onComplete ?? (await deps.resolveAsyncToolOnComplete(pending));++ // Single-fire guard: only one concurrent completion flips the op.+ const won = await new AgentOperationModel(deps.serverDB, deps.userId).tryResumeFromAsyncTool(+ parentOperationId,+ );+ if (!won) {+ log('[%s] lost async-tool resume CAS, no-op', parentOperationId);+ asyncToolResumeCounter.add(1, { outcome: 'lost_cas' });+ return false;+ }++ asyncToolResumeCounter.add(1, { outcome: 'resumed' });++ log(+ '[%s] won async-tool resume CAS, scheduling step %d (onComplete: %s)',+ parentOperationId,+ state.stepCount,+ onComplete,+ );++ if (deps.queueService) {+ await deps.queueService.scheduleMessage({+ context: undefined,+ delay: 100,+ endpoint: `${deps.baseURL}/run`,+ operationId: parentOperationId,+ payload: onComplete === 'finish' ? { finishAfterAsyncTool: true } : { resumeAsyncTool: true },+ priority: 'high',+ stepIndex: state.stepCount,+ });+ } else {+ log('[%s] queue service disabled, skipping async-tool resume schedule', parentOperationId);+ }++ return true;+}++/**+ * Arm the next bounded `verifyAsyncToolBarrier` re-check for a parent op whose+ * resume attempt found it not yet resumable. Skipped for terminal states+ * (nothing left to resume) and when the caller didn't opt in.+ *+ * Unlike the original single shot, the watchdog re-arms after each unsatisfied+ * check: the verify handler re-enters here with `verifyAttempt + 1`, backing+ * off exponentially up to {@link ASYNC_TOOL_VERIFY_MAX_ATTEMPTS}. A transient+ * miss (read-replica lag, a sibling dying between backfill and resume) is thus+ * retried instead of permanently stranding the parent. Once attempts are+ * exhausted the chain stops and the `verify_exhausted` metric fires so the+ * orphan is observable. For details see: async sub-agent suspend/resume stability hardening — bounded watchdog retry with exponential backoff.+ */+export async function maybeScheduleAsyncToolVerify(+ deps: AsyncToolDeps,+ parentOperationId: string,+ state: AgentState | null,+ options?: { scheduleVerifyOnHold?: boolean; verifyAttempt?: number },+): Promise<void> {+ if (!options?.scheduleVerifyOnHold || !deps.queueService) return;++ // `state` is null when the parked snapshot is missing/expired at completion+ // time (no_state). We can't read a status to skip a terminal op, but the+ // bounded attempt cap below keeps a genuinely-gone parent from re-arming+ // forever, so it's safe to retry instead of stranding on a transient miss.+ const status = state?.status as string | undefined;+ if (status === 'done' || status === 'error' || status === 'interrupted') return;++ const attempt = options.verifyAttempt ?? 1;+ if (attempt > ASYNC_TOOL_VERIFY_MAX_ATTEMPTS) {+ // Bounded retries spent and the parent is still not resumable — give up+ // re-arming and report so the stuck wait can be detected, not silently+ // accumulated.+ log(+ '[%s] async-tool barrier verify exhausted after %d attempts, giving up (status: %s)',+ parentOperationId,+ ASYNC_TOOL_VERIFY_MAX_ATTEMPTS,+ status ?? 'missing',+ );+ asyncToolResumeCounter.add(1, { outcome: 'verify_exhausted' });+ return;+ }++ const delay = asyncToolVerifyDelayMs(attempt);+ log(+ '[%s] scheduling async-tool barrier verify attempt %d/%d in %dms (status: %s)',+ parentOperationId,+ attempt,+ ASYNC_TOOL_VERIFY_MAX_ATTEMPTS,+ delay,+ status ?? 'missing',+ );++ try {+ await deps.queueService.scheduleMessage({+ context: undefined,+ delay,+ endpoint: `${deps.baseURL}/run`,+ operationId: parentOperationId,+ payload: { asyncToolVerifyAttempt: attempt, verifyAsyncToolBarrier: true },+ priority: 'high',+ stepIndex: state?.stepCount ?? 0,+ });+ } catch (error) {+ log(+ '[%s] failed to schedule async-tool barrier verify (non-fatal): %O',+ parentOperationId,+ error,+ );+ }+}++/**+ * Whether every pending tool call has a fulfilled tool_result message — i.e.+ * a tool message exists for its `tool_call_id` with non-empty content or a+ * terminal pluginState. Looks up by `tool_call_id` (plugin id === message id).+ *+ * `knownFulfilledMessageId` short-circuits the per-tool content/state read for+ * a placeholder the caller just backfilled in the same request: its terminal+ * write is a local fact, so re-reading it (possibly from a lagging read+ * replica) would only risk a false negative that strands the parent. The+ * plugin row itself predates the park, so the `tool_call_id → plugin.id`+ * lookup still resolves; only the freshly written content/state is trusted.+ */+export async function allPendingToolsFulfilled(+ deps: AsyncToolDeps,+ pending: ChatToolPayload[],+ knownFulfilledMessageId?: string,+): Promise<boolean> {+ for (const tc of pending) {+ const plugin = await deps.serverDB.query.messagePlugins.findFirst({+ where: (mp, { eq }) => eq(mp.toolCallId, tc.id),+ });+ if (!plugin) return false;++ // Trust the caller's own just-committed backfill (read-your-writes).+ if (knownFulfilledMessageId && plugin.id === knownFulfilledMessageId) continue;++ const message = await deps.messageModel.findById(plugin.id);+ const pluginState = plugin.state as { status?: string } | null;+ const fulfilled =+ (!!message?.content && message.content.length > 0) ||+ pluginState?.status === 'completed' ||+ pluginState?.status === 'error';+ if (!fulfilled) return false;+ }+ return true;+}++/**+ * Resolve the resume disposition for a parked op from the disposition hint+ * persisted on its first pending tool message's pluginState. Group+ * orchestration stamps `onComplete: 'finish'` there for skipCallSupervisor /+ * delegate; everything else (sub-agents, client tools) resolves to `resume`.+ * Self-describing so the generic verify watchdog finishes the right ops.+ */+export async function resolveAsyncToolOnComplete(+ deps: AsyncToolDeps,+ pending: ChatToolPayload[],+): Promise<GroupActionOnComplete> {+ // A batched turn can park multiple deferred/client tools. If ANY of them is+ // a group action requesting finish (skipCallSupervisor / delegate), the+ // orchestration must finish — reading only pending[0] would miss a group+ // finish call that isn't the first pending tool and wrongly resume.+ for (const tool of pending) {+ const plugin = await deps.serverDB.query.messagePlugins.findFirst({+ where: (mp, { eq }) => eq(mp.toolCallId, tool.id),+ });+ const pluginState = plugin?.state as { onComplete?: string } | null;+ if (pluginState?.onComplete === 'finish') return 'finish';+ }+ return 'resume';+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/clientLlmWait.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/clientLlmWait.tsnew file mode 100644index 00000000000..cf831afb825--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/clientLlmWait.ts@@ -0,0 +1,528 @@+import type {+ AgentRunClientLlmWait,+ AgentRunLlmExecutor,+ AgentRuntimeContext,+ AgentState,+} from '@lobechat/agent-runtime';+import { type ClientLlmWaitItem, type ResumeClientLlmWaitResult } from '@lobechat/types';+import debug from 'debug';+import pMap from 'p-map';++import type { MessageModel } from '@/database/models/message';+import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';+import {+ buildClientLlmWait,+ buildClientLlmWaitMessageError,+ CLIENT_WAIT_REVERT_RETRY_DELAYS_MS,+ isClientLlmWaitExpiryOf,+ MIN_CLIENT_LLM_WAIT_REMAINING_MS,+} from '@/server/modules/AgentRuntime/llmRelay/clientWait';+import {+ createClientLlmExecutorUnavailableError,+ getClientLlmWaitableReason,+} from '@/server/modules/AgentRuntime/llmRelay/errors';+import { CLIENT_LLM_WAIT_CAPABILITY } from '@/server/modules/AgentRuntime/llmRelay/protocol';++import { CLIENT_WAIT_ROW_WRITE_ATTEMPTS } from './constants';+import type { AgentRuntimeServiceContext } from './types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type ClientLlmWaitDeps = Pick<+ AgentRuntimeServiceContext,+ | 'agentOperationModel'+ | 'baseURL'+ | 'completionLifecycle'+ | 'coordinator'+ | 'endExpiredClientLlmWait'+ | 'expireClientLlmWait'+ | 'finishClientLlmWaitExpiry'+ | 'messageModel'+ | 'queueService'+ | 'restoreClientLlmWait'+ | 'revertClientWaitResumeWithRetry'+ | 'traceRecorder'+ | 'updateAssistantRowWithRetry'+ | 'userId'+>;++/**+ * Park a step that failed because no client could run its LLM call — the+ * provider is reachable only from the user's device and no LobeHub client+ * took the call (a schedule, a bot, a CLI run, every tab closed). The run+ * waits in `waiting_for_client` on the state the step started from, its+ * assistant row says why, and an expiry check is armed. `undefined` when the+ * error is not one a client can fix, or nothing could resume or expire the+ * park (no queue) — the step then fails as before.+ */+export async function parkForClientLlm(+ deps: ClientLlmWaitDeps,+ operationId: string,+ errorState: AgentState,+ context: AgentRuntimeContext | undefined,+ notAfter?: string,+ stepStartState?: AgentState,+): Promise<AgentState | undefined> {+ const reason = getClientLlmWaitableReason(errorState.error);+ if (!reason || !deps.queueService) return;++ // A client that started the run but predates the wait takes the parked+ // call's error as the run's end and settles it locally, while the row+ // stays parked under its topic. Fail the step for it as before.+ const declaredExecutor = errorState.host?.llmExecutor;+ if (declaredExecutor && !declaredExecutor.capabilities?.includes(CLIENT_LLM_WAIT_CAPABILITY)) {+ log("[%s] The run's client cannot wait for a client, failing instead", operationId);+ return;+ }++ const errorBody = (errorState.error as { body?: { provider?: unknown } } | undefined)?.body;+ const provider =+ (typeof errorBody?.provider === 'string' && errorBody.provider) ||+ errorState.modelRuntimeConfig?.provider ||+ 'unknown';++ const topicId = errorState.origin?.topicId;+ let assistantMessage: { id: string; parentId?: string | null } | undefined;+ if (topicId) {+ try {+ const row = await deps.messageModel.findLatestAssistantByOperationId({+ operationId,+ topicId,+ });+ if (row?.id) assistantMessage = { id: row.id, parentId: row.parentId };+ } catch (error) {+ log('[%s] Failed to find the parked call assistant row: %O', operationId, error);+ }+ }++ // A client picks a wait up by subscribing to the run's stream, which needs+ // the run's topic and assistant row. Without them nothing could claim the+ // wait, so fail the step as before instead of parking it.+ if (!topicId || !assistantMessage) {+ log('[%s] No stream anchor to park on, failing instead', operationId);+ return;+ }++ const wait = buildClientLlmWait({ assistantMessage, context, notAfter, provider, reason });+ // A re-park with (almost) nothing left of its wait would arm an expiry that+ // can land before this step commits and be overwritten by it. The wait is+ // over anyway: fail the step with its actionable error instead.+ if (Date.parse(wait.expiresAt) - Date.now() < MIN_CLIENT_LLM_WAIT_REMAINING_MS) {+ log('[%s] Client wait already used up, failing instead', operationId);+ return;+ }+ const parkedState: AgentState = {+ ...errorState,+ // The call never ran, so it does not spend a step: the resume replays it+ // through `runtime.step`, which counts it (and applies the step limit)+ // then. Keeping the incremented count would count it twice and, at the+ // limit, replay it as a forced final answer.+ ...(stepStartState && {+ forceFinish: stepStartState.forceFinish,+ stepCount: stepStartState.stepCount,+ }),+ clientLlmWait: wait,+ error: undefined,+ lastModified: wait.parkedAt,+ status: 'waiting_for_client',+ };++ // Resume, expiry and Stop all key off the durable row, so it must say+ // `waiting_for_client` before anything advertises the wait. If it cannot,+ // fail the step as before rather than park a run nothing could settle.+ try {+ const recorded = await deps.agentOperationModel.recordCompletion(operationId, {+ completionReason: 'waiting_for_client',+ status: 'waiting_for_client',+ });+ if (!recorded) {+ log('[%s] No durable row to park on, failing instead', operationId);+ return;+ }+ } catch (error) {+ log('[%s] Could not record the client wait, failing instead: %O', operationId, error);+ return;+ }++ // The expiry can fire at once (a re-park past its deadline), and it acts+ // only on the park it names: the parked state and the waiting notice must+ // already be in place, or it no-ops — or its terminal error is overwritten+ // by the notice — and the run waits with nothing left to end it.+ try {+ await deps.coordinator.saveAgentState(operationId, parkedState);+ } catch (error) {+ log('[%s] Could not save the parked state, failing instead: %O', operationId, error);+ return;+ }++ // The notice is the only thing a client that cannot run the provider sees+ // (its relay error handler re-reads the server-owned row), so a transient+ // failure is retried rather than left as a silent park.+ await deps.updateAssistantRowWithRetry(operationId, assistantMessage.id, {+ error: buildClientLlmWaitMessageError(wait),+ });++ try {+ await deps.queueService.scheduleMessage({+ context: undefined,+ delay: Math.max(Date.parse(wait.expiresAt) - Date.now(), 0),+ endpoint: `${deps.baseURL}/run`,+ operationId,+ payload: { clientLlmWaitExpired: wait.parkedAt },+ priority: 'normal',+ stepIndex: parkedState.stepCount,+ });+ } catch (error) {+ // Without the expiry the run could wait forever: fail it now instead+ // (the run's error then replaces the waiting notice on its row).+ log('[%s] Could not arm the client wait expiry, failing instead: %O', operationId, error);+ return;+ }++ log(+ '[%s] Parked in waiting_for_client (provider=%s, reason=%s, until %s)',+ operationId,+ provider,+ reason,+ wait.expiresAt,+ );+ return parkedState;+}++/**+ * Continue a run parked in `waiting_for_client` from the step it parked on.+ * The asking client becomes the run's relay executor, so the replayed call+ * is delivered to it. Single-fire: concurrent resumes (an automatic one and+ * a click) race on the durable row and one wins.+ */+export async function resumeFromClientLlmWait(+ deps: ClientLlmWaitDeps,+ params: {+ llmExecutor?: AgentRunLlmExecutor;+ operationId: string;+ },+): Promise<ResumeClientLlmWaitResult> {+ const { llmExecutor, operationId } = params;+ const state = await deps.coordinator.loadAgentState(operationId);+ if (!state || state.status !== 'waiting_for_client') return { resumed: false };+ if (state.origin?.userId && state.origin.userId !== deps.userId) return { resumed: false };++ // Past its deadline the wait is over even if the expiry is still in flight+ // (QStash can deliver late): leave the run to it rather than run the call+ // after the advertised time.+ const expiresAt = Date.parse(state.clientLlmWait?.expiresAt ?? '');+ if (Number.isFinite(expiresAt) && Date.now() >= expiresAt) return { resumed: false };++ const won = await deps.agentOperationModel.tryResumeFromClientWait(operationId);+ if (!won) return { resumed: false };++ const wait = state.clientLlmWait;+ // Past the claim, everything up to the queued step must land, or the run+ // goes back to its wait: a `running` row with nothing queued is one that no+ // resume, expiry or Stop can reach.+ try {+ await deps.coordinator.saveAgentState(operationId, {+ ...state,+ host: { ...state.host, ...(llmExecutor && { llmExecutor }) },+ lastModified: new Date().toISOString(),+ });++ // A Stop that landed after the claim could not settle the `running` row,+ // and the save above may have overwritten its `interrupted` state. It+ // marks the interrupt before saving, so any such Stop shows here; a later+ // one saves after this and the queued step stops on it.+ if (await deps.coordinator.isInterrupted(operationId)) {+ log('[%s] Stopped while being resumed; settling as interrupted', operationId);+ const interruptedState: AgentState = {+ ...state,+ clientLlmWait: undefined,+ lastModified: new Date().toISOString(),+ status: 'interrupted',+ };+ await deps.coordinator.saveAgentState(operationId, interruptedState);+ if (await deps.agentOperationModel.settleRunning(operationId, 'interrupted')) {+ await deps.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');+ }+ return { resumed: false };+ }++ if (wait?.assistantMessageId) {+ try {+ await deps.messageModel.update(wait.assistantMessageId, { error: null });+ } catch (error) {+ log('[%s] Failed to clear the waiting notice: %O', operationId, error);+ }+ }++ await deps.queueService?.scheduleMessage({+ context: undefined,+ delay: 100,+ endpoint: `${deps.baseURL}/run`,+ operationId,+ payload: { resumeClientLlm: true },+ priority: 'high',+ stepIndex: state.stepCount,+ });+ } catch (error) {+ log('[%s] Could not hand the run to a client, staying parked: %O', operationId, error);+ await deps.restoreClientLlmWait(operationId, state);+ throw error;+ }++ log('[%s] Resumed from waiting_for_client at step %d', operationId, state.stepCount);+ return {+ assistantMessageId: wait?.assistantMessageId,+ resumed: true,+ topicId: state.origin?.topicId ?? undefined,+ };+}++/**+ * Put a run whose resume claim could not be completed back into its wait.+ * Other transitions may have raced the claim, so this re-reads the run+ * first. If a Stop moved it on (its settle could not match the claimed+ * `running` row), the row is settled to match instead of re-parked. If it is+ * still this park, the durable row goes back first — it is what resume,+ * expiry and Stop key off — and the expiry is re-armed, because one that+ * fired while the row read `running` gave up. Each step is best-effort so+ * one failure does not skip the rest.+ */+export async function restoreClientLlmWait(+ deps: ClientLlmWaitDeps,+ operationId: string,+ parkedState: AgentState,+) {+ const wait = parkedState.clientLlmWait;+ const current = await deps.coordinator.loadAgentState(operationId).catch(() => null);+ const stillParked =+ current?.status === 'waiting_for_client' && current.clientLlmWait?.parkedAt === wait?.parkedAt;++ if (!stillParked) {+ if (current?.status === 'interrupted') {+ const settled = await deps.agentOperationModel+ .settleRunning(operationId, 'interrupted')+ .catch(() => false);+ if (settled) {+ await deps.completionLifecycle+ .dispatchHooks(operationId, current, 'interrupted')+ .catch((error) => log('[%s] Failed to finish the stop: %O', operationId, error));+ }+ }+ return;+ }++ // The visible wait is only worth restoring once the row is parked again:+ // with the row stuck `running`, no resume, expiry or Stop can reach it, and+ // the abandoned-run watchdog is what settles it.+ if (!(await deps.revertClientWaitResumeWithRetry(operationId))) {+ log('[%s] Could not re-park the durable row; leaving it to the watchdog', operationId);+ return;+ }+ await deps.coordinator+ .saveAgentState(operationId, parkedState)+ .catch((error) => log('[%s] Failed to restore the parked state: %O', operationId, error));+ if (wait?.assistantMessageId) {+ await deps.messageModel+ .update(wait.assistantMessageId, { error: buildClientLlmWaitMessageError(wait) })+ .catch((error) => log('[%s] Failed to restore the waiting notice: %O', operationId, error));+ }+ if (!wait) return;++ // Duplicate expiries are no-ops (they match on `parkedAt` and the row CAS).+ if (Date.now() >= Date.parse(wait.expiresAt)) {+ await deps+ .expireClientLlmWait(operationId, wait.parkedAt)+ .catch((error) => log('[%s] Failed to expire the overdue wait: %O', operationId, error));+ return;+ }+ await deps.queueService+ ?.scheduleMessage({+ context: undefined,+ delay: Math.max(Date.parse(wait.expiresAt) - Date.now(), 0),+ endpoint: `${deps.baseURL}/run`,+ operationId,+ payload: { clientLlmWaitExpired: wait.parkedAt },+ priority: 'normal',+ stepIndex: parkedState.stepCount,+ })+ .catch((error) => log('[%s] Failed to re-arm the wait expiry: %O', operationId, error));+}++/** Put the claimed row back to `waiting_for_client`, riding out a transient DB error. */+export async function revertClientWaitResumeWithRetry(+ deps: ClientLlmWaitDeps,+ operationId: string,+): Promise<boolean> {+ for (const delayMs of CLIENT_WAIT_REVERT_RETRY_DELAYS_MS) {+ if (delayMs) await new Promise((resolve) => setTimeout(resolve, delayMs));+ try {+ // `false` means the row is no longer the claimed `running` one, so it+ // is not ours to put back.+ return await deps.agentOperationModel.revertClientWaitResume(operationId);+ } catch (error) {+ log('[%s] Failed to re-park the durable row: %O', operationId, error);+ }+ }+ return false;+}++/**+ * Runs of this user parked in `waiting_for_client`, with what a client needs+ * to pick one up: the provider it must be able to run, and where the run's+ * conversation lives so it can subscribe to the stream before resuming.+ */+export async function listClientLlmWaits(+ deps: ClientLlmWaitDeps,+ providers?: string[],+): Promise<ClientLlmWaitItem[]> {+ const rows = await deps.agentOperationModel.listWaitingForClient({ providers });+ const items = await pMap(+ rows,+ async (row): Promise<ClientLlmWaitItem | undefined> => {+ const state = await deps.coordinator.loadAgentState(row.id).catch(() => null);+ const wait = state?.clientLlmWait;+ if (state?.status !== 'waiting_for_client' || !wait) return;+ return {+ agentId: state.origin?.agentId ?? undefined,+ assistantMessageId: wait.assistantMessageId,+ expiresAt: wait.expiresAt,+ operationId: row.id,+ provider: wait.provider,+ threadId: state.origin?.threadId ?? undefined,+ topicId: state.origin?.topicId ?? row.topicId ?? undefined,+ };+ },+ { concurrency: 4 },+ );+ return items.filter((item): item is ClientLlmWaitItem => !!item);+}++/**+ * End a `waiting_for_client` park nobody resumed in time. A no-op unless the+ * run is still parked on the very wait that armed this check; the durable+ * row CAS keeps a racing resume from being killed.+ */+export async function expireClientLlmWait(+ deps: ClientLlmWaitDeps,+ operationId: string,+ parkedAt: string,+): Promise<boolean> {+ const state = await deps.coordinator.loadAgentState(operationId);++ // A redelivery after this expiry already ended the run but its lifecycle+ // delivery threw (a critical hook asks QStash to retry): deliver it again,+ // like a retried terminal step does.+ if (state?.status === 'error' && isClientLlmWaitExpiryOf(state, parkedAt)) {+ log('[%s] Redelivering the lifecycle of an expired client wait', operationId);+ await deps.finishClientLlmWaitExpiry(operationId, state);+ return true;+ }++ if (state?.status !== 'waiting_for_client' || state.clientLlmWait?.parkedAt !== parkedAt) {+ return false;+ }++ // Redis still holds this exact park. A row this CAS cannot claim is one a+ // resume took (`running`), unless it is already `error`: then an earlier+ // delivery of this expiry settled it and failed before finishing (resumes,+ // Stop and failing steps all move the Redis state off this park first), so+ // finish it now — QStash retries the delivery that threw.+ const settled = await deps.agentOperationModel.settleClientWait(operationId);+ if (!settled) {+ const row = await deps.agentOperationModel.findById(operationId);+ if (row?.status !== 'error') return false;+ log('[%s] Finishing a client wait expiry that settled but did not finish', operationId);+ }++ await deps.endExpiredClientLlmWait(operationId, state, state.clientLlmWait);++ log('[%s] waiting_for_client expired (parked at %s)', operationId, parkedAt);+ return true;+}++/**+ * The terminal half of an expiry, once the durable row reads `error`: the+ * parked call's row, the Redis state (which ends the stream) and the+ * lifecycle. `state` is the run as it was parked on `wait`.+ */+export async function endExpiredClientLlmWait(+ deps: ClientLlmWaitDeps,+ operationId: string,+ state: AgentState,+ wait: AgentRunClientLlmWait,+) {+ const provider = wait.provider;+ const finalState: AgentState = {+ ...state,+ clientLlmWait: undefined,+ error: formatErrorForState(+ createClientLlmExecutorUnavailableError(provider, 'wait_timeout', {+ waitedSince: wait.parkedAt,+ }),+ ),+ lastModified: new Date().toISOString(),+ status: 'error',+ };++ // The row gets the terminal error first: the save below ends the stream+ // with a `uiMessages` snapshot read from the DB, and an open tab adopts it,+ // so writing it later would leave that tab on the waiting notice. The+ // lifecycle writes the same error again when it finalizes the run.+ // A transient failure is retried here: the lifecycle's later write emits+ // no message patch, so a tab that took the stale snapshot would keep the+ // dead waiting notice until reload.+ const assistantMessageId = wait.assistantMessageId;+ if (assistantMessageId && finalState.error) {+ const message = deps.completionLifecycle.extractErrorMessage(finalState.error);+ const error = { ...finalState.error, body: finalState.error.body ?? { message }, message };+ await deps.updateAssistantRowWithRetry(operationId, assistantMessageId, { error });+ }++ // Ends the stream (`agent_runtime_end`) and finalizes the run like any failure.+ await deps.coordinator.saveAgentState(operationId, finalState);+ await deps.completionLifecycle.emitSignalEvents(operationId, finalState, 'error');+ await deps.finishClientLlmWaitExpiry(operationId, finalState);+}++/**+ * Write a client-wait notice or error onto the assistant row, retrying a+ * transient failure: what a connected tab shows next is read from this row.+ */+export async function updateAssistantRowWithRetry(+ deps: ClientLlmWaitDeps,+ operationId: string,+ messageId: string,+ value: Parameters<MessageModel['update']>[1],+) {+ for (let attempt = 1; attempt <= CLIENT_WAIT_ROW_WRITE_ATTEMPTS; attempt += 1) {+ try {+ await deps.messageModel.update(messageId, value);+ return;+ } catch (error) {+ log('[%s] Failed to write the assistant row (%d): %O', operationId, attempt, error);+ if (attempt < CLIENT_WAIT_ROW_WRITE_ATTEMPTS) {+ await new Promise((resolve) => setTimeout(resolve, 100 * attempt));+ }+ }+ }+}++/** Lifecycle delivery of an expired client wait; safe to repeat on redelivery. */+export async function finishClientLlmWaitExpiry(+ deps: ClientLlmWaitDeps,+ operationId: string,+ finalState: AgentState,+) {+ const provider = (finalState.error as { body?: { provider?: string } } | undefined)?.body+ ?.provider;+ await deps.completionLifecycle.dispatchHooks(operationId, finalState, 'error');+ await deps.traceRecorder.finalize(operationId, {+ completionReason: 'error',+ error: {+ message: `No LobeHub client picked up the ${provider ?? 'local model'} call in time`,+ type: String(finalState.error?.type ?? 'ClientLlmExecutorUnavailable'),+ },+ state: finalState,+ });+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.tsnew file mode 100644index 00000000000..85011799b60--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/constants.ts@@ -0,0 +1,66 @@+/** Tries for a client wait's notice or expiry error on the assistant row. */+export const CLIENT_WAIT_ROW_WRITE_ATTEMPTS = 3;++/**+ * Base delay before the first `verifyAsyncToolBarrier` re-check fires after a+ * sub-agent completion found the parent not yet resumable. Long enough for+ * the parent's parking step to finish persisting, short enough that a lost+ * resume is recovered promptly. Subsequent attempts back off exponentially —+ * see {@link asyncToolVerifyDelayMs}.+ */+export const ASYNC_TOOL_VERIFY_DELAY_MS = 15_000;++/**+ * Maximum number of bounded watchdog re-checks armed per parked parent. The+ * watchdog re-arms after each unsatisfied check (instead of the old single+ * shot) so a transient miss — a read-replica lag, a sibling dying between+ * backfill and resume — is retried rather than leaving the parent stuck in+ * `waiting_for_async_tool` forever. With exponential backoff from a 15s base,+ * 5 attempts span ~15s → ~7.75min total before giving up. For details see: async sub-agent suspend/resume stability hardening — bounded watchdog retry with exponential backoff instead of single-shot verification.+ */+export const ASYNC_TOOL_VERIFY_MAX_ATTEMPTS = 5;++/** Hard ceiling on a single backoff delay so late attempts don't overshoot. */+export const ASYNC_TOOL_VERIFY_MAX_DELAY_MS = 240_000;++export const STEP_LOCK_TTL_SECONDS = 120;+/**+ * How often a live step re-reads its own operation state to notice an+ * interrupt. Interrupts are persisted by a different invocation, so this poll+ * is the only way a running tool learns it should stop.+ */+export const STEP_ABORT_POLL_INTERVAL_MS = 2_000;+/**+ * Temporary compatibility cadence for interrupts written by pre-sentinel+ * workers during a rolling deployment. Remove after every worker writes the+ * sentinel; keeping this much slower than the sentinel poll preserves most of+ * the Redis bandwidth reduction in the meantime.+ */+export const LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS = 30_000;+/** Cap on the exponential backoff multiplier after consecutive poll failures. */+export const STEP_ABORT_POLL_MAX_BACKOFF = 8;+export const STEP_LOCK_HEARTBEAT_MS = 30_000;+export const DURABLE_LEASE_HEARTBEAT_EVERY_TICKS = 3;+/**+ * How long a `running` operation's durable lease may go unrefreshed, with its+ * runtime state gone, before a stop request treats it as dead. Far above the+ * heartbeat cadence (STEP_LOCK_HEARTBEAT_MS × DURABLE_LEASE_HEARTBEAT_EVERY_TICKS).+ */+export const DEAD_OPERATION_LEASE_MS = 10 * 60 * 1000;+export const EVAL_TOOL_FORWARDING_HOOK_ID = 'eval-tool-forwarding';+export const INTERVENTION_LIFECYCLE_CHECKPOINT_KEY = '_agentInterventionLifecycle';++/**+ * How many times a delivery that lost the operation lock re-queues itself+ * before giving up and falling back to a retryable response.+ */+export const STEP_LOCK_RETRY_MAX_ATTEMPTS = 12;+/** Base delay for the first lock-conflict re-delivery. */+export const STEP_LOCK_RETRY_BASE_DELAY_MS = 15_000;+/**+ * Ceiling on a single lock-conflict backoff. Together with the base delay,+ * {@link STEP_LOCK_RETRY_MAX_ATTEMPTS} attempts span ~20 minutes — comfortably+ * longer than the platform's hard step ceiling, so a step that legitimately+ * holds the lock for minutes no longer strands the delivery waiting behind it.+ */+export const STEP_LOCK_RETRY_MAX_DELAY_MS = 120_000;diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.tsnew file mode 100644index 00000000000..9c7aad543f2--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts@@ -0,0 +1,485 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';+import debug from 'debug';++import {+ deriveAgentInterventionQueueDeduplicationId,+ matchesAgentInterventionContinuationProvenance,+} from '@/business/server/agent-run/agentInterventionIdentity';+import { traceStartStage } from '@/server/services/aiAgent/pipeline/sendTracing';++import { isAbortError, throwIfAborted } from '../abort';+import { hookDispatcher, parseSerializedHooks } from '../hooks';+import {+ type GroupActionMemberBridgeParams,+ type OperationCreationParams,+ type OperationCreationResult,+} from '../types';+import type { AgentRuntimeServiceContext } from './types';+import { withoutFrozenModelFacts } from './utils';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type CreateOperationDeps = Pick<+ AgentRuntimeServiceContext,+ | 'acceptsFileWorks'+ | 'agentOperationModel'+ | 'baseURL'+ | 'completionLifecycle'+ | 'coordinator'+ | 'persistInterventionDispatchAck'+ | 'queueService'+ | 'resolveLlmExecutor'+ | 'workspaceId'+>;++/**+ * Create a new Agent operation+ */+export async function createOperation(+ deps: CreateOperationDeps,+ params: OperationCreationParams,+): Promise<OperationCreationResult> {+ const {+ acceptsFileWorks,+ acceptsMemberRuntimeEnd,+ activeDeviceId,+ activeDeviceScope,+ operationId,+ initialContext,+ agentConfig,+ agentGroup,+ agentShareVisitor,+ modelRuntimeConfig,+ operationCredentials,+ userId,+ autoStart = true,+ stream,+ initialMessages = [],+ interventionResolution,+ onInterventionPrepared,+ appContext,+ toolSet,+ hooks,+ userInterventionConfig,+ queueRetries,+ queueRetryDelay,+ searchDecision,+ botContext,+ botPlatformContext,+ deviceAccessPolicy,+ connectorOwnershipNote,+ discordContext,+ evalContext,+ evalRuntime,+ enableExpertise,+ expertise,+ projectInstructions,+ executionPlan,+ maxSteps,+ userMemory,+ deviceSystemInfo,+ disabledPluginIds,+ operationSkillSet,+ parentOperationId,+ signal,+ userTimezone,+ initialStepCount = 0,+ workspaceId,+ } = params;++ // Persist initial agent_operations row. CompletionLifecycle owns both+ // ends of the persistence lifecycle (start row here, terminal update+ // in dispatchHooks) and swallows DB errors so runtime startup is never+ // blocked.+ // A group member's completion bridge lives in the runtime snapshot, which+ // expires (2h). Keep a durable copy on the row so a late approval or a+ // stop can still reach the member's supervisor (`loadGroupMemberBridge`).+ const groupMemberBridge = hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook+ ?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;+ // The Redis state expires independently of pending tools/approvals. Keep+ // caller hook templates on the private operation record, as hetero runs do.+ const durableHooks = parseSerializedHooks(+ (hooks ?? []).flatMap((hook) =>+ hook.webhook+ ? [{ id: hook.id, type: hook.type, matcher: hook.matcher, webhook: hook.webhook }]+ : [],+ ),+ );+ const requiresDurableResultControl = durableHooks.some(+ (hook) => hook.type === 'afterToolCall' && hook.webhook?.responseHandling === 'toolCall',+ );+ const operationStartPersisted = await traceStartStage('record_start', () =>+ deps.completionLifecycle.recordStart({+ agentId: appContext?.agentId ?? null,+ appContext: {+ defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,+ documentId: appContext?.documentId,+ editingAgentId: appContext?.editingAgentId,+ groupId: appContext?.groupId,+ scope: appContext?.scope,+ sessionId: appContext?.sessionId,+ sourceMessageId: appContext?.sourceMessageId,+ },+ chatGroupId: appContext?.groupId ?? null,+ maxSteps,+ metadata: {+ ...(durableHooks.length > 0 && { _hooks: durableHooks }),+ ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),+ ...(interventionResolution+ ? { agentInterventionContinuation: interventionResolution }+ : {}),+ ...(groupMemberBridge ? { groupMemberBridge } : {}),+ },+ model: modelRuntimeConfig?.model,+ modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),+ operationId,+ parentOperationId: parentOperationId ?? null,+ provider: modelRuntimeConfig?.provider,+ taskId: appContext?.taskId ?? null,+ threadId: appContext?.threadId ?? null,+ topicId: appContext?.topicId ?? null,+ trigger: appContext?.trigger,+ }),+ );+ if (requiresDurableResultControl && !operationStartPersisted) {+ throw new Error('Failed to durably persist afterToolCall control policy before dispatch');+ }+ if (interventionResolution && !operationStartPersisted) {+ throw new Error(+ `Failed to durably persist intervention continuation ${operationId} before dispatch`,+ );+ }++ // A member's durable bridge is what a Stop or a late approval falls back+ // to once the runtime snapshot expires; a member without it could strand+ // its supervisor, so fail the start instead.+ if (groupMemberBridge && !operationStartPersisted) {+ throw new Error(`Failed to durably persist group member ${operationId} before dispatch`);+ }++ if (interventionResolution) {+ const durableOperation = await deps.agentOperationModel.findById(operationId);+ const persistedProvenance = durableOperation?.metadata?.agentInterventionContinuation;+ if (+ !durableOperation ||+ !matchesAgentInterventionContinuationProvenance(persistedProvenance, interventionResolution)+ ) {+ throw new Error(`Intervention continuation operation identity conflict: ${operationId}`);+ }+ }++ const operationToolSet = toolSet;+ let operationCreated = false;+ let hooksRegistered = false;++ try {+ throwIfAborted(signal, 'Agent execution aborted before operation startup');++ const memories = userMemory?.memories;+ log(+ '[%s] Creating new operation (autoStart: %s) with params: model=%s, provider=%s, tools=%d, messages=%d, manifests=%d, memory=%s',+ operationId,+ autoStart,+ agentConfig?.model,+ agentConfig?.provider,+ operationToolSet.tools?.length ?? 0,+ initialMessages.length,+ operationToolSet.manifestMap ? Object.keys(operationToolSet.manifestMap).length : 0,+ memories+ ? `{contexts:${memories.contexts?.length ?? 0},experiences:${memories.experiences?.length ?? 0},preferences:${memories.preferences?.length ?? 0},identities:${memories.identities?.length ?? 0},activities:${memories.activities?.length ?? 0},persona:${memories.persona ? 'yes' : 'no'}}`+ : 'none',+ );++ // Initialize operation state - create state before saving+ const activatableToolIds = new Set(operationToolSet.activatableToolIds ?? []);+ const restoredActivatedToolIds = extractActivatedToolIdsFromMessages(initialMessages)?.filter(+ (id) => activatableToolIds.has(id),+ );+ const activatedStepTools = restoredActivatedToolIds?.length+ ? restoredActivatedToolIds.map((id) => ({+ activatedAtStep: initialStepCount,+ id,+ manifest: operationToolSet.manifestMap[id],+ source: 'discovery' as const,+ }))+ : undefined;++ const llmExecutor = await deps.resolveLlmExecutor(params.llmExecutor, parentOperationId);+ // A member's pushes reach the supervisor's client, so it renders what+ // that client declared.+ const fileWorksAccepted =+ acceptsFileWorks ??+ (parentOperationId && appContext?.orchestrationRole === 'member'+ ? await deps.acceptsFileWorks(parentOperationId)+ : undefined);++ const initialState = {+ activatedStepTools,+ createdAt: new Date().toISOString(),+ // Store initialContext for executeSync to use+ initialContext,+ lastModified: new Date().toISOString(),+ // Use the passed initial messages+ messages: initialMessages,+ // Late-bound execution facts. The device may be unrouted here and get+ // bound at a later step boundary (`computeDeviceContext`).+ ...((activeDeviceId || deviceSystemInfo) && {+ binding: {+ device: {+ ...(activeDeviceId && { id: activeDeviceId }),+ ...(deviceSystemInfo && { systemInfo: deviceSystemInfo }),+ },+ },+ }),+ // What the host needs to deliver and retry the run. Hooks are stamped+ // right after creation once the dispatcher has serialized them.+ host: {+ ...(fileWorksAccepted === true && { acceptsFileWorks: true }),+ ...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),+ ...(params.includeFinalState === true && { includeFinalState: true }),+ ...(llmExecutor && { llmExecutor }),+ queue: { retries: queueRetries, retryDelay: queueRetryDelay },+ },+ // Run ledger — everything fixed at creation lives in the typed slots.+ metadata: {},+ // 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,+ editingAgentId: appContext?.editingAgentId,+ editingGroupId: appContext?.editingGroupId,+ 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,+ },+ maxSteps,+ // modelRuntimeConfig at state level for executor fallback+ modelRuntimeConfig,+ // Read once during discovery; dropped again as soon as the run changes+ // its own credentials (see the creds invalidation after a step).+ operationCredentials,+ operationId,+ // The run's only copy of its tool set. The manifest map is the heaviest+ // thing on the state and the state is re-serialized at every step, so the+ // former top-level mirrors (`tools`, `toolManifestMap`, `toolSourceMap`,+ // `toolExecutorMap`) are no longer written; readers go through+ // `selectToolManifestMap` and friends.+ operationToolSet,+ status: 'idle',+ stepCount: initialStepCount,+ // How the run executes — frozen from here on.+ plan: {+ eval: evalRuntime,+ execution: executionPlan,+ skills: operationSkillSet,+ stream,+ workingDirectory: agentConfig?.chatConfig?.runtimeEnv?.workingDirectory,+ },+ // Under whose authority the run acts and what it may do — decided here,+ // re-presented (never re-derived) at each dispatch boundary.+ principal: {+ actor: {+ bot: botContext,+ deviceScope: activeDeviceScope,+ shareVisitor: agentShareVisitor,+ },+ audit: { clientIp: appContext?.clientIp, userAgent: appContext?.userAgent },+ // What the run may do, decided once here: device access and the+ // approval mode its tool calls answer to.+ policy: { deviceAccess: deviceAccessPolicy, userIntervention: userInterventionConfig },+ },+ // Compat mirrors for a rolling deploy: a worker still running the+ // pre-slot build reads only these, and a missing approval mode defaults+ // to `manual` there — which parks a headless run on an approval nobody+ // can give. Drop them (and the matching entries in+ // `normalizeAgentState`'s COMPAT_MIRROR_PATHS) once no pre-slot worker+ // can pick up a step.+ enableExpertise,+ expertise,+ userInterventionConfig,+ // What the model is told about the run's world — frozen from here on;+ // the context engine reads it on every step.+ world: {+ agent: agentConfig,+ ...((botPlatformContext || discordContext) && {+ channel: { botPlatform: botPlatformContext, discord: discordContext },+ }),+ connectorOwnershipNote,+ disabledPluginIds,+ enableExpertise,+ eval: evalContext,+ expertise,+ group: agentGroup,+ projectInstructions,+ searchDecision,+ userMemory,+ userTimezone,+ },+ } as Partial<AgentState>;++ // Use coordinator to create operation, automatically sends initialization event.+ // For an in-group broadcast/speak member, mirror its Gateway stream events+ // onto the supervisor op's channel (parentOperationId) so they flow down the+ // supervisor's existing WebSocket — the client subscribes to one connection,+ // not one per member (single-connection multiplexing).+ const mirrorToOperationId =+ appContext?.orchestrationRole === 'member' ? (parentOperationId ?? undefined) : undefined;+ await traceStartStage('runtime_meta', () =>+ deps.coordinator.createAgentOperation(operationId, {+ acceptsMemberRuntimeEnd,+ agentConfig,+ // Persisted so a queue worker that never ran this op's init still+ // applies the owner-configured visitor redaction policy instead of the+ // fail-closed full strip. See `gatewayVisitorRedaction.ts`.+ visitorRedaction: agentShareVisitor+ ? {+ showErrorDetails: agentShareVisitor.showErrorDetails,+ showModelInfo: agentShareVisitor.showModelInfo,+ }+ : undefined,+ mirrorToOperationId,+ modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),+ // Share-visitor runs execute as the creator (`userId`) but stream only+ // to the visitor — the gateway registers the WS channel under this id.+ streamOwnerUserId: agentShareVisitor?.visitorUserId,+ userId,+ workspaceId: deps.workspaceId,+ }),+ );+ operationCreated = true;++ // Save initial state+ await traceStartStage('save_state', () =>+ deps.coordinator.saveAgentState(operationId, initialState as any),+ );++ // Register external hooks+ hookDispatcher.register(operationId, hooks ?? []);+ hooksRegistered = hookDispatcher.hasHooks(operationId);+ if (hooksRegistered) {+ // Persist webhook configs to state metadata for production mode+ const serializedHooks = hookDispatcher.getSerializedHooks(operationId);+ if (serializedHooks && serializedHooks.length > 0) {+ const currentState = await deps.coordinator.loadAgentState(operationId);+ if (currentState) {+ await deps.coordinator.saveAgentState(operationId, {+ ...currentState,+ host: { ...currentState.host, hooks: serializedHooks },+ });+ }+ }+ }++ if (interventionResolution) {+ const preparedState = await deps.coordinator.loadAgentState(operationId);+ if (!preparedState) {+ throw new Error(`Intervention continuation state disappeared: ${operationId}`);+ }+ const preparation = {+ deduplicationId: deriveAgentInterventionQueueDeduplicationId(operationId, initialStepCount),+ resolutionRequestId: interventionResolution.resolutionRequestId,+ state: 'ready' as const,+ stepIndex: initialStepCount,+ };+ await deps.coordinator.saveAgentState(operationId, {+ ...preparedState,+ metadata: {+ ...preparedState.metadata,+ agentInterventionPreparation: preparation,+ },+ });+ const preparationPersisted =+ await deps.agentOperationModel.recordAgentInterventionPreparation(operationId, preparation);+ if (!preparationPersisted) {+ throw new Error(`Failed to persist intervention continuation preparation: ${operationId}`);+ }+ onInterventionPrepared?.();+ }++ await params.onOperationCreated?.(operationId);++ throwIfAborted(signal, 'Agent execution aborted before first step scheduling');++ let messageId: string | undefined;+ let autoStarted = false;++ if (autoStart && deps.queueService) {+ const deduplicationId = interventionResolution+ ? deriveAgentInterventionQueueDeduplicationId(operationId, initialStepCount)+ : undefined;+ // Both local and queue modes use scheduleMessage+ // LocalQueueServiceImpl uses setTimeout + callback mechanism+ // QStashQueueServiceImpl schedules HTTP requests+ const queueService = deps.queueService;+ messageId = await traceStartStage('schedule_step', () =>+ queueService.scheduleMessage({+ context: initialContext,+ deduplicationId,+ delay: 50, // Short delay for startup+ endpoint: `${deps.baseURL}/run`,+ operationId,+ priority: 'high',+ retryDelay: queueRetryDelay,+ retries: queueRetries,+ stepIndex: initialStepCount,+ }),+ );+ if (interventionResolution && deduplicationId) {+ await deps.persistInterventionDispatchAck({+ deduplicationId,+ messageId,+ operationId,+ resolutionRequestId: interventionResolution.resolutionRequestId,+ });+ }+ autoStarted = true;+ log('[%s] Scheduled first step (messageId: %s)', operationId, messageId);+ }++ if (!autoStarted) {+ log('[%s] Created operation without auto-start', operationId);+ }++ return { autoStarted, messageId, operationId, success: true };+ } catch (error) {+ if (isAbortError(error)) {+ if (hooksRegistered) {+ hookDispatcher.unregister(operationId);+ }++ if (operationCreated) {+ try {+ await deps.coordinator.deleteAgentOperation(operationId);+ } catch (cleanupError) {+ console.error('Failed to cleanup aborted operation %s: %O', operationId, cleanupError);+ }+ }++ log('[%s] Operation creation aborted before scheduling', operationId);+ throw error;+ }++ console.error('Failed to create operation %s: %O', operationId, error);+ throw error;+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.tsnew file mode 100644index 00000000000..67bf4445d73--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/evalToolForwardingHook.ts@@ -0,0 +1,71 @@+import type {+ ToolCallHookEvent,+ ToolForwardingRequest,+ ToolRunResult,+} from '@lobechat/agent-runtime';+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';+import { type EvalToolForwardingConfig } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';++import { type AgentHook } from '../hooks';+import { EVAL_TOOL_FORWARDING_HOOK_ID } from './constants';++export const toToolForwardingFailure = (error?: unknown): ToolRunResult => ({+ content: error === undefined ? 'Tool forwarding failed' : String(error),+ error,+ success: false,+});++export const createEvalToolForwardingHook = (+ toolForwarding: EvalToolForwardingConfig,+ caseId?: string,+): AgentHook => ({+ handler: async (event) => {+ const { apiName, args, callIndex, identifier, mock, operationId, stepIndex } =+ event as unknown as ToolCallHookEvent;+ const target = toolForwarding[identifier];+ if (!target) return;++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), target.timeoutMs ?? 15_000);++ try {+ const payload: ToolForwardingRequest = {+ data: { apiName, args, identifier },+ metadata: { ...(caseId && { caseId }), callIndex, operationId, stepIndex },+ type: 'toolCall',+ };+ const response = await ssrfSafeFetch(target.endpoint, {+ body: JSON.stringify(payload),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ signal: controller.signal,+ });+ if (!response.ok) throw `Tool forwarding server responded with HTTP ${response.status}`;++ const body: unknown = await response.json();+ if (!isRecord(body)) throw new Error('Invalid tool forwarding response');++ if (body.success === true) {+ const result = body.data;+ if (+ isRecord(result) &&+ typeof result.content === 'string' &&+ typeof result.success === 'boolean'+ ) {+ mock({ ...result, content: result.content, success: result.success });+ } else {+ mock({ content: 'No tool result', success: true });+ }+ } else {+ mock(toToolForwardingFailure(body.error));+ }+ } catch (error) {+ mock(toToolForwardingFailure(error));+ } finally {+ clearTimeout(timeout);+ }+ },+ id: EVAL_TOOL_FORWARDING_HOOK_ID,+ type: 'beforeToolCall',+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/abortPoll.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/abortPoll.tsnew file mode 100644index 00000000000..dd250660a96--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/abortPoll.ts@@ -0,0 +1,89 @@+import debug from 'debug';++import {+ LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS,+ STEP_ABORT_POLL_INTERVAL_MS,+ STEP_ABORT_POLL_MAX_BACKOFF,+} from '../constants';+import type { AgentRuntimeServiceContext } from '../types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepAbortPollDeps = Pick<AgentRuntimeServiceContext, 'coordinator'>;++export interface StepAbortPoll {+ signal: AbortSignal;+ /** Stop polling. Called from the step's `finally` on every exit path. */+ stop: () => void;+}++export function startStepAbortPoll(+ deps: StepAbortPollDeps,+ operationId: string,+ stepIndex: number,+): StepAbortPoll {+ // Hoisted so the shared `finally` can stop it on every exit path — an+ // orphaned interval would keep polling Redis for a step that is long gone.+ let stepAbortPoll: ReturnType<typeof setTimeout> | undefined;+ // Clearing the timeout is not enough: a poll already awaiting the state read+ // would schedule the next one after the step is gone, leaking a loop that+ // re-reads the store forever for a finished operation.+ let stepAbortPollStopped = false;++ // Interrupts arrive as a sentinel key beside the persisted state — the+ // request that asked for the stop runs in a different invocation, so+ // there is no in-process controller to share. Poll while the step is alive+ // and cancel locally, otherwise a multi-minute tool would keep running+ // long after the user asked it to stop.+ const stepAbortController = new AbortController();+ // Serialized on purpose: `setInterval` would fire a new read without+ // waiting for the last one, so a slow or failing state store turns every+ // concurrent run into a growing pile of overlapping requests — the load+ // spikes exactly when the store is already struggling. Each read is+ // scheduled only after the previous one settles, and failures back off.+ let abortPollFailures = 0;+ let lastLegacyInterruptStatePollAt = Date.now();+ const pollForAbort = async () => {+ try {+ // Prefer the sentinel. During the first rolling deployment, an old+ // worker can still write only the authoritative state, so sample+ // that large blob at a much lower cadence until all writers have+ // sentinel support.+ let interrupted = await deps.coordinator.isInterrupted(operationId);+ const now = Date.now();+ if (+ !interrupted &&+ now - lastLegacyInterruptStatePollAt >= LEGACY_INTERRUPT_STATE_POLL_INTERVAL_MS+ ) {+ lastLegacyInterruptStatePollAt = now;+ interrupted =+ (await deps.coordinator.loadAgentState(operationId))?.status === 'interrupted';+ }+ abortPollFailures = 0;+ if (interrupted) {+ stepAbortController.abort();+ return;+ }+ } catch (error) {+ abortPollFailures += 1;+ log('[%s][%d] Abort poll failed: %O', operationId, stepIndex, error);+ }++ if (stepAbortPollStopped || stepAbortController.signal.aborted) return;++ stepAbortPoll = setTimeout(+ pollForAbort,+ STEP_ABORT_POLL_INTERVAL_MS * Math.min(2 ** abortPollFailures, STEP_ABORT_POLL_MAX_BACKOFF),+ );+ };+ stepAbortPoll = setTimeout(pollForAbort, STEP_ABORT_POLL_INTERVAL_MS);++ return {+ signal: stepAbortController.signal,+ stop: () => {+ stepAbortPollStopped = true;+ if (stepAbortPoll) clearTimeout(stepAbortPoll);+ },+ };+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.tsnew file mode 100644index 00000000000..8efacab50b7--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/completion.ts@@ -0,0 +1,108 @@+import type { Span } from '@lobechat/observability-otel/api';+import { buildInvokeAgentResultAttributes } from '@lobechat/observability-otel/modules/agent-runtime';+import debug from 'debug';++import { logToolCallPc } from '../../formalObservation';+import type { AgentRuntimeServiceContext } from '../types';+import type { StepRunResult } from './runStep';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepCompletionDeps = Pick<+ AgentRuntimeServiceContext,+ | 'completionLifecycle'+ | 'determineCompletionReason'+ | 'recordInterventionLifecycleCompletion'+ | 'traceRecorder'+ | 'tryResumeParentFromAsyncTool'+>;+/**+ * The run stops here: emit the completion signals, dispatch the completion+ * hooks, record a parked intervention, re-check a just-parked async-tool+ * barrier and finalize the trace.+ */+export async function finishOperation(+ deps: StepCompletionDeps,+ {+ invokeAgentSpan,+ operationId,+ stepIndex,+ stepResult,+ }: {+ invokeAgentSpan: Span;+ operationId: string;+ stepIndex: number;+ stepResult: StepRunResult;+ },+): Promise<void> {+ const reason = deps.determineCompletionReason(stepResult.newState);+ invokeAgentSpan.setAttributes(buildInvokeAgentResultAttributes({ completionReason: reason }));++ // A client park is no completion: the run continues under this id.+ const completionSignalEvents =+ reason === 'waiting_for_client'+ ? []+ : await deps.completionLifecycle.emitSignalEvents(operationId, stepResult.newState, reason);+ logToolCallPc(operationId, stepIndex, 'post.completion_signals', () => ({ reason }));++ // Dispatch completion hooks+ await deps.completionLifecycle.dispatchHooks(operationId, stepResult.newState, reason);+ logToolCallPc(operationId, stepIndex, 'post.completion_hooks', () => ({ reason }));++ if (reason === 'waiting_for_human') {+ await deps.recordInterventionLifecycleCompletion(operationId, stepResult.newState, stepIndex);+ }++ // Park-time self-check: sub-agents are dispatched mid-step, so a+ // fast child can complete BEFORE this op's parked state/row were+ // persisted — its resume attempt then no-ops against the status+ // guard and nothing retries. Now that both the Redis state and the+ // `agent_operations` row (via dispatchHooks → persistCompletion)+ // say `waiting_for_async_tool`, re-run the barrier once to recover+ // any resume that raced the park.+ if (stepResult.newState.status === 'waiting_for_async_tool') {+ try {+ await deps.tryResumeParentFromAsyncTool({ parentOperationId: operationId });+ } catch (selfCheckError) {+ log(+ '[%s][%d] Park-time async-tool self-check failed (non-fatal): %O',+ operationId,+ stepIndex,+ selfCheckError,+ );+ }+ }++ // Finalize tracing snapshot. The error catch below uses the same+ // recorder so propagated failures still write the canonical S3+ // snapshot instead of orphaning the partial ().+ // A client park is no trace boundary: keep the partial so the resumed+ // steps extend the same trajectory and the real end finalizes it whole.+ const newStateError = stepResult.newState.error;+ if (reason === 'waiting_for_client') {+ await deps.traceRecorder.flushPartial();+ } else+ await deps.traceRecorder.finalize(operationId, {+ appendEventsToLastStep: completionSignalEvents,+ completionReason: reason,+ error: newStateError+ ? {+ attribution: newStateError.attribution,+ body: newStateError.body,+ category: newStateError.category,+ countAsFailure: newStateError.countAsFailure,+ httpStatus: newStateError.httpStatus,+ message:+ deps.completionLifecycle.extractErrorMessage(newStateError) ??+ JSON.stringify(newStateError),+ numericId: newStateError.numericId,+ retryable: newStateError.retryable,+ severity: newStateError.severity,+ type: String(newStateError.type ?? newStateError.errorType ?? 'unknown'),+ }+ : undefined,+ state: stepResult.newState,+ });+ logToolCallPc(operationId, stepIndex, 'post.trace_finalized', () => ({ reason }));+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/continuation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/continuation.tsnew file mode 100644index 00000000000..42c7c0ef3d2--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/continuation.ts@@ -0,0 +1,119 @@+import debug from 'debug';++import { logToolCallPc } from '../../formalObservation';+import { type AgentStepContinuation } from '../../types';+import type { AgentRuntimeServiceContext } from '../types';+import type { StepRunResult } from './runStep';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepContinuationDeps = Pick<+ AgentRuntimeServiceContext,+ | 'baseURL'+ | 'calculatePriority'+ | 'calculateStepDelay'+ | 'coordinator'+ | 'queueService'+ | 'streamManager'+ | 'traceRecorder'+>;+/**+ * Hand the next step back to the caller (inline) or queue it. Inlining needs+ * the envelope parked first, so a redelivery can recover the run when this+ * invocation dies mid-step.+ */+export async function scheduleNextStep(+ deps: StepContinuationDeps,+ {+ inlineContinuation,+ operationId,+ stepIndex,+ stepResult,+ }: {+ inlineContinuation: boolean;+ operationId: string;+ stepIndex: number;+ stepResult: StepRunResult;+ },+): Promise<{+ continuation: AgentStepContinuation | undefined;+ handedOffInline: boolean;+ nextStepScheduled: boolean;+}> {+ let continuation: AgentStepContinuation | undefined;+ let handedOffInline = false;+ let nextStepScheduled = false;++ // The caller checks both; repeated here for the type narrowing.+ if (!deps.queueService || !stepResult.nextContext) {+ return { continuation, handedOffInline, nextStepScheduled };+ }++ const nextStepIndex = stepIndex + 1;+ const next: AgentStepContinuation = {+ context: stepResult.nextContext,+ delay: deps.calculateStepDelay(stepResult),+ operationId,+ priority: deps.calculatePriority(stepResult),+ retries:+ typeof stepResult.newState.host?.queue?.retries === 'number'+ ? stepResult.newState.host?.queue?.retries+ : undefined,+ retryDelay:+ typeof stepResult.newState.host?.queue?.retryDelay === 'string'+ ? stepResult.newState.host?.queue?.retryDelay+ : undefined,+ stepIndex: nextStepIndex,+ };++ // Park the envelope before handing it over. The caller is about to run+ // this step in-process with nothing queued behind it; if that+ // invocation dies mid-step, the only way back is for a redelivery to+ // find this envelope — the stale-delivery guard would otherwise ACK+ // the (now older) delivered step and strand the operation.+ //+ // Inlining is therefore conditional on the park succeeding. When it+ // doesn't, fall back to the ordinary queue round-trip: slower by a+ // step boundary, but it keeps the recovery path the queue provides.+ const parked = inlineContinuation+ ? await deps.coordinator.saveInlineResume(operationId, next)+ : false;++ if (!parked && inlineContinuation) {+ log(+ '[%s][%d] Could not park the inline envelope; falling back to the queue',+ operationId,+ stepIndex,+ );+ }++ if (parked) {+ handedOffInline = true;+ // Hand the next step back to the caller instead of paying a full+ // queue round-trip for it. The caller either runs it in this same+ // invocation or publishes it via `scheduleContinuation` when its+ // time budget runs out, so the step is never dropped.+ continuation = next;+ logToolCallPc(operationId, stepIndex, 'post.next_step_inlined', () => ({+ nextStepIndex,+ }));+ log('[%s][%d] Next step %d deferred to caller', operationId, stepIndex, nextStepIndex);+ } else {+ // The next step runs in another invocation, which rebuilds the+ // partial from the store — it has to see this step. The gateway+ // pushes this invocation issued have to land for the same reason:+ // nothing carries them once it stops running.+ await deps.traceRecorder.flushPartial();+ await deps.streamManager.drainPushes?.(operationId);+ await deps.queueService.scheduleMessage({ ...next, endpoint: `${deps.baseURL}/run` });+ nextStepScheduled = true;+ logToolCallPc(operationId, stepIndex, 'post.next_step_scheduled', () => ({+ nextStepIndex,+ }));++ log('[%s][%d] Scheduled next step %d', operationId, stepIndex, nextStepIndex);+ }++ return { continuation, handedOffInline, nextStepScheduled };+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.tsnew file mode 100644index 00000000000..07645c1be11--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/failure.ts@@ -0,0 +1,167 @@+import type { Span } from '@lobechat/observability-otel/api';+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { buildInvokeAgentResultAttributes } from '@lobechat/observability-otel/modules/agent-runtime';+import debug from 'debug';++import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';++import { CriticalAgentInterventionPersistenceError } from '../../CompletionLifecycle';+import { logToolCallPc } from '../../formalObservation';+import type { AgentRuntimeServiceContext } from '../types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepFailureDeps = Pick<+ AgentRuntimeServiceContext,+ 'completionLifecycle' | 'coordinator' | 'streamManager' | 'traceRecorder'+>;+/**+ * A step threw. Record it on the span, persist the error state, settle the+ * completion lifecycle and finalize the trace, then rethrow — except a failed+ * intervention Review publication, which keeps the run parked for the retry.+ */+export async function failStep(+ deps: StepFailureDeps,+ {+ error,+ externalRetryCount,+ invokeAgentSpan,+ operationId,+ stepIndex,+ stepStartAt,+ }: {+ error: unknown;+ externalRetryCount: number;+ invokeAgentSpan: Span;+ operationId: string;+ stepIndex: number;+ stepStartAt: number;+ },+): Promise<never> {+ const isInterventionPersistenceFailure =+ error instanceof CriticalAgentInterventionPersistenceError;+ invokeAgentSpan.recordException(error as Error);+ invokeAgentSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ invokeAgentSpan.setAttributes(+ buildInvokeAgentResultAttributes({+ completionReason: isInterventionPersistenceFailure ? 'waiting_for_human' : 'error',+ }),+ );++ log('Step %d failed for operation %s: %O', stepIndex, operationId, error);++ // The runtime step and its waiting_for_human state are already durable;+ // only the idempotent generic Review publication failed. Turning this+ // infrastructure failure into an agent error would overwrite the parked+ // state/operation row and make the QStash redelivery terminal-short-circuit.+ // Preserve the parked state and propagate non-2xx so the completed-step+ // lifecycle replay above can retry Review persistence without repeating+ // any LLM or tool side effects.+ if (isInterventionPersistenceFailure) {+ log(+ '[%s][%d] Intervention Review persistence failed; keeping operation parked for retry',+ operationId,+ stepIndex,+ );+ throw error;+ }++ const formattedError = formatErrorForState(error);++ // Build error state — try loading current state from coordinator, but if that+ // also fails (e.g. Redis ECONNRESET), fall back to a minimal error state so+ // that completion callbacks and webhooks can still fire.+ let finalStateWithError: any;+ try {+ await deps.streamManager.publishStreamEvent(operationId, {+ data: {+ error: formattedError.message,+ errorType: String(formattedError.type),+ phase: 'step_execution',+ stepIndex,+ },+ stepIndex,+ type: 'error',+ });+ } catch (publishError) {+ log('[%s] Failed to publish error event (infra may be down): %O', operationId, publishError);+ }++ try {+ const errorState = await deps.coordinator.loadAgentState(operationId);+ finalStateWithError = {+ ...errorState!,+ error: formattedError,+ metadata: {+ ...errorState?.metadata,+ externalRetryCount,+ },+ status: 'error' as const,+ stepCount: errorState?.stepCount ?? stepIndex,+ };+ } catch (loadError) {+ log('[%s] Failed to load error state (infra may be down): %O', operationId, loadError);+ // Fallback: construct a minimal error state so callbacks still receive useful info+ finalStateWithError = {+ error: formattedError,+ metadata: { externalRetryCount },+ status: 'error' as const,+ stepCount: stepIndex,+ };+ }++ try {+ await deps.coordinator.saveAgentState(operationId, finalStateWithError);+ } catch (saveError) {+ log('[%s] Failed to save error state (infra may be down): %O', operationId, saveError);+ }++ await deps.completionLifecycle.emitSignalEvents(operationId, finalStateWithError, 'error');+ logToolCallPc(operationId, stepIndex, 'post.completion_signals', () => ({ reason: 'error' }));++ // Dispatch onComplete + onError hooks+ await deps.completionLifecycle.dispatchHooks(operationId, finalStateWithError, 'error');+ logToolCallPc(operationId, stepIndex, 'post.completion_hooks', () => ({ reason: 'error' }));++ // Finalize the partial snapshot into the canonical S3 path so the+ // failed op is observable in the same place as a successful run.+ // Without this, propagated errors (e.g. markPersistFatal from+ // RuntimeExecutors) leave the partial as an orphan at+ // `_partial/<op>.json.zst` and the canonical+ // `agent-traces/<agentId>/<topicId>/<op>.json.zst` returns 404 — see+ // .+ //+ // `failedStep` synthesizes a step record for the failure because the+ // real step never reached `appendStepToPartial` — it threw before the+ // success path could push it. Without this synthetic step, the+ // snapshot's step count would lag the assistant message that+ // triggered the failing call.+ await deps.traceRecorder.finalize(operationId, {+ completionReason: 'error',+ error: {+ attribution: formattedError.attribution,+ body: formattedError.body,+ category: formattedError.category,+ countAsFailure: formattedError.countAsFailure,+ httpStatus: formattedError.httpStatus,+ message: formattedError.message ?? String(formattedError.type),+ numericId: formattedError.numericId,+ retryable: formattedError.retryable,+ severity: formattedError.severity,+ type: String(formattedError.type),+ },+ failedStep: {+ startedAt: stepStartAt,+ stepIndex,+ stepType: formattedError.category === 'provider' ? 'call_llm' : 'call_tool',+ },+ state: finalStateWithError,+ });+ logToolCallPc(operationId, stepIndex, 'post.trace_finalized', () => ({ reason: 'error' }));++ throw error;+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.tsnew file mode 100644index 00000000000..d11bb3ee014--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/guards.ts@@ -0,0 +1,465 @@+import type { AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';++import { type AgentExecutionParams, type AgentExecutionResult } from '../../types';+import { STEP_LOCK_RETRY_MAX_ATTEMPTS } from '../constants';+import type { AgentRuntimeServiceContext } from '../types';+import { stepLockRetryDelayMs } from '../utils';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepGuardsDeps = Pick<+ AgentRuntimeServiceContext,+ | 'agentOperationModel'+ | 'baseURL'+ | 'buildShareAbortResult'+ | 'completionLifecycle'+ | 'coordinator'+ | 'delegate'+ | 'determineCompletionReason'+ | 'expireClientLlmWait'+ | 'handleGroupMemberTimeout'+ | 'queueService'+ | 'recordInterventionLifecycleCompletion'+ | 'shouldReplayPendingInterventionLifecycle'+ | 'traceRecorder'+ | 'tryResumeParentFromAsyncTool'+>;++/**+ * Deliveries that execute nothing and never claim the step lock: a group+ * member's deadline, a client wait's expiry, a terminal durable operation and+ * the async-tool barrier watchdog. Returns the delivery's result, or+ * `undefined` when the step has to run.+ */+export async function runLockFreeDelivery(+ deps: StepGuardsDeps,+ params: AgentExecutionParams,+): Promise<AgentExecutionResult | undefined> {+ const {+ asyncToolVerifyAttempt,+ clientLlmWaitExpired,+ groupMemberTimeout,+ operationId,+ stepIndex,+ verifyAsyncToolBarrier,+ } = params;++ // Group member timeout watchdog: enforce a member's deadline without claiming+ // the step lock. No-op if the member already finished; otherwise interrupt it+ // and bridge a `timeout` completion so the parked supervisor resumes/finishes.+ if (groupMemberTimeout) {+ return deps.handleGroupMemberTimeout(groupMemberTimeout);+ }++ // Expiry check of a `waiting_for_client` park. It executes nothing: the CAS+ // on the durable row decides whether the wait (still parked, same park) ends+ // here or a resume already took the run. Ahead of the terminal-row guard+ // below, because a retried expiry whose first attempt settled the row but+ // failed to finish must still get to finish it.+ if (clientLlmWaitExpired) {+ const expired = await deps.expireClientLlmWait(operationId, clientLlmWaitExpired);+ return {+ nextStepScheduled: false,+ state: expired ? { status: 'error' } : {},+ stepResult: null,+ success: true,+ };+ }++ // Redis keeps the resumable step state, but the durable operation row is+ // the authority for cancellation/recovery. A queued QStash delivery can+ // outlive a crashed process and arrive after Goal recovery has atomically+ // marked that operation interrupted. ACK it without touching the old+ // topic; otherwise the abandoned attempt can finish concurrently with its+ // replacement and submit a second Acceptance run.+ try {+ const durableOperation = await deps.agentOperationModel.findById(operationId);+ if (+ durableOperation &&+ ['done', 'error', 'interrupted', 'abandoned'].includes(durableOperation.status)+ ) {+ log(+ '[%s][%d] Skipping delivery for terminal durable operation (%s)',+ operationId,+ stepIndex,+ durableOperation.status,+ );+ return {+ nextStepScheduled: false,+ state: {+ status: durableOperation.status === 'abandoned' ? 'interrupted' : durableOperation.status,+ },+ stepResult: null,+ success: true,+ };+ }+ } catch (error) {+ // Preserve runtime availability when the durable store has a transient+ // read failure. The step lock and normal persistence path still apply.+ log('[%s][%d] Durable operation status check failed: %O', operationId, stepIndex, error);+ }++ // Watchdog re-check for a parked async-tool wait: re-run the barrier + CAS+ // without claiming the step lock or executing anything. Idempotent — the+ // CAS guarantees at most one real resume regardless of how many checks run.+ // Opt back into `scheduleVerifyOnHold` with the next attempt so an+ // unsatisfied barrier re-arms (bounded backoff) instead of giving up after+ // a single shot — bounded watchdog retry ensures transient misses are recovered.+ if (verifyAsyncToolBarrier) {+ const attempt = asyncToolVerifyAttempt ?? 1;+ log('[%s][%d] Running async-tool barrier verify (attempt %d)', operationId, stepIndex, attempt);+ const resumed = await deps.tryResumeParentFromAsyncTool(+ { parentOperationId: operationId },+ { scheduleVerifyOnHold: true, verifyAttempt: attempt + 1 },+ );+ return {+ nextStepScheduled: resumed,+ state: {},+ stepResult: null,+ success: true,+ };+ }++ return undefined;+}++/**+ * Another delivery holds the step lock. ACK a stale duplicate, ask for a+ * redelivery of a still-locked lifecycle replay, or re-queue this delivery on+ * the bounded lock backoff.+ */+export async function handleStepLockConflict(+ deps: StepGuardsDeps,+ params: AgentExecutionParams,+): Promise<AgentExecutionResult> {+ const {+ approvedToolCall,+ context,+ externalRetryCount = 0,+ finishAfterAsyncTool,+ humanInput,+ lockRetryAttempt = 0,+ operationId,+ rejectAndContinue,+ rejectionReason,+ resumeAsyncTool,+ resumeClientLlm,+ stepIndex,+ toolMessageId,+ } = params;++ // Someone else owns this operation now. Whatever this invocation buffered+ // for the trace belongs to their partial from here — every return below+ // leaves without it, so drop it once, up front, rather than per exit.+ deps.traceRecorder.discardPartial();++ let currentState: AgentState | null | undefined = null;+ try {+ currentState = await deps.coordinator.loadAgentState(operationId);+ } catch (error) {+ log(+ '[%s][%d] Failed to load state while handling step lock conflict: %O',+ operationId,+ stepIndex,+ error,+ );+ }++ const currentStepCount = currentState?.stepCount;+ if (currentState && typeof currentStepCount === 'number' && currentStepCount > stepIndex) {+ if (+ deps.shouldReplayPendingInterventionLifecycle(currentState, stepIndex, externalRetryCount)+ ) {+ // This is a retry of a completed human-approval step whose Review+ // lifecycle did not finish. Do not ACK it while another delivery still+ // owns the step lock: once that owner releases the lock, QStash must+ // redeliver so the lifecycle-only replay below can publish the Review.+ log(+ '[%s][%d] Pending intervention lifecycle retry is still locked; requesting redelivery',+ operationId,+ stepIndex,+ );+ return {+ locked: true,+ nextStepScheduled: false,+ state: currentState,+ success: false,+ };+ }++ log(+ '[%s][%d] Step lock conflict is stale (stepCount=%d), skipping',+ operationId,+ stepIndex,+ currentStepCount,+ );+ return {+ nextStepScheduled: false,+ state: currentState,+ stepResult: null,+ success: true,+ };+ }++ // The lock is held by a live step of this operation, and this delivery is+ // not a stale duplicate — it still has to run once the holder is done.+ //+ // Don't lean on the queue's own retry budget for that wait: the lock is+ // heartbeat-refreshed for as long as the holding step runs (unbounded),+ // while the budget is a handful of fixed-delay retries. A step that runs+ // longer than the budget therefore exhausts it and the delivery is+ // dead-lettered — the step it carried is then never executed. Re-queue a+ // fresh delivery on our own bounded backoff instead, and ACK this one.+ //+ // The re-delivery has to carry this delivery's own resume/intervention+ // payload: a human-intervention resume (`processHumanIntervention`) or an+ // async-tool resume (`tryResumeParentFromAsyncTool`) can lose the lock+ // race too, and re-queueing only the retry counter would run a plain step+ // once the lock clears — silently dropping the approval / human input, or+ // leaving a parked operation parked forever. Undefined fields drop out of+ // the JSON body, so unrelated deliveries still send just the counter.+ const nextLockRetryAttempt = lockRetryAttempt + 1;+ if (deps.queueService && nextLockRetryAttempt <= STEP_LOCK_RETRY_MAX_ATTEMPTS) {+ const delay = stepLockRetryDelayMs(nextLockRetryAttempt);+ log(+ '[%s][%d] Step lock conflict — re-queueing attempt %d/%d in %dms',+ operationId,+ stepIndex,+ nextLockRetryAttempt,+ STEP_LOCK_RETRY_MAX_ATTEMPTS,+ delay,+ );++ try {+ await deps.queueService.scheduleMessage({+ context,+ delay,+ endpoint: `${deps.baseURL}/run`,+ operationId,+ payload: {+ approvedToolCall,+ finishAfterAsyncTool,+ humanInput,+ lockRetryAttempt: nextLockRetryAttempt,+ rejectAndContinue,+ rejectionReason,+ resumeAsyncTool,+ resumeClientLlm,+ toolMessageId,+ },+ priority: 'high',+ retryDelay:+ typeof currentState?.host?.queue?.retryDelay === 'string'+ ? currentState.host?.queue?.retryDelay+ : undefined,+ retries:+ typeof currentState?.host?.queue?.retries === 'number'+ ? currentState.host?.queue?.retries+ : undefined,+ stepIndex,+ });++ return {+ locked: true,+ lockRescheduled: true,+ nextStepScheduled: true,+ state: {},+ success: true,+ };+ } catch (error) {+ // Fall through to the retryable response so the delivery isn't lost.+ log(+ '[%s][%d] Failed to re-queue after step lock conflict: %O',+ operationId,+ stepIndex,+ error,+ );+ }+ }++ log(+ '[%s][%d] Step lock conflict — another instance is executing this step, returning locked',+ operationId,+ stepIndex,+ );+ return {+ locked: true,+ nextStepScheduled: false,+ state: {},+ success: false,+ };+}++/**+ * Replay only the completion lifecycle of a parked approval step whose Review+ * publication failed. Returns the step's result when it replayed.+ */+export async function replayPendingInterventionLifecycle(+ deps: StepGuardsDeps,+ {+ agentState,+ externalRetryCount,+ operationId,+ stepIndex,+ }: {+ agentState: AgentState;+ externalRetryCount: number;+ operationId: string;+ stepIndex: number;+ },+): Promise<AgentExecutionResult | undefined> {+ // A parked approval step is already durable before its generic Review+ // is published. When that final Review write fails, the request returns+ // non-2xx and QStash retries this SAME step with `upstash-retried > 0`.+ // The runtime state now has stepCount > stepIndex, so the ordinary stale+ // delivery guard below would ACK it and permanently strand the Review.+ // Replay only the idempotent completion lifecycle: never run beforeStep,+ // runtime.step (LLM/tools), afterStep, or saveStepResult again.+ if (+ agentState.stepCount > stepIndex &&+ deps.shouldReplayPendingInterventionLifecycle(agentState, stepIndex, externalRetryCount)+ ) {+ agentState.metadata = {+ ...agentState.metadata,+ externalRetryCount,+ };++ const reason = 'waiting_for_human' as const;+ const completionSignalEvents = await deps.completionLifecycle.emitSignalEvents(+ operationId,+ agentState,+ reason,+ );+ await deps.completionLifecycle.dispatchHooks(operationId, agentState, reason);+ await deps.recordInterventionLifecycleCompletion(operationId, agentState, stepIndex);+ await deps.traceRecorder.finalize(operationId, {+ appendEventsToLastStep: completionSignalEvents,+ completionReason: reason,+ state: agentState,+ });++ log('[%s][%d] Replayed pending intervention lifecycle', operationId, stepIndex);+ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };+ }++ return undefined;+}++/**+ * A loaded step that must not run: already completed, already terminal,+ * parked for a client, or a shared run whose authorization was revoked.+ * Returns the step's result, or `undefined` when the step runs.+ */+export async function skipUnrunnableStep(+ deps: StepGuardsDeps,+ {+ agentState,+ operationId,+ resumeClientLlm,+ stepIndex,+ }: {+ agentState: AgentState;+ operationId: string;+ resumeClientLlm: AgentExecutionParams['resumeClientLlm'];+ stepIndex: number;+ },+): Promise<AgentExecutionResult | undefined> {+ // Layer 2 defense: catch extremely delayed retries that arrive after lock TTL expired+ if (agentState.stepCount > stepIndex) {+ log(+ '[%s][%d] Step already completed (stepCount=%d), skipping',+ operationId,+ stepIndex,+ agentState.stepCount,+ );+ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };+ }++ // Early exit: skip step if operation is already in a terminal state+ // This prevents executing expensive LLM/tool calls after timeout or interruption+ if (+ agentState.status === 'interrupted' ||+ agentState.status === 'done' ||+ agentState.status === 'error'+ ) {+ log(+ '[%s][%d] Skipping step — operation already in terminal state: %s',+ operationId,+ stepIndex,+ agentState.status,+ );++ const reason = deps.determineCompletionReason(agentState);++ await deps.completionLifecycle.emitSignalEvents(operationId, agentState, reason);++ // Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize+ await deps.completionLifecycle.dispatchHooks(operationId, agentState, reason);++ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };+ }++ // A run parked for a client moves only through its own resume: any other+ // delivery (a duplicate, a stale redrive) would replay the call with no+ // client to take it.+ if (agentState.status === 'waiting_for_client' && !resumeClientLlm) {+ log('[%s][%d] Skipping step — operation is waiting for a client', operationId, stepIndex);+ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };+ }++ // Agent Share: re-prove this visitor run's authorization on EVERY step.+ // A revocation only flips the `agent_shares` row — nothing tears down+ // an operation that was already created, so without this the run keeps+ // going under the creator's credentials/budget for the rest of its+ // (potentially very long) lifetime, and the visitor's own Stop button+ // has already stopped working (it re-resolves the now-private share and+ // gets FORBIDDEN). Re-checking here means a revocation cannot survive a+ // step boundary. See `AgentShareModel.isRunStillAuthorized`'s JSDoc for+ // why one query covers every revocation path (visibility flip — which+ // is what turning sharing off does — share delete, agent delete).+ if (deps.delegate.verifyShareRunStillAuthorized) {+ const shareMarker = agentState.principal?.actor?.shareVisitor as+ { agentId?: string; shareId?: string } | undefined;+ if (shareMarker?.agentId && shareMarker.shareId) {+ let stillAuthorized = false;+ try {+ stillAuthorized = await deps.delegate.verifyShareRunStillAuthorized({+ agentId: shareMarker.agentId,+ shareId: shareMarker.shareId,+ });+ } catch (error) {+ // Fail closed: a read failure must not be read as "still+ // authorized". Falls through to the abort below with+ // `stillAuthorized` left `false`.+ log('[%s][%d] Share run authorization re-check failed: %O', operationId, stepIndex, error);+ }+ if (!stillAuthorized) {+ return deps.buildShareAbortResult(operationId, agentState);+ }+ }+ }++ return undefined;+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.tsnew file mode 100644index 00000000000..7b2d383f407--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts@@ -0,0 +1,242 @@+import type { AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';++import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';++import { isAgentShareRun } from '../../CompletionLifecycle';+import { logToolCallPc } from '../../formalObservation';+import { hookDispatcher } from '../../hooks';+import type { AgentRuntimeServiceContext } from '../types';+import { toAgentSignalSnapshotEvents } from '../utils';+import type { StepPresentation, StepRunResult } from './runStep';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepHooksDeps = Pick<+ AgentRuntimeServiceContext,+ 'coordinator' | 'queueService' | 'serverDB' | 'userId' | 'workspaceId'+>;+type SignalSnapshotEvents = Array<{ [key: string]: unknown; type: string }>;++/** Emit the `runtime.before_step` signal and dispatch the `beforeStep` hooks. */+export async function dispatchBeforeStepHooks(+ deps: StepHooksDeps,+ {+ agentState,+ operationId,+ stepIndex,+ }: { agentState: AgentState; operationId: string; stepIndex: number },+): Promise<SignalSnapshotEvents> {+ let beforeStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];++ // Dispatch beforeStep hooks+ try {+ 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+ // reasoning (and same predicate) as the completion-signal guard in+ // `CompletionLifecycle.emitSignalEvents`.+ const beforeStepSignalEmission = isAgentShareRun(agentState)+ ? undefined+ : await emitAgentSignalSourceEvent(+ {+ payload: {+ agentId: beforeStepOrigin.agentId,+ operationId,+ serializedContext: undefined,+ stepIndex,+ topicId: beforeStepOrigin.topicId,+ turnCount: agentState?.stepCount || 0,+ },+ sourceId: `${operationId}:before:${stepIndex}`,+ sourceType: 'runtime.before_step',+ },+ {+ agentId: beforeStepOrigin.agentId,+ db: deps.serverDB,+ userId: beforeStepOrigin.userId || deps.userId,+ workspaceId: deps.workspaceId,+ },+ { ignoreError: true },+ );+ beforeStepSignalEvents = toAgentSignalSnapshotEvents(beforeStepSignalEmission);+ await hookDispatcher.dispatch(+ operationId,+ 'beforeStep',+ {+ agentId: beforeStepOrigin.agentId || '',+ finalState: agentState,+ operationId,+ stepIndex,+ steps: agentState?.stepCount || 0,+ userId: beforeStepOrigin.userId || deps.userId,+ },+ agentState?.host?.hooks,+ );+ } catch (hookError) {+ log('[%s] beforeStep hook dispatch error: %O', operationId, hookError);+ }++ return beforeStepSignalEvents;+}++/**+ * Emit the `runtime.after_step` signal and dispatch the `afterStep` hooks,+ * enriched with the step's presentation and the cross-step tracking data.+ */+export async function dispatchAfterStepHooks(+ deps: StepHooksDeps,+ {+ content,+ operationId,+ shouldContinue,+ stepIndex,+ stepPresentationData,+ stepResult,+ toolsCalling,+ }: {+ content: StepPresentation['content'];+ operationId: string;+ shouldContinue: boolean;+ stepIndex: number;+ stepPresentationData: StepPresentation;+ stepResult: StepRunResult;+ toolsCalling: StepPresentation['toolsCalling'];+ },+): Promise<SignalSnapshotEvents> {+ let afterStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];++ // 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()+ : undefined;+ const stepLabel = metadata?._stepLabel;++ // See the `runtime.before_step` guard above — same share-visitor+ // suppression at the sibling per-step emission.+ afterStepSignalEvents = toAgentSignalSnapshotEvents(+ isAgentShareRun(stepResult.newState)+ ? undefined+ : await emitAgentSignalSourceEvent(+ {+ payload: {+ agentId: origin.agentId,+ operationId,+ serializedContext: undefined,+ stepIndex,+ topicId: origin.topicId,+ turnCount: stepResult.newState?.stepCount || 0,+ },+ sourceId: `${operationId}:after:${stepIndex}`,+ sourceType: 'runtime.after_step',+ },+ {+ agentId: origin.agentId,+ db: deps.serverDB,+ userId: origin.userId || deps.userId,+ },+ { ignoreError: true },+ ),+ );++ await hookDispatcher.dispatch(+ operationId,+ 'afterStep',+ {+ agentId: origin.agentId || '',+ content,+ elapsedMs,+ executionTimeMs: stepPresentationData.executionTimeMs,+ finalState: stepResult.newState,+ ...(stepLabel && { stepLabel }),+ lastLLMContent: tracking.lastLLMContent,+ lastToolsCalling: tracking.lastToolsCalling,+ operationId,+ reasoning: stepPresentationData.reasoning,+ shouldContinue,+ status: stepResult.newState?.status,+ stepCost: stepPresentationData.stepCost,+ stepIndex,+ stepType: stepPresentationData.stepType,+ steps: stepResult.newState?.stepCount || 0,+ thinking: stepPresentationData.thinking,+ toolCalls: stepResult.newState?.usage?.tools?.totalCalls,+ toolsCalling: stepPresentationData.toolsCalling,+ toolsResult: stepPresentationData.toolsResult,+ 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: origin.userId || deps.userId,+ },+ stepResult.newState?.host?.hooks,+ );+ } catch (hookError) {+ log('[%s] afterStep hook dispatch error: %O', operationId, hookError);+ }++ return afterStepSignalEvents;+}++/** Accumulate the step tracking the next step's `afterStep` hooks read. */+export async function persistStepTracking(+ deps: StepHooksDeps,+ {+ content,+ operationId,+ shouldContinue,+ stepIndex,+ stepResult,+ toolsCalling,+ }: {+ content: StepPresentation['content'];+ operationId: string;+ shouldContinue: boolean;+ stepIndex: number;+ stepResult: StepRunResult;+ toolsCalling: StepPresentation['toolsCalling'];+ },+): Promise<void> {+ // Update step tracking in state metadata for afterStep hooks (cross-step accumulator)+ const hasAfterStepHooks = stepResult.newState.host?.hooks?.some(+ (h: { type: string }) => h.type === 'afterStep',+ );+ logToolCallPc(operationId, stepIndex, 'post.trace_appended', () => ({}));+ logToolCallPc(operationId, stepIndex, 'post.route_selected', () => ({+ hasAfterStepHooks,+ nextContextPresent: stepResult.nextContext !== undefined,+ queueAvailable: Boolean(deps.queueService),+ shouldContinue,+ }));+ if (hasAfterStepHooks && stepResult.newState.metadata) {+ const prevTracking = stepResult.newState.metadata._stepTracking || {};+ const newTotalToolCalls = (prevTracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0);++ // Truncate content to 1800 chars to keep state small+ const truncatedContent = content+ ? content.length > 1800+ ? content.slice(0, 1800) + '...'+ : content+ : prevTracking.lastLLMContent;++ const updatedTracking = {+ lastLLMContent: truncatedContent,+ lastToolsCalling: toolsCalling || prevTracking.lastToolsCalling,+ totalToolCalls: newTotalToolCalls,+ };++ // Persist tracking state for next step+ stepResult.newState.metadata._stepTracking = updatedTracking;+ await deps.coordinator.saveAgentState(operationId, stepResult.newState);+ logToolCallPc(operationId, stepIndex, 'post.step_tracking_saved', () => ({}));+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.tsnew file mode 100644index 00000000000..1c9e2cac1c4--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts@@ -0,0 +1,348 @@+import { context as otelContext, trace as otelTrace } from '@lobechat/observability-otel/api';+import {+ buildInvokeAgentAttributes,+ buildInvokeAgentResultAttributes,+ invokeAgentSpanName,+ tracer as agentRuntimeTracer,+} from '@lobechat/observability-otel/modules/agent-runtime';+import debug from 'debug';++import {+ type AgentExecutionParams,+ type AgentExecutionResult,+ type AgentStepContinuation,+} from '../../types';+import { STEP_LOCK_TTL_SECONDS } from '../constants';+import type { AgentRuntimeServiceContext } from '../types';+import { createStepLockOwner } from '../utils';+import { startStepAbortPoll, type StepAbortPoll } from './abortPoll';+import { finishOperation } from './completion';+import { scheduleNextStep } from './continuation';+import { failStep } from './failure';+import {+ handleStepLockConflict,+ replayPendingInterventionLifecycle,+ runLockFreeDelivery,+ skipUnrunnableStep,+} from './guards';+import { dispatchAfterStepHooks, dispatchBeforeStepHooks, persistStepTracking } from './hooks';+import { prepareStepInput } from './prepare';+import { runAndReconcileStep, saveAndPublishStep } from './runStep';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type ExecuteStepDeps = Pick<+ AgentRuntimeServiceContext,+ | 'agentOperationModel'+ | 'baseURL'+ | 'buildShareAbortResult'+ | 'calculatePriority'+ | 'calculateStepDelay'+ | 'completionLifecycle'+ | 'computeDeviceContext'+ | 'coordinator'+ | 'createAgentRuntime'+ | 'delegate'+ | 'determineCompletionReason'+ | 'expireClientLlmWait'+ | 'handleGroupMemberTimeout'+ | 'humanIntervention'+ | 'parkForClientLlm'+ | 'publishSubAgentProgress'+ | 'queryStepEntryMessages'+ | 'queryUiMessages'+ | 'queueService'+ | 'readQueuedMessagesFlag'+ | 'recordInterventionLifecycleCompletion'+ | 'refreshMessagesFromDB'+ | 'resolveAsyncToolResumeParentMessageId'+ | 'serverDB'+ | 'shouldContinueExecution'+ | 'shouldReplayPendingInterventionLifecycle'+ | 'startStepLockHeartbeat'+ | 'streamManager'+ | 'traceRecorder'+ | 'tryResumeParentFromAsyncTool'+ | 'userId'+ | 'usesGatewayMessagePatch'+ | 'workspaceId'+>;++/**+ * Execute Agent step+ */+export async function executeStep(+ deps: ExecuteStepDeps,+ params: AgentExecutionParams,+): Promise<AgentExecutionResult> {+ const {+ operationId,+ stepIndex,+ resumeClientLlm,+ externalRetryCount = 0,+ inlineContinuation = false,+ retainStepLock = false,+ stepLockOwner: providedStepLockOwner,+ } = params;++ const lockFree = await runLockFreeDelivery(deps, params);+ if (lockFree) return lockFree;++ // ===== Distributed lock: prevent duplicate execution from QStash retries =====+ const stepLockOwner = providedStepLockOwner ?? createStepLockOwner(operationId, stepIndex);+ const claimed = await deps.coordinator.tryClaimStep(+ operationId,+ stepIndex,+ STEP_LOCK_TTL_SECONDS,+ stepLockOwner,+ );+ if (!claimed) return handleStepLockConflict(deps, params);++ await deps.agentOperationModel.touchRunning(operationId).catch((error) => {+ log('[%s][%d] Operation lease refresh failed: %O', operationId, stepIndex, error);+ });+ const stopStepLockHeartbeat = deps.startStepLockHeartbeat(operationId, stepIndex, stepLockOwner);++ // Hoisted so the shared `finally` can stop it on every exit path — an+ // orphaned poll would keep reading Redis for a step that is long gone.+ let abortPoll: StepAbortPoll | undefined;++ // Hoisted so the error-path snapshot finalize can record an+ // approximate startedAt for the failing step. The inner `startAt` at the+ // runtime.step() call site stays as the authoritative start for the+ // success path.+ const stepStartAt = Date.now();++ // Hoisted so the shared `finally` knows whether the next step stays in this+ // invocation. When it does, the accumulated trace partial stays in memory;+ // on every other exit some other process reads it, so it has to be durable.+ let handedOffInline = false;++ // OTel invoke_agent span. Wraps the entire step body so child spans+ // (chat / execute_tool / context_engineering) auto-nest via the active+ // context. Started with minimal attrs; agent/model/topic are added once+ // agentState is loaded.+ const invokeAgentSpan = agentRuntimeTracer.startSpan(invokeAgentSpanName(), {+ attributes: buildInvokeAgentAttributes({ operationId, stepIndex }),+ });+ const invokeAgentCtx = otelTrace.setSpan(otelContext.active(), invokeAgentSpan);++ try {+ return await otelContext.with(invokeAgentCtx, async () => {+ log('[%s][%d] Start step executing...', operationId, stepIndex);++ // Load agent state BEFORE publishing step_start so we can attach the+ // canonical UIChatMessage snapshot to the event payload. step_start+ // fires after the previous step's DB writes are awaited durable, so+ // the snapshot query here reflects strongly-consistent state — that's+ // the contract that lets the client treat the pushed uiMessages as+ // the source of truth instead of doing its own refetch.+ const agentState = await deps.coordinator.loadAgentState(operationId);++ if (!agentState) {+ throw new Error(`Agent state not found for operation ${operationId}`);+ }++ const replayed = await replayPendingInterventionLifecycle(deps, {+ agentState,+ externalRetryCount,+ operationId,+ stepIndex,+ });+ if (replayed) return replayed;++ const gatewayMessagePatchEnabled = deps.usesGatewayMessagePatch(agentState);+ const { uiMessages: stepStartUiMessages, messages: stepEntryMessages } =+ await deps.queryStepEntryMessages(agentState);+ await deps.streamManager.publishStreamEvent(operationId, {+ data: gatewayMessagePatchEnabled+ ? { messageRevision: stepIndex }+ : { ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }) },+ stepIndex,+ type: 'step_start',+ });++ agentState.metadata = {+ ...agentState.metadata,+ externalRetryCount,+ };++ // Enrich invoke_agent span with agent identity now that state is loaded.+ const stateAgentConfig = agentState.world?.agent as+ { description?: string | null; title?: string | null } | undefined;+ const stateModel = agentState.modelRuntimeConfig?.model;+ const stateProvider = agentState.modelRuntimeConfig?.provider;+ invokeAgentSpan.updateName(invokeAgentSpanName(stateAgentConfig?.title ?? undefined));+ invokeAgentSpan.setAttributes(+ buildInvokeAgentAttributes({+ agentDescription: stateAgentConfig?.description ?? undefined,+ agentId: agentState.origin?.agentId,+ agentName: stateAgentConfig?.title ?? undefined,+ conversationId: agentState.origin?.topicId,+ operationId,+ provider: stateProvider,+ requestModel: stateModel,+ stepIndex,+ }),+ );++ const skipped = await skipUnrunnableStep(deps, {+ agentState,+ operationId,+ resumeClientLlm,+ stepIndex,+ });+ if (skipped) return skipped;++ const beforeStepSignalEvents = await dispatchBeforeStepHooks(deps, {+ agentState,+ operationId,+ stepIndex,+ });++ // Per-step buffer for context engine input/output. Populated by the+ // `tracingContextEngine` callback passed into the executor context;+ // consumed by traceRecorder.appendStep below. Routing CE this way keeps+ // its heavy payload (agentDocuments, systemRole, …) out of+ // `stepResult.events` and therefore out of the Redis state pipeline.+ //+ // Context: contextEngine.input (agentDocuments) was ~2.7MB/step,+ // hitting Upstash Redis 10MB limit. Bypassing events keeps the heavy+ // payload in trace only, reducing per-step Redis state by ~500x.+ let contextEnginePayload: { input: unknown; metadata?: unknown; output: unknown } | undefined;++ // Create Agent and Runtime instances+ // Use agentState.metadata which contains the full app context (topicId, agentId, etc.)+ // operationMetadata only contains basic fields (agentConfig, modelRuntimeConfig, userId)+ abortPoll = startStepAbortPoll(deps, operationId, stepIndex);++ const { runtime } = await deps.createAgentRuntime({+ abortSignal: abortPoll.signal,+ agentState,+ operationId,+ stepIndex,+ tracingContextEngine: (input, output, metadata) => {+ contextEnginePayload = { input, metadata, output };+ },+ });++ const input = await prepareStepInput(deps, { agentState, params, stepEntryMessages });+ const { currentContext } = input;++ const { startAt, stepResult } = await runAndReconcileStep(deps, {+ ...input,+ operationId,+ runtime,+ stepIndex,+ });++ const { content, shouldContinue, stepPresentationData, toolsCalling } =+ await saveAndPublishStep(deps, {+ gatewayMessagePatchEnabled,+ operationId,+ startAt,+ stepIndex,+ stepResult,+ stepStartUiMessages,+ });++ const afterStepSignalEvents = await dispatchAfterStepHooks(deps, {+ content,+ operationId,+ shouldContinue,+ stepIndex,+ stepPresentationData,+ stepResult,+ toolsCalling,+ });++ await deps.traceRecorder.appendStep(operationId, {+ afterStepSignalEvents,+ agentState,+ beforeStepSignalEvents,+ contextEngine: contextEnginePayload,+ currentContext,+ externalRetryCount,+ presentation: stepPresentationData,+ startedAt: startAt,+ stepIndex,+ stepResult,+ });++ await persistStepTracking(deps, {+ content,+ operationId,+ shouldContinue,+ stepIndex,+ stepResult,+ toolsCalling,+ });++ let nextStepScheduled = false;+ let continuation: AgentStepContinuation | undefined;+ if (shouldContinue && stepResult.nextContext && deps.queueService) {+ const scheduled = await scheduleNextStep(deps, {+ inlineContinuation,+ operationId,+ stepIndex,+ stepResult,+ });+ continuation = scheduled.continuation;+ nextStepScheduled = scheduled.nextStepScheduled;+ if (scheduled.handedOffInline) handedOffInline = true;+ }++ // Record final agent-level usage on the invoke_agent span. Done on every+ // step so partial trees (e.g. interrupted runs) still carry the+ // last-known token counters.+ invokeAgentSpan.setAttributes(+ buildInvokeAgentResultAttributes({+ inputTokens: stepResult.newState.usage?.llm?.tokens?.input,+ outputTokens: stepResult.newState.usage?.llm?.tokens?.output,+ stepCount: stepResult.newState.stepCount,+ }),+ );++ if (!shouldContinue) {+ await finishOperation(deps, { invokeAgentSpan, operationId, stepIndex, stepResult });+ }++ return {+ continuation,+ nextStepScheduled,+ state: stepResult.newState,+ stepResult,+ success: true,+ };+ });+ } catch (error) {+ return await failStep(deps, {+ error,+ externalRetryCount,+ invokeAgentSpan,+ operationId,+ stepIndex,+ stepStartAt,+ });+ } finally {+ invokeAgentSpan.end();+ abortPoll?.stop();+ stopStepLockHeartbeat();+ // Parked runs (human input, async tools) and finished ones are read back+ // by a different invocation, so the partial cannot stay in memory only.+ // An inline hand-off keeps it: the next step runs on this recorder.+ if (!handedOffInline) {+ await deps.traceRecorder.flushPartial();+ // Same boundary for the stream: an issued push is only guaranteed to+ // reach the gateway while this invocation is still running.+ await deps.streamManager.drainPushes?.(operationId);+ }+ // The inline step loop keeps the lock across step boundaries — releasing+ // here would open a window for a stale redelivery to claim it mid-run.+ // Its caller releases once, in a `finally`, for the whole invocation.+ if (!retainStepLock) {+ await deps.coordinator.releaseStepLock(operationId, stepIndex, stepLockOwner);+ }+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.tsnew file mode 100644index 00000000000..a28150bb1a3--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/prepare.ts@@ -0,0 +1,242 @@+import type {+ AgentRunClientLlmWait,+ AgentRuntimeContext,+ AgentState,+} from '@lobechat/agent-runtime';+import { type ChatToolPayload } from '@lobechat/types';+import debug from 'debug';++import { isDeviceCapablePlan, isDeviceLockedPlan } from '@/helpers/executionTarget';+import { runMayUseDevice } from '@/server/modules/AgentRuntime/executors/resolveRunActiveDeviceId';+import { buildClientLlmWaitResumeContext } from '@/server/modules/AgentRuntime/llmRelay/clientWait';++import { type AgentExecutionParams } from '../../types';+import type { AgentRuntimeServiceContext } from '../types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepPrepareDeps = Pick<+ AgentRuntimeServiceContext,+ | 'computeDeviceContext'+ | 'humanIntervention'+ | 'readQueuedMessagesFlag'+ | 'refreshMessagesFromDB'+ | 'resolveAsyncToolResumeParentMessageId'+>;++export interface PreparedStepInput {+ currentContext: AgentExecutionParams['context'];+ currentState: AgentState;+ /** Set when a parked supervisor finishes without another LLM turn. */+ forcedFinishState: AgentState | undefined;+ resumedClientLlmWait: AgentRunClientLlmWait | undefined;+}++/**+ * The state and context this step runs with: the human decision it carries,+ * an async-tool or client resume, a forced finish, the device binding and the+ * queued-follow-up flag.+ */+export async function prepareStepInput(+ deps: StepPrepareDeps,+ {+ agentState,+ params,+ stepEntryMessages,+ }: {+ agentState: AgentState;+ params: AgentExecutionParams;+ stepEntryMessages: Awaited<+ ReturnType<AgentRuntimeServiceContext['queryStepEntryMessages']>+ >['messages'];+ },+): Promise<PreparedStepInput> {+ const {+ approvedToolCall,+ context,+ finishAfterAsyncTool,+ humanInput,+ operationId,+ rejectAndContinue,+ rejectionReason,+ resumeAsyncTool,+ resumeClientLlm,+ stepIndex,+ toolMessageId,+ } = params;++ // Handle human intervention+ let currentContext = context;+ // The wait this step resumes, if any: a resumed call that finds no client+ // again re-parks under the same deadline, so retries never extend it.+ let resumedClientLlmWait: AgentRunClientLlmWait | undefined;+ let currentState = agentState;++ if (humanInput || approvedToolCall || rejectionReason) {+ const interventionResult = await deps.humanIntervention.process(currentState, {+ approvedToolCall,+ humanInput,+ rejectAndContinue,+ rejectionReason,+ toolMessageId,+ });+ currentState = interventionResult.newState;+ currentContext = interventionResult.nextContext;+ }++ // Resume from a parked async-tool wait (server sub-agent completion+ // bridge). Every deferred tool has delivered its result by now, so clear+ // the pending set, refresh messages from the DB (to pick up the tool+ // results written out-of-band), and re-enter the LLM with them.+ if (resumeAsyncTool && currentState.status === 'waiting_for_async_tool') {+ const refreshed = await deps.refreshMessagesFromDB(currentState);+ const pendingTools = (currentState.pendingToolsCalling ?? []) as ChatToolPayload[];+ const resumeParentMessageId = deps.resolveAsyncToolResumeParentMessageId(+ refreshed,+ pendingTools,+ );+ currentState = structuredClone(currentState);+ currentState.messages = refreshed;+ currentState.pendingToolsCalling = [];+ currentState.status = 'running';+ currentState.interruption = undefined;+ // Whatever ran while this operation was parked is invisible from+ // here: a sub-agent that saved a credential cleared its own snapshot,+ // not this one. Drop ours rather than render a list that predates it.+ currentState.operationCredentials = undefined;+ currentState.lastModified = new Date().toISOString();+ // A resume op (e.g. approving a callSubAgent) seeds its assistant+ // placeholder before running the tool; when that tool is deferred the+ // op parks with the seed unclaimed. Fill it now — creating another+ // assistant leaves the seed as an empty "…" sibling branch that hides+ // the real answer.+ const seededAssistantMessageId = currentState.pendingAssistantMessageId;+ currentContext = {+ payload: {+ ...(seededAssistantMessageId && { assistantMessageId: seededAssistantMessageId }),+ parentMessageId: resumeParentMessageId,+ },+ phase: 'user_input',+ } as AgentRuntimeContext;+ log(+ '[%s][%d] Resuming from async tool with %d messages (parent=%s)',+ operationId,+ stepIndex,+ refreshed.length,+ resumeParentMessageId,+ );+ }++ // Continue a run parked in `waiting_for_client`: a client that can run the+ // provider asked for it (`resumeFromClientLlmWait` already recorded it as+ // the run's executor). Replay the parked LLM turn into the assistant row+ // it created, on the messages the parked step had.+ if (resumeClientLlm && currentState.status === 'waiting_for_client') {+ const wait = currentState.clientLlmWait;+ resumedClientLlmWait = wait;+ currentState = structuredClone(currentState);+ currentState.status = 'running';+ currentState.clientLlmWait = undefined;+ currentState.error = undefined;+ currentState.lastModified = new Date().toISOString();+ if (wait?.assistantMessageId) currentState.pendingAssistantMessageId = wait.assistantMessageId;+ currentContext = buildClientLlmWaitResumeContext(wait);+ log(+ '[%s][%d] Resuming from waiting_for_client (assistant=%s)',+ operationId,+ stepIndex,+ wait?.assistantMessageId,+ );+ }++ // Finish a parked supervisor op WITHOUT another LLM turn (group+ // orchestration skipCallSupervisor / delegate). Refresh messages so the+ // final group conversation is captured, transition straight to `done`,+ // and let the standard `!shouldContinue` finalization below record+ // completion + dispatch hooks. Skips runtime.step entirely.+ let forcedFinishState: AgentState | undefined;+ if (finishAfterAsyncTool && currentState.status === 'waiting_for_async_tool') {+ const refreshed = await deps.refreshMessagesFromDB(currentState);+ currentState = structuredClone(currentState);+ currentState.messages = refreshed;+ currentState.pendingToolsCalling = [];+ currentState.status = 'done';+ currentState.interruption = undefined;+ currentState.lastModified = new Date().toISOString();+ forcedFinishState = currentState;+ log(+ '[%s][%d] Finishing parked supervisor op after async tool (%d messages)',+ operationId,+ stepIndex,+ refreshed.length,+ );+ }++ // Pre-step computation: extract device context from DB messages+ // Follows front-end computeStepContext pattern — computed at step boundary, not inside executors+ // Only for a run that may actually touch a device: the executors read the+ // id through the same gate, so binding one here for a forbidden run buys+ // nothing and puts the device's working directory and system info into+ // the prompt variables (`serverCallLlmContextBuilder`).+ //+ // A run whose plan still leaves the device open (unrouted, not locked)+ // keeps the remote-device picker for its whole lifetime, so it must keep+ // following it: re-read on every step and let the latest activation win.+ // Binding only once made every later `activateDevice` report success+ // while local tools stayed on the first device.+ const executionPlan = currentState.plan?.execution;+ const deviceStillSelectable =+ !!executionPlan && isDeviceCapablePlan(executionPlan) && !isDeviceLockedPlan(executionPlan);+ if (+ (!currentState.binding?.device?.id || deviceStillSelectable) &&+ runMayUseDevice(currentState)+ ) {+ // Interventions and async resumes can change tool rows after the+ // entry snapshot. Those paths still need a fresh device read.+ const canReuseEntryMessages =+ !humanInput &&+ !approvedToolCall &&+ !rejectionReason &&+ !resumeAsyncTool &&+ !finishAfterAsyncTool;+ const deviceContext = await deps.computeDeviceContext(+ currentState,+ canReuseEntryMessages ? stepEntryMessages : undefined,+ );+ if (deviceContext && deviceContext.activeDeviceId !== currentState.binding?.device?.id) {+ currentState.binding = {+ ...currentState.binding,+ device: {+ id: deviceContext.activeDeviceId,+ platform: deviceContext.devicePlatform,+ systemInfo: deviceContext.deviceSystemInfo,+ },+ };+ log(+ '[%s][%d] Pre-step: device context computed from messages (deviceId: %s)',+ operationId,+ stepIndex,+ deviceContext.activeDeviceId,+ );+ }+ }++ // Queued follow-ups live in the client's composer, not in this state.+ // The client mirrors them into a flag; the agent reads it from the step+ // context and hands the turn back at its next decision point, so the+ // follow-up starts as the next turn instead of after the whole run.+ // This read is authoritative for the step: a value carried in on the+ // incoming context must not keep a hand-back the user has withdrawn.+ if (currentContext && !forcedFinishState) {+ const hasQueuedMessages = await deps.readQueuedMessagesFlag(operationId, stepIndex);+ if (hasQueuedMessages !== Boolean(currentContext.stepContext?.hasQueuedMessages)) {+ const stepContext = { ...currentContext.stepContext };+ if (hasQueuedMessages) stepContext.hasQueuedMessages = true;+ else delete stepContext.hasQueuedMessages;+ currentContext = { ...currentContext, stepContext };+ }+ }++ return { currentContext, currentState, forcedFinishState, resumedClientLlmWait };+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.tsnew file mode 100644index 00000000000..c56957b17b6--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runStep.ts@@ -0,0 +1,287 @@+import type { AgentRuntime, AgentRuntimeContext } from '@lobechat/agent-runtime';+import debug from 'debug';++import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';++import { isSuccessLikeCompletionReason } from '../../CompletionLifecycle';+import { stepChangedCredentials } from '../../credentialFacts';+import { logToolCallPc } from '../../formalObservation';+import { buildProjectedMessagePatch } from '../../messagePatch';+import { buildStepPresentation, formatTokenCount } from '../../stepPresentation';+import { INTERVENTION_LIFECYCLE_CHECKPOINT_KEY } from '../constants';+import type { AgentRuntimeServiceContext, InterventionLifecycleCheckpoint } from '../types';+import type { PreparedStepInput } from './prepare';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type StepRunStepDeps = Pick<+ AgentRuntimeServiceContext,+ | 'completionLifecycle'+ | 'coordinator'+ | 'determineCompletionReason'+ | 'parkForClientLlm'+ | 'publishSubAgentProgress'+ | 'queryUiMessages'+ | 'shouldContinueExecution'+ | 'streamManager'+>;++export type StepRunResult = Awaited<ReturnType<AgentRuntime['step']>>;+export type StepPresentation = ReturnType<typeof buildStepPresentation>['presentation'];++/**+ * Run the step (or take the forced finish), then reconcile it with a Stop that+ * landed meanwhile, or park the run for a client when no executor could make+ * its LLM call.+ */+export async function runAndReconcileStep(+ deps: StepRunStepDeps,+ {+ currentContext,+ currentState,+ forcedFinishState,+ operationId,+ resumedClientLlmWait,+ runtime,+ stepIndex,+ }: PreparedStepInput & { operationId: string; runtime: AgentRuntime; stepIndex: number },+): Promise<{ startAt: number; stepResult: StepRunResult }> {+ // Execute step (skipped when force-finishing a parked supervisor op).+ const startAt = Date.now();+ logToolCallPc(operationId, stepIndex, 'post.runtime_step_entered', () => ({+ forcedFinish: Boolean(forcedFinishState),+ stateStatus: currentState.status,+ }));+ let stepResult = forcedFinishState+ ? { events: [], newState: forcedFinishState, nextContext: undefined }+ : await runtime.step(currentState, currentContext);++ // Inner runtime.step() catches model-runtime exceptions and stuffs the+ // raw error into newState.error without re-throwing — so the outer+ // catch at the bottom of this method never sees them. Normalize ++ // classify here so the raw error doesn't reach Redis state, the+ // success-path trace finalize, or `persistCompletion`'s JSONB write.+ if (stepResult.newState.error) {+ stepResult.newState.error = formatErrorForState(stepResult.newState.error);+ }+ logToolCallPc(operationId, stepIndex, 'post.runtime_step_returned', () => ({+ errorCategory: stepResult.newState.error?.category ?? null,+ errorRetryable: stepResult.newState.error?.retryable ?? null,+ nextContextPresent: stepResult.nextContext !== undefined,+ stateStatus: stepResult.newState.status,+ }));++ // Check if the operation was interrupted while the step was executing+ // (e.g., user clicked abort during a long LLM call). Prefer the tiny+ // sentinel, but fall back to the state once at the step boundary while+ // old workers that only write `status: 'interrupted'` may still be+ // running during a rolling deployment.+ const sentinelInterrupted = await deps.coordinator.isInterrupted(operationId);+ const wasInterrupted = sentinelInterrupted+ ? true+ : (await deps.coordinator.loadAgentState(operationId))?.status === 'interrupted';+ logToolCallPc(operationId, stepIndex, 'post.latest_state_loaded', () => ({+ interrupted: wasInterrupted,+ }));+ if (wasInterrupted) {+ // Stop can be persisted after a client-tool executor's last local+ // signal check but before this reconciliation read. If that executor+ // just returned a parked state, run the agent's existing abort path+ // once so every pending tool call gets a terminal row before the+ // interrupted state is saved.+ if (+ stepResult.newState.status === 'waiting_for_async_tool' &&+ stepResult.newState.pendingToolsCalling?.length &&+ currentContext+ ) {+ const interruptedState = structuredClone(stepResult.newState);+ interruptedState.status = 'interrupted';+ const abortContext: AgentRuntimeContext = {+ ...currentContext,+ payload: {+ ...(currentContext.payload as Record<string, unknown>),+ hasToolsCalling: true,+ toolsCalling: interruptedState.pendingToolsCalling,+ },+ phase: 'llm_result',+ };+ const abortResult = await runtime.step(interruptedState, abortContext);+ stepResult = {+ ...abortResult,+ events: [...stepResult.events, ...abortResult.events],+ };+ }++ stepResult.newState.status = 'interrupted';+ stepResult.newState.lastModified = new Date().toISOString();+ log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);+ } else if (stepResult.newState.status === 'error') {+ // No client could run the step's LLM call: park for one instead of+ // failing (U4c). The parked state is what the step started from, so+ // a resume replays the same call.+ const parkedState = await deps.parkForClientLlm(+ operationId,+ stepResult.newState,+ currentContext,+ resumedClientLlmWait?.expiresAt,+ currentState,+ );+ if (parkedState) {+ stepResult = { ...stepResult, newState: parkedState, nextContext: undefined };+ }+ }++ return { startAt, stepResult };+}++/**+ * Persist the step: file Works and the intervention checkpoint before a+ * terminal save, the gateway message patch, the step result itself, and the+ * `step_complete` event. Returns whether the run continues and the step's+ * presentation.+ */+export async function saveAndPublishStep(+ deps: StepRunStepDeps,+ {+ gatewayMessagePatchEnabled,+ operationId,+ startAt,+ stepIndex,+ stepResult,+ stepStartUiMessages,+ }: {+ gatewayMessagePatchEnabled: boolean;+ operationId: string;+ startAt: number;+ stepIndex: number;+ stepResult: StepRunResult;+ stepStartUiMessages: Awaited<+ ReturnType<AgentRuntimeServiceContext['queryStepEntryMessages']>+ >['uiMessages'];+ },+): Promise<{+ content: StepPresentation['content'];+ shouldContinue: boolean;+ stepPresentationData: StepPresentation;+ toolsCalling: StepPresentation['toolsCalling'];+}> {+ // Decide whether to schedule next step (hoisted above the save: it also+ // gates the pre-snapshot file-Work registration below)+ const shouldContinue = deps.shouldContinueExecution(stepResult.newState, stepResult.nextContext);++ // Register entity-file Works BEFORE the terminal save: `saveStepResult`+ // publishes `agent_runtime_end`, whose `uiMessages` snapshot the client+ // adopts as the settled message list — the Work rows must exist by then+ // or the file-Work card stays absent until a manual refresh. Perceived+ // loading is not extended: for runs with entity edits the early+ // `visible_output_end` is suppressed (see `createAgentRuntime`), so+ // loading covers this export window by design. Idempotent — the+ // dispatchHooks backstop below no-ops via the state marker.+ if (!shouldContinue) {+ const preSaveReason = deps.determineCompletionReason(stepResult.newState);+ if (preSaveReason === 'waiting_for_human') {+ stepResult.newState.metadata = {+ ...stepResult.newState.metadata,+ [INTERVENTION_LIFECYCLE_CHECKPOINT_KEY]: {+ state: 'pending',+ stepIndex,+ } satisfies InterventionLifecycleCheckpoint,+ };+ }++ // Success-like reasons ONLY — a `waiting_for_human` park must NOT+ // register because it is not a completed deliverable boundary. The+ // fresh approval continuation sees the complete authoritative+ // history and performs the terminal scan after the decision runs;+ // registering here would freeze pre-approval content too early.+ if (isSuccessLikeCompletionReason(preSaveReason)) {+ await deps.completionLifecycle.registerFileWorks(operationId, stepResult.newState);+ logToolCallPc(operationId, stepIndex, 'post.file_works_registered', () => ({}));+ }+ }++ // Protocol v2 native runs reconcile only what this step changed. The+ // full before/after lists stay server-side; the wire sees a bounded+ // patch. Publish before saveStepResult because a terminal save emits+ // agent_runtime_end immediately, and the client must apply the patch+ // before completing the run.+ if (gatewayMessagePatchEnabled && stepStartUiMessages) {+ const settledUiMessages = await deps.queryUiMessages(stepResult.newState, {+ skipWorks: shouldContinue,+ });+ if (settledUiMessages) {+ // Projected: this branch runs only for a client that asked for+ // protocol 2, which renders tool view models and can fetch a stored+ // payload back. The model-facing lists are read elsewhere, straight+ // off `MessageModel`, and stay whole.+ await deps.streamManager.publishStreamEvent(operationId, {+ data: buildProjectedMessagePatch(stepStartUiMessages, settledUiMessages, stepIndex + 1),+ stepIndex,+ type: 'message_patch',+ });+ }+ }++ // A credential the run just saved or connected changes the list the next+ // step must show, so the snapshot frozen at creation no longer holds.+ // Dropped before the save below — that write is what the next step+ // reloads, and nothing else persists the state on a plain step.+ if (stepChangedCredentials(stepResult.nextContext) && stepResult.newState.operationCredentials) {+ stepResult.newState.operationCredentials = undefined;+ log('[%s][%d] Credentials changed in-run; dropped the snapshot', operationId, stepIndex);+ }++ // Save state, coordinator will handle event sending automatically+ await deps.coordinator.saveStepResult(operationId, {+ ...stepResult,+ executionTime: Date.now() - startAt,+ stepIndex, // placeholder+ });+ logToolCallPc(operationId, stepIndex, 'post.step_result_saved', () => ({+ stateStatus: stepResult.newState.status,+ stateStepCount: stepResult.newState.stepCount,+ }));++ // The next step is scheduled after this event, so it always reports `false`.+ const nextStepScheduled = false;++ // Publish step complete event+ await deps.streamManager.publishStreamEvent(operationId, {+ data: {+ ...(stepResult.newState.host?.includeFinalState === true && {+ finalState: stepResult.newState,+ }),+ nextStepScheduled,+ stepIndex,+ },+ stepIndex,+ type: 'step_complete',+ });+ logToolCallPc(operationId, stepIndex, 'post.step_complete_published', () => ({}));++ await deps.publishSubAgentProgress(stepResult.newState, stepIndex);++ // Build enhanced step completion log & presentation data+ const { presentation: stepPresentationData, summary: stepSummary } = buildStepPresentation(+ stepResult,+ Date.now() - startAt,+ );++ const { usage } = stepResult.newState;+ log(+ '[%s][%d] completed %s | total: %s tokens / $%s | llm×%d | tools×%d',+ operationId,+ stepIndex,+ stepSummary,+ formatTokenCount(stepPresentationData.totalTokens),+ stepPresentationData.totalCost.toFixed(4),+ usage?.llm?.apiCalls ?? 0,+ usage?.tools?.totalCalls ?? 0,+ );++ const toolsCalling = stepPresentationData.toolsCalling;+ const content = stepPresentationData.content;++ return { content, shouldContinue, stepPresentationData, toolsCalling };+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeSync.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeSync.tsnew file mode 100644index 00000000000..56ea11a0b54--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeSync.ts@@ -0,0 +1,127 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import { isParkedStatus } from '@lobechat/agent-runtime';+import debug from 'debug';++import type { AgentRuntimeServiceContext } from './types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type ExecuteSyncDeps = Pick<+ AgentRuntimeServiceContext,+ 'completionLifecycle' | 'coordinator' | 'executeStep' | 'shouldContinueExecution'+>;++/**+ * Synchronously execute Agent operation until completion+ *+ * Used in test scenarios, doesn't depend on QueueService, executes all steps directly in the current process.+ *+ * @param operationId Operation ID+ * @param options Execution options+ * @returns Final state+ *+ * @example+ * ```ts+ * // Create operation (without auto-starting queue)+ * const result = await service.createOperation({ ...params, autoStart: false });+ *+ * // Synchronously execute to completion+ * const finalState = await service.executeSync(result.operationId);+ * expect(finalState.status).toBe('done');+ * ```+ */+export async function executeSync(+ deps: ExecuteSyncDeps,+ operationId: string,+ options?: {+ /** Initial context (if not provided, inferred from state) */+ initialContext?: AgentRuntimeContext;+ /** Maximum step limit to prevent infinite loops, defaults to 9999 */+ maxSteps?: number;+ /** Callback after each step execution (for debugging) */+ onStepComplete?: (stepIndex: number, state: AgentState) => void;+ },+): Promise<AgentState> {+ const { maxSteps = 999, onStepComplete, initialContext } = options ?? {};++ log('[%s] Starting sync execution (maxSteps: %d)', operationId, maxSteps);++ // Load initial state+ const initialState = await deps.coordinator.loadAgentState(operationId);+ if (!initialState) {+ throw new Error(`Agent state not found for operation ${operationId}`);+ }++ let state: AgentState = initialState;++ // Build initial context+ // Priority: explicit initialContext param > saved initialContext in state > default+ let context: AgentRuntimeContext | undefined =+ initialContext ??+ (state as any).initialContext ??+ ({+ payload: {},+ phase: 'user_input' as const,+ session: {+ messageCount: state.messages?.length ?? 0,+ sessionId: operationId,+ status: state.status,+ stepCount: state.stepCount,+ },+ } as AgentRuntimeContext);++ let stepIndex = state.stepCount;++ // Execution loop+ while (stepIndex < maxSteps) {+ // Check termination conditions+ if (state.status === 'done' || state.status === 'error' || state.status === 'interrupted') {+ log('[%s] Sync execution finished with status: %s', operationId, state.status);+ break;+ }++ // Parked on a pause (human intervention or an async tool / sub-agent+ // result) — the result is delivered out-of-band, so sync execution+ // can't resume it+ if (isParkedStatus(state.status)) {+ log('[%s] Sync execution paused: %s', operationId, state.status);+ break;+ }++ // Execute one step+ log('[%s][%d] Start executing...', operationId, stepIndex);+ const result = await deps.executeStep({+ context,+ operationId,+ stepIndex,+ });++ state = result.state as AgentState;+ context = result.stepResult.nextContext;+ stepIndex++;++ // Callback+ if (onStepComplete) {+ onStepComplete(stepIndex, state);+ }++ // Check if should continue+ if (!deps.shouldContinueExecution(state, context)) {+ log('[%s] Sync execution stopped: shouldContinue=false', operationId);+ break;+ }+ }++ if (stepIndex >= maxSteps) {+ log('[%s] Sync execution stopped: reached maxSteps (%d)', operationId, maxSteps);+ // If stopped due to executeSync's maxSteps limit, need to manually dispatch onComplete hooks+ // Note: If stopped due to state.maxSteps being reached, onComplete has already been called in executeStep+ if (state.status !== 'done' && state.status !== 'error') {+ await deps.completionLifecycle.emitSignalEvents(operationId, state, 'max_steps');+ await deps.completionLifecycle.dispatchHooks(operationId, state, 'max_steps');+ }+ }++ return state;+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/groupMember.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/groupMember.tsnew file mode 100644index 00000000000..ddd33b8928c--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/groupMember.ts@@ -0,0 +1,425 @@+import debug from 'debug';++import {+ extractTextFromMessage,+ findLastAssistantMessage,+ normalizeCompletionMessages,+} from '../CompletionLifecycle';+import {+ type AgentExecutionResult,+ type GroupActionMemberBridgeParams,+ type GroupMemberTimeoutParams,+} from '../types';+import type { AgentRuntimeServiceContext } from './types';+import { formatErrorForMetadata, formatSubAgentErrorReason } from './utils';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type GroupMemberDeps = Pick<+ AgentRuntimeServiceContext,+ | 'agentOperationModel'+ | 'baseURL'+ | 'completeGroupActionMember'+ | 'completeGroupMemberBarrier'+ | 'controlCompletedToolResult'+ | 'coordinator'+ | 'countFulfilledMemberAnchors'+ | 'interruptOperation'+ | 'maybeScheduleAsyncToolVerify'+ | 'messageModel'+ | 'queueService'+ | 'resolveLastAssistantContentFromThread'+ | 'resolveLastAssistantMessageFromDB'+ | 'serverDB'+ | 'tryResumeParentFromAsyncTool'+>;++/**+ * The completion bridge of a group member run: from its runtime snapshot+ * while it lives, else from the durable copy recorded on the operation row+ * at start. Undefined for any run that is not a group member.+ */+export async function loadGroupMemberBridge(+ deps: GroupMemberDeps,+ operationId: string,+): Promise<+ | {+ agentId: string;+ bridge: Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'>;+ groupId?: string;+ threadId?: string;+ topicId?: string;+ }+ | undefined+> {+ const state = await deps.coordinator.loadAgentState(operationId);+ if (state) {+ const origin = state.origin;+ const bridge = state.host?.hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook+ ?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;+ if (origin?.lineage?.orchestrationRole !== 'member' || !origin.agentId || !bridge) {+ return undefined;+ }+ return {+ agentId: origin.agentId,+ bridge,+ groupId: origin.groupId ?? undefined,+ threadId: origin.threadId ?? undefined,+ topicId: origin.topicId ?? undefined,+ };+ }++ const row = await deps.agentOperationModel.findById(operationId);+ const bridge = (row?.metadata as Record<string, unknown> | null | undefined)+ ?.groupMemberBridge as+ Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;+ if (!row?.agentId || !bridge) return undefined;+ return {+ agentId: row.agentId,+ bridge,+ groupId: row.chatGroupId ?? undefined,+ threadId: row.threadId ?? undefined,+ topicId: row.topicId ?? undefined,+ };+}++/**+ * Count fulfilled member anchors under a group-management tool call — child+ * `role: 'tool'` messages whose content is non-empty or whose pluginState is+ * terminal. The K=N member barrier for broadcast / executeAgentTasks: the+ * group tool message is only backfilled (satisfying the parked op's+ * single-tool barrier) once this reaches the expected member count.+ */+export async function countFulfilledMemberAnchors(+ deps: GroupMemberDeps,+ groupToolMessageId: string,+): Promise<number> {+ const children = await deps.serverDB.query.messages.findMany({+ where: (m, { and, eq }) => and(eq(m.parentId, groupToolMessageId), eq(m.role, 'tool')),+ });+ let fulfilled = 0;+ for (const child of children) {+ if (child.content && child.content.length > 0) {+ fulfilled += 1;+ continue;+ }+ const plugin = await deps.serverDB.query.messagePlugins.findFirst({+ where: (mp, { eq }) => eq(mp.id, child.id),+ });+ const pluginState = plugin?.state as { status?: string } | null;+ if (pluginState?.status === 'completed' || pluginState?.status === 'error') fulfilled += 1;+ }+ return fulfilled;+}++/**+ * Completion bridge for the group orchestration "call agent member" path+ * (`lobe-group-management`: speak / broadcast / delegate / executeAgentTask(s)).+ * Mirrors {@link completeSubAgentBridge} but enforces a K=N member barrier:+ *+ * 1. Backfill this member's anchor tool message (in_group → a short receipt,+ * since the member already spoke in the shared group conversation;+ * isolated → the member's final answer from its hidden thread).+ * 2. Multi-member actions: hold until every member anchor is fulfilled, then+ * backfill the supervisor's group tool message so the parked op's+ * single-tool barrier passes. Single-member actions collapse the anchor+ * onto the group tool call, so step 1 already satisfies the barrier.+ * 3. Barrier-check + CAS resume/finish the parked supervisor via+ * `tryResumeParentFromAsyncTool` (finish disposition read from the group+ * tool message's pluginState).+ *+ * THROWS on infra failure of any backfill so the queue-mode callback returns+ * non-2xx and QStash redelivers — backfills are idempotent and the resume is+ * CAS-guarded, so redelivery is safe.+ */+export async function completeGroupActionMember(+ deps: GroupMemberDeps,+ params: GroupActionMemberBridgeParams,+): Promise<boolean> {+ const {+ anchorMessageId,+ expectedMembers,+ groupToolMessageId,+ mode,+ operationId,+ parentOperationId,+ reason,+ threadId,+ } = params;+ const failed = reason === 'error' || reason === 'interrupted' || reason === 'timeout';++ // Members answer to the supervisor's approval mode, so a member can park on+ // a tool that needs the user's approval. That segment fires `onComplete`+ // (so the approval surfaces), but the member has not answered yet: leave its+ // anchor pending and the supervisor parked. The approval continuation+ // inherits this bridge hook and reports the member's real outcome.+ if (reason === 'waiting_for_human') {+ log(+ '[%s] group-member bridge: member parked for human approval, holding parent %s',+ operationId,+ parentOperationId,+ );+ return false;+ }++ const finalState =+ params.finalState ?? (await deps.coordinator.loadAgentState(operationId)) ?? undefined;++ log(+ '[%s] group-member bridge → parent %s (mode: %s, reason: %s, %d members)',+ operationId,+ parentOperationId,+ mode,+ reason,+ expectedMembers,+ );++ // 1. Backfill this member's anchor.+ // The member's textual answer is only read in delegate mode below; a state+ // loaded via the fallback above arrives without `messages` (dropped from+ // the persisted Redis blob — see AgentStateManager.serializeStateForPersist),+ // so resolve the original final leaf from the DB when we actually need it.+ // Keeping the original row preserves the exact content/metadata pairing+ // that conversation-flow display grouping intentionally aggregates.+ let lastAssistant: unknown;+ if (!failed && mode !== 'in_group' && finalState && !Array.isArray(finalState.messages)) {+ try {+ lastAssistant = await deps.resolveLastAssistantMessageFromDB(finalState);+ } catch (error) {+ console.error(+ '[%s] group-member bridge: failed to resolve final assistant from DB: %O',+ operationId,+ error,+ );+ }+ }+ const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];+ lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));+ let lastAssistantContent = extractTextFromMessage(lastAssistant);++ // Gated on `!finalState`, not merely an empty `lastAssistantContent` —+ // see the identical guard (and its full rationale) in+ // `completeSubAgentBridge`. A real final state whose last turn is+ // legitimately textless must keep the stub below, not risk surfacing a+ // stale earlier reply from the thread's own history. `!finalState` is+ // exactly the heterogeneous-isolated-member case this fallback exists+ // for: it never populates `finalState` at all.+ if (!failed && mode !== 'in_group' && !finalState && threadId) {+ try {+ lastAssistantContent = await deps.resolveLastAssistantContentFromThread(threadId);+ } catch (error) {+ console.error(+ '[%s] group-member bridge: failed to resolve content from thread %s: %O',+ operationId,+ threadId,+ error,+ );+ }+ }+ const agentLabel = (finalState?.origin?.agentId as string | undefined) ?? 'member';+ const memberErrorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;+ const anchorContent = failed+ ? memberErrorReason+ ? `Agent member did not complete (${reason}): ${memberErrorReason}`+ : `Agent member did not complete (${reason}).`+ : mode === 'in_group'+ ? `Agent ${agentLabel} responded in the group.`+ : lastAssistantContent || 'Agent member completed without a textual answer.';++ const { result: completed, blocked } = await deps.controlCompletedToolResult({+ preserveUsage: true,+ contextToolMessageId: groupToolMessageId,+ operationId: parentOperationId,+ toolMessageId: anchorMessageId,+ result: {+ content: anchorContent,+ success: !failed,+ error: failed ? formatErrorForMetadata(finalState?.error) : undefined,+ state: {+ model: finalState?.modelRuntimeConfig?.model,+ status: failed ? 'error' : 'completed',+ threadId,+ // The child's spend rides on this anchor row so the parent's usage tray can+ // account for it. The tray sums per-MESSAGE usage, and the child's own+ // assistant messages live in an isolation thread the parent never loads —+ // this row is the only place the child's cost surfaces in the parent's own+ // message list.+ totalCost: finalState?.cost?.total,+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,+ totalToolCalls: finalState?.usage?.tools?.totalCalls,+ totalTokens: finalState?.usage?.llm?.tokens?.total,+ },+ },+ });+ const anchorBackfill = await deps.messageModel.updateToolMessage(anchorMessageId, {+ content: completed.content,+ pluginError: completed.error ?? null,+ pluginState: completed.state,+ onlyIfEmpty: true,+ ...(blocked && { replacePluginState: true }),+ });+ if (!anchorBackfill.success) {+ throw new Error(+ `Group-member bridge: failed to backfill anchor ${anchorMessageId} for parent ${parentOperationId}`,+ );+ }++ return deps.completeGroupMemberBarrier({+ anchorMessageId,+ expectedMembers,+ groupToolMessageId,+ parentOperationId,+ });+}++/** Shared by a child's completion and a member that failed before an operation existed. */+export async function completeGroupMemberBarrier(+ deps: GroupMemberDeps,+ {+ anchorMessageId,+ expectedMembers,+ groupToolMessageId,+ parentOperationId,+ }: Pick<+ GroupActionMemberBridgeParams,+ 'anchorMessageId' | 'expectedMembers' | 'groupToolMessageId' | 'parentOperationId'+ >,+): Promise<boolean> {+ // 2. K=N member barrier (multi-member actions only — single-member actions+ // use the group tool call itself as the anchor, already backfilled above).+ if (expectedMembers > 1 && anchorMessageId !== groupToolMessageId) {+ const fulfilled = await deps.countFulfilledMemberAnchors(groupToolMessageId);+ if (fulfilled < expectedMembers) {+ log(+ '[%s] group-member barrier %d/%d, holding parent %s',+ parentOperationId,+ fulfilled,+ expectedMembers,+ parentOperationId,+ );+ const parentState = await deps.coordinator.loadAgentState(parentOperationId);+ if (parentState) {+ await deps.maybeScheduleAsyncToolVerify(parentOperationId, parentState, {+ scheduleVerifyOnHold: true,+ });+ }+ return false;+ }++ // All members done — backfill the group tool call so the parked op's+ // single-tool barrier ([groupTool]) passes. Idempotent across racing+ // last-committers; the resume/finish CAS guarantees one transition.+ const { result: groupResult, blocked: groupBlocked } = await deps.controlCompletedToolResult({+ operationId: parentOperationId,+ toolMessageId: groupToolMessageId,+ result: {+ content: `All ${expectedMembers} agent members completed.`,+ state: { expectedMembers, status: 'completed' },+ success: true,+ },+ });+ const groupBackfill = await deps.messageModel.updateToolMessage(groupToolMessageId, {+ content: groupResult.content,+ pluginError: groupResult.error ?? null,+ pluginState: groupResult.state,+ onlyIfEmpty: true,+ ...(groupBlocked && {+ replacePluginState: true,+ }),+ });+ if (!groupBackfill.success) {+ throw new Error(+ `Group-member bridge: failed to backfill group tool ${groupToolMessageId} for parent ${parentOperationId}`,+ );+ }+ }++ // 3. Barrier + CAS + resume/finish the parked supervisor op.+ return deps.tryResumeParentFromAsyncTool({ parentOperationId }, { scheduleVerifyOnHold: true });+}++/**+ * Schedule the group-member timeout watchdog. Fired `delayMs` after the member+ * op is forked; if the member hasn't finished by then, the watchdog interrupts+ * it and bridges a `timeout` completion so the parked supervisor doesn't wait+ * forever. No-op when the queue is disabled or the timeout is non-positive.+ */+export async function scheduleGroupMemberTimeout(+ deps: GroupMemberDeps,+ params: GroupMemberTimeoutParams,+ delayMs: number,+): Promise<void> {+ if (!deps.queueService || !(delayMs > 0)) return;+ try {+ await deps.queueService.scheduleMessage({+ context: undefined,+ delay: delayMs,+ endpoint: `${deps.baseURL}/run`,+ // Keyed on the member op so the /run worker can resolve userId from its+ // metadata, same trust chain as every other scheduled step.+ operationId: params.memberOperationId,+ payload: { groupMemberTimeout: params },+ priority: 'normal',+ stepIndex: 0,+ });+ log(+ '[%s] scheduled group-member timeout in %dms (parent %s)',+ params.memberOperationId,+ delayMs,+ params.parentOperationId,+ );+ } catch (error) {+ log(+ '[%s] failed to schedule group-member timeout (non-fatal): %O',+ params.memberOperationId,+ error,+ );+ }+}++/**+ * Enforce a group member's timeout. No-op if the member already reached a+ * terminal state (its own completion bridge handles that). Otherwise interrupt+ * the member and bridge a `timeout` completion — backfilling its anchor and+ * resuming/finishing the parked supervisor via the K=N barrier. The member's+ * own interrupt bridge may also fire; both are idempotent (anchor rewrite ++ * CAS-guarded resume).+ */+export async function handleGroupMemberTimeout(+ deps: GroupMemberDeps,+ params: GroupMemberTimeoutParams,+): Promise<AgentExecutionResult> {+ const state = await deps.coordinator.loadAgentState(params.memberOperationId);+ const status = state?.status as string | undefined;+ if (!state || status === 'done' || status === 'error' || status === 'interrupted') {+ log(+ '[%s] group-member timeout: member already terminal (%s), no-op',+ params.memberOperationId,+ status,+ );+ return { nextStepScheduled: false, state: {}, success: true };+ }++ log(+ '[%s] group-member timeout fired, interrupting + bridging timeout to parent %s',+ params.memberOperationId,+ params.parentOperationId,+ );+ await deps.interruptOperation(params.memberOperationId);++ const resumed = await deps.completeGroupActionMember({+ anchorMessageId: params.anchorMessageId,+ expectedMembers: params.expectedMembers,+ finalState: state,+ groupToolMessageId: params.groupToolMessageId,+ mode: params.mode,+ onComplete: params.onComplete,+ operationId: params.memberOperationId,+ parentOperationId: params.parentOperationId,+ reason: 'timeout',+ });++ return { nextStepScheduled: resumed, state: {}, success: true };+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.tsnew file mode 100644index 00000000000..926adabfd0a--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts@@ -0,0 +1,625 @@+import type { Agent, GeneralAgentConfig } from '@lobechat/agent-runtime';+import debug from 'debug';+import urlJoin from 'url-join';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { MessageModel } from '@/database/models/message';+import { type LobeChatDatabase } from '@/database/type';+import { appEnv } from '@/envs/app';+import { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modules/AgentRuntime';+import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';+import { mcpService } from '@/server/services/mcp';+import { MessageService } from '@/server/services/message';+import { QueueService } from '@/server/services/queue';+import { ToolExecutionService } from '@/server/services/toolExecution';+import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';++import { CompletionLifecycle } from '../CompletionLifecycle';+import { HumanInterventionHandler } from '../HumanInterventionHandler';+import { OperationTraceRecorder } from '../OperationTraceRecorder';+import { createDefaultSnapshotStore } from '../snapshotStore';+import {+ allPendingToolsFulfilled,+ maybeScheduleAsyncToolVerify,+ resolveAsyncToolOnComplete,+ tryResumeParentFromAsyncTool,+} from './asyncTool';+import {+ endExpiredClientLlmWait,+ expireClientLlmWait,+ finishClientLlmWaitExpiry,+ listClientLlmWaits,+ parkForClientLlm,+ restoreClientLlmWait,+ resumeFromClientLlmWait,+ revertClientWaitResumeWithRetry,+ updateAssistantRowWithRetry,+} from './clientLlmWait';+import { createOperation } from './createOperation';+import { executeStep } from './executeStep/index';+import { executeSync } from './executeSync';+import {+ completeGroupActionMember,+ completeGroupMemberBarrier,+ countFulfilledMemberAnchors,+ handleGroupMemberTimeout,+ loadGroupMemberBridge,+ scheduleGroupMemberTimeout,+} from './groupMember';+import {+ ensureInterventionContinuationStarted,+ getPendingInterventions,+ loadInterventionContinuationState,+ persistInterventionDispatchAck,+ processHumanIntervention,+ recordInterventionLifecycleCompletion,+ shouldReplayPendingInterventionLifecycle,+} from './intervention';+import {+ queryMessagesFromDB,+ queryStepEntryMessages,+ queryUiMessages,+ refreshMessagesFromDB,+ resolveAsyncToolResumeParentMessageId,+ resolveLastAssistantContentFromThread,+ resolveLastAssistantMessageFromDB,+ usesGatewayMessagePatch,+} from './messages';+import {+ acceptsFileWorks,+ acceptsMemberRuntimeEnd,+ controlCompletedToolResult,+ getOperationStatus,+ interruptOperation,+ isOperationInterrupted,+ readQueuedMessagesFlag,+ releaseOperationLock,+ scheduleContinuation,+ setQueuedMessages,+ startExecution,+ startStepLockHeartbeat,+} from './operationControl';+import {+ computeDeviceContext,+ createAgentRuntime,+ getLlmExecutor,+ resolveLlmExecutor,+ setupLocalExecutionCallback,+} from './runtimeFactory';+import { buildShareAbortResult } from './shareRunGate';+import {+ calculatePriority,+ calculateStepDelay,+ determineCompletionReason,+ shouldContinueExecution,+} from './stepPolicy';+import {+ completeSubAgentBridge,+ isCallSubAgentToolMessage,+ publishSubAgentProgress,+} from './subAgentBridge';+import type {+ AgentRuntimeDelegate,+ AgentRuntimeServiceContext,+ AgentRuntimeServiceOptions,+ MethodArgs,+} from './types';+import { createStepLockOwner } from './utils';++if (process.env.VERCEL) {+ // Route debug output to stdout (`console.info`) instead of stderr, which+ // Vercel would otherwise surface as error-level logs.+ debug.log = console.info.bind(console);+}++export { createEvalToolForwardingHook } from './evalToolForwardingHook';+export type { AgentRuntimeDelegate, AgentRuntimeServiceOptions } from './types';++/**+ * The step executor and its operation lifecycle. The class holds the+ * collaborators and delegates every method to a sibling module, handing it the+ * narrow `AgentRuntimeServiceContext` view it declares; calls still dispatch+ * through the instance, so the methods stay overridable and spy-able.+ */+export class AgentRuntimeService {+ private readonly agentOperationModel: AgentOperationModel;+ private readonly agentFactory?: (config: GeneralAgentConfig) => Agent;+ private readonly completionLifecycle: CompletionLifecycle;+ private readonly coordinator: AgentRuntimeCoordinator;+ private readonly delegate: AgentRuntimeDelegate;+ private readonly humanIntervention: HumanInterventionHandler;+ private readonly streamManager: IStreamEventManager;+ private readonly queueService: QueueService | null;+ private readonly traceRecorder: OperationTraceRecorder;+ private readonly toolExecutionService: ToolExecutionService;+ private get baseURL() {+ const baseUrl = process.env.AGENT_RUNTIME_BASE_URL || appEnv.APP_URL || 'http://localhost:3010';++ return urlJoin(baseUrl, '/api/agent');+ }+ private readonly serverDB: LobeChatDatabase;+ private readonly userId: string;+ private readonly workspaceId?: string;+ private readonly messageModel: MessageModel;+ // Lazily constructed because MessageService instantiates a FileService+ // which eagerly creates the S3 client and throws when S3 env vars are+ // missing — eager construction would break every test that builds an+ // AgentRuntimeService without mocking the file backend.+ private messageServiceInstance?: MessageService;+ private get messageService(): MessageService {+ if (!this.messageServiceInstance) {+ this.messageServiceInstance = new MessageService(+ this.serverDB,+ this.userId,+ this.workspaceId,+ );+ }+ return this.messageServiceInstance;+ }++ constructor(db: LobeChatDatabase, userId: string, options?: AgentRuntimeServiceOptions) {+ // Use factory function to auto-select Redis or InMemory implementation.+ // Gateway pushes are deferred off the step path: every point where this+ // invocation can stop or hand the run over calls `drainPushes` first.+ this.streamManager =+ options?.streamEventManager ??+ options?.coordinatorOptions?.streamEventManager ??+ createStreamEventManager({ deferPushes: true });+ this.coordinator = new AgentRuntimeCoordinator({+ ...options?.coordinatorOptions,+ messagePatchModeResolver: (state) => this.usesGatewayMessagePatch(state),+ streamEventManager: this.streamManager,+ // Provide the canonical UIChatMessage[] for terminal-state events so+ // the client can use the pushed payload directly instead of refetching+ // from DB. Falls back gracefully when topicId isn't set.+ uiMessagesResolver: async (state) =>+ this.usesGatewayMessagePatch(state) ? undefined : this.queryUiMessages(state),+ });+ this.queueService =+ options?.queueService === null ? null : (options?.queueService ?? new QueueService());+ this.traceRecorder = new OperationTraceRecorder(+ options?.snapshotStore ?? createDefaultSnapshotStore(),+ );+ this.agentFactory = options?.agentFactory;+ this.delegate = options?.delegate ?? {};+ this.serverDB = db;+ this.userId = userId;+ this.workspaceId = options?.workspaceId;+ const workspaceId = this.workspaceId;+ const includeShareVisitor = options?.includeShareVisitor ?? false;+ this.agentOperationModel = new AgentOperationModel(db, this.userId, workspaceId);+ this.messageModel = new MessageModel(db, this.userId, workspaceId, undefined, {+ includeShareVisitor,+ });+ this.completionLifecycle = new CompletionLifecycle(db, userId, workspaceId, {+ includeShareVisitor,+ });+ this.humanIntervention = new HumanInterventionHandler(db, this.messageModel);++ // Initialize ToolExecutionService with dependencies+ const builtinToolsExecutor = new BuiltinToolsExecutor(db, userId);++ this.toolExecutionService = new ToolExecutionService({+ builtinToolsExecutor,+ mcpService,+ });++ // Setup local execution callback for LocalQueueServiceImpl+ this.setupLocalExecutionCallback();+ }++ // ==================== Operation Interruption ====================++ // ==================== Operation Management ====================++ /**+ * Mint a lock owner for an inline step loop. Unique per invocation, which is+ * what makes re-entering the same lock on the next step safe.+ */+ createOperationLockOwner(operationId: string): string {+ return createStepLockOwner(operationId, 0);+ }++ // ==================== Waiting for a client (U4c) ====================++ /**+ * Get Coordinator instance (for testing)+ */+ getCoordinator(): AgentRuntimeCoordinator {+ return this.coordinator;+ }++ /**+ * The view the sibling modules get: the collaborators through getters, so a+ * module reads a field when it uses it (as a method body did), and the+ * methods through arrows, so a call still dispatches on the instance.+ */+ private get context(): AgentRuntimeServiceContext {+ // eslint-disable-next-line @typescript-eslint/no-this-alias+ const self = this;+ return {+ get agentOperationModel() {+ return self.agentOperationModel;+ },+ get agentFactory() {+ return self.agentFactory;+ },+ get completionLifecycle() {+ return self.completionLifecycle;+ },+ get coordinator() {+ return self.coordinator;+ },+ get delegate() {+ return self.delegate;+ },+ get humanIntervention() {+ return self.humanIntervention;+ },+ get streamManager() {+ return self.streamManager;+ },+ get queueService() {+ return self.queueService;+ },+ get traceRecorder() {+ return self.traceRecorder;+ },+ get toolExecutionService() {+ return self.toolExecutionService;+ },+ get baseURL() {+ return self.baseURL;+ },+ get serverDB() {+ return self.serverDB;+ },+ get userId() {+ return self.userId;+ },+ get workspaceId() {+ return self.workspaceId;+ },+ get messageModel() {+ return self.messageModel;+ },+ get messageService() {+ return self.messageService;+ },+ acceptsFileWorks: (...args) => self.acceptsFileWorks(...args),+ acceptsMemberRuntimeEnd: (...args) => self.acceptsMemberRuntimeEnd(...args),+ allPendingToolsFulfilled: (...args) => self.allPendingToolsFulfilled(...args),+ buildShareAbortResult: (...args) => self.buildShareAbortResult(...args),+ calculatePriority: (...args) => self.calculatePriority(...args),+ calculateStepDelay: (...args) => self.calculateStepDelay(...args),+ completeGroupActionMember: (...args) => self.completeGroupActionMember(...args),+ completeGroupMemberBarrier: (...args) => self.completeGroupMemberBarrier(...args),+ completeSubAgentBridge: (...args) => self.completeSubAgentBridge(...args),+ computeDeviceContext: (...args) => self.computeDeviceContext(...args),+ controlCompletedToolResult: (...args) => self.controlCompletedToolResult(...args),+ countFulfilledMemberAnchors: (...args) => self.countFulfilledMemberAnchors(...args),+ createAgentRuntime: (...args) => self.createAgentRuntime(...args),+ createOperation: (...args) => self.createOperation(...args),+ determineCompletionReason: (...args) => self.determineCompletionReason(...args),+ endExpiredClientLlmWait: (...args) => self.endExpiredClientLlmWait(...args),+ ensureInterventionContinuationStarted: (...args) =>+ self.ensureInterventionContinuationStarted(...args),+ executeStep: (...args) => self.executeStep(...args),+ executeSync: (...args) => self.executeSync(...args),+ expireClientLlmWait: (...args) => self.expireClientLlmWait(...args),+ finishClientLlmWaitExpiry: (...args) => self.finishClientLlmWaitExpiry(...args),+ getLlmExecutor: (...args) => self.getLlmExecutor(...args),+ getOperationStatus: (...args) => self.getOperationStatus(...args),+ getPendingInterventions: (...args) => self.getPendingInterventions(...args),+ handleGroupMemberTimeout: (...args) => self.handleGroupMemberTimeout(...args),+ interruptOperation: (...args) => self.interruptOperation(...args),+ isCallSubAgentToolMessage: (...args) => self.isCallSubAgentToolMessage(...args),+ isOperationInterrupted: (...args) => self.isOperationInterrupted(...args),+ listClientLlmWaits: (...args) => self.listClientLlmWaits(...args),+ loadGroupMemberBridge: (...args) => self.loadGroupMemberBridge(...args),+ loadInterventionContinuationState: (...args) =>+ self.loadInterventionContinuationState(...args),+ maybeScheduleAsyncToolVerify: (...args) => self.maybeScheduleAsyncToolVerify(...args),+ parkForClientLlm: (...args) => self.parkForClientLlm(...args),+ persistInterventionDispatchAck: (...args) => self.persistInterventionDispatchAck(...args),+ processHumanIntervention: (...args) => self.processHumanIntervention(...args),+ publishSubAgentProgress: (...args) => self.publishSubAgentProgress(...args),+ queryMessagesFromDB: (...args) => self.queryMessagesFromDB(...args),+ queryStepEntryMessages: (...args) => self.queryStepEntryMessages(...args),+ queryUiMessages: (...args) => self.queryUiMessages(...args),+ readQueuedMessagesFlag: (...args) => self.readQueuedMessagesFlag(...args),+ recordInterventionLifecycleCompletion: (...args) =>+ self.recordInterventionLifecycleCompletion(...args),+ refreshMessagesFromDB: (...args) => self.refreshMessagesFromDB(...args),+ releaseOperationLock: (...args) => self.releaseOperationLock(...args),+ resolveAsyncToolOnComplete: (...args) => self.resolveAsyncToolOnComplete(...args),+ resolveAsyncToolResumeParentMessageId: (...args) =>+ self.resolveAsyncToolResumeParentMessageId(...args),+ resolveLastAssistantContentFromThread: (...args) =>+ self.resolveLastAssistantContentFromThread(...args),+ resolveLastAssistantMessageFromDB: (...args) =>+ self.resolveLastAssistantMessageFromDB(...args),+ resolveLlmExecutor: (...args) => self.resolveLlmExecutor(...args),+ restoreClientLlmWait: (...args) => self.restoreClientLlmWait(...args),+ resumeFromClientLlmWait: (...args) => self.resumeFromClientLlmWait(...args),+ revertClientWaitResumeWithRetry: (...args) => self.revertClientWaitResumeWithRetry(...args),+ scheduleContinuation: (...args) => self.scheduleContinuation(...args),+ scheduleGroupMemberTimeout: (...args) => self.scheduleGroupMemberTimeout(...args),+ setQueuedMessages: (...args) => self.setQueuedMessages(...args),+ setupLocalExecutionCallback: (...args) => self.setupLocalExecutionCallback(...args),+ shouldContinueExecution: (...args) => self.shouldContinueExecution(...args),+ shouldReplayPendingInterventionLifecycle: (...args) =>+ self.shouldReplayPendingInterventionLifecycle(...args),+ startExecution: (...args) => self.startExecution(...args),+ startStepLockHeartbeat: (...args) => self.startStepLockHeartbeat(...args),+ tryResumeParentFromAsyncTool: (...args) => self.tryResumeParentFromAsyncTool(...args),+ updateAssistantRowWithRetry: (...args) => self.updateAssistantRowWithRetry(...args),+ usesGatewayMessagePatch: (...args) => self.usesGatewayMessagePatch(...args),+ };+ }++ // ==================== Delegates to the sibling modules ====================+ private startStepLockHeartbeat(...args: MethodArgs<typeof startStepLockHeartbeat>) {+ return startStepLockHeartbeat(this.context, ...args);+ }++ isOperationInterrupted(...args: MethodArgs<typeof isOperationInterrupted>) {+ return isOperationInterrupted(this.context, ...args);+ }++ interruptOperation(...args: MethodArgs<typeof interruptOperation>) {+ return interruptOperation(this.context, ...args);+ }++ acceptsFileWorks(...args: MethodArgs<typeof acceptsFileWorks>) {+ return acceptsFileWorks(this.context, ...args);+ }++ acceptsMemberRuntimeEnd(...args: MethodArgs<typeof acceptsMemberRuntimeEnd>) {+ return acceptsMemberRuntimeEnd(this.context, ...args);+ }++ setQueuedMessages(...args: MethodArgs<typeof setQueuedMessages>) {+ return setQueuedMessages(this.context, ...args);+ }++ private readQueuedMessagesFlag(...args: MethodArgs<typeof readQueuedMessagesFlag>) {+ return readQueuedMessagesFlag(this.context, ...args);+ }++ controlCompletedToolResult(...args: MethodArgs<typeof controlCompletedToolResult>) {+ return controlCompletedToolResult(this.context, ...args);+ }++ scheduleContinuation(...args: MethodArgs<typeof scheduleContinuation>) {+ return scheduleContinuation(this.context, ...args);+ }++ releaseOperationLock(...args: MethodArgs<typeof releaseOperationLock>) {+ return releaseOperationLock(this.context, ...args);+ }++ getOperationStatus(...args: MethodArgs<typeof getOperationStatus>) {+ return getOperationStatus(this.context, ...args);+ }++ startExecution(...args: MethodArgs<typeof startExecution>) {+ return startExecution(this.context, ...args);+ }++ loadInterventionContinuationState(...args: MethodArgs<typeof loadInterventionContinuationState>) {+ return loadInterventionContinuationState(this.context, ...args);+ }++ ensureInterventionContinuationStarted(+ ...args: MethodArgs<typeof ensureInterventionContinuationStarted>+ ) {+ return ensureInterventionContinuationStarted(this.context, ...args);+ }++ private persistInterventionDispatchAck(+ ...args: MethodArgs<typeof persistInterventionDispatchAck>+ ) {+ return persistInterventionDispatchAck(this.context, ...args);+ }++ getPendingInterventions(...args: MethodArgs<typeof getPendingInterventions>) {+ return getPendingInterventions(this.context, ...args);+ }++ processHumanIntervention(...args: MethodArgs<typeof processHumanIntervention>) {+ return processHumanIntervention(this.context, ...args);+ }++ private shouldReplayPendingInterventionLifecycle(+ ...args: Parameters<typeof shouldReplayPendingInterventionLifecycle>+ ) {+ return shouldReplayPendingInterventionLifecycle(...args);+ }++ private recordInterventionLifecycleCompletion(+ ...args: MethodArgs<typeof recordInterventionLifecycleCompletion>+ ) {+ return recordInterventionLifecycleCompletion(this.context, ...args);+ }++ private buildShareAbortResult(...args: MethodArgs<typeof buildShareAbortResult>) {+ return buildShareAbortResult(this.context, ...args);+ }++ createOperation(...args: MethodArgs<typeof createOperation>) {+ return createOperation(this.context, ...args);+ }++ queryUiMessages(...args: MethodArgs<typeof queryUiMessages>) {+ return queryUiMessages(this.context, ...args);+ }++ private usesGatewayMessagePatch(...args: Parameters<typeof usesGatewayMessagePatch>) {+ return usesGatewayMessagePatch(...args);+ }++ private queryMessagesFromDB(...args: MethodArgs<typeof queryMessagesFromDB>) {+ return queryMessagesFromDB(this.context, ...args);+ }++ private refreshMessagesFromDB(...args: MethodArgs<typeof refreshMessagesFromDB>) {+ return refreshMessagesFromDB(this.context, ...args);+ }++ private resolveLastAssistantMessageFromDB(+ ...args: MethodArgs<typeof resolveLastAssistantMessageFromDB>+ ) {+ return resolveLastAssistantMessageFromDB(this.context, ...args);+ }++ private resolveLastAssistantContentFromThread(+ ...args: MethodArgs<typeof resolveLastAssistantContentFromThread>+ ) {+ return resolveLastAssistantContentFromThread(this.context, ...args);+ }++ private queryStepEntryMessages(...args: MethodArgs<typeof queryStepEntryMessages>) {+ return queryStepEntryMessages(this.context, ...args);+ }++ private resolveAsyncToolResumeParentMessageId(+ ...args: Parameters<typeof resolveAsyncToolResumeParentMessageId>+ ) {+ return resolveAsyncToolResumeParentMessageId(...args);+ }++ executeStep(...args: MethodArgs<typeof executeStep>) {+ return executeStep(this.context, ...args);+ }++ tryResumeParentFromAsyncTool(...args: MethodArgs<typeof tryResumeParentFromAsyncTool>) {+ return tryResumeParentFromAsyncTool(this.context, ...args);+ }++ private maybeScheduleAsyncToolVerify(...args: MethodArgs<typeof maybeScheduleAsyncToolVerify>) {+ return maybeScheduleAsyncToolVerify(this.context, ...args);+ }++ private allPendingToolsFulfilled(...args: MethodArgs<typeof allPendingToolsFulfilled>) {+ return allPendingToolsFulfilled(this.context, ...args);+ }++ private resolveAsyncToolOnComplete(...args: MethodArgs<typeof resolveAsyncToolOnComplete>) {+ return resolveAsyncToolOnComplete(this.context, ...args);+ }++ private parkForClientLlm(...args: MethodArgs<typeof parkForClientLlm>) {+ return parkForClientLlm(this.context, ...args);+ }++ resumeFromClientLlmWait(...args: MethodArgs<typeof resumeFromClientLlmWait>) {+ return resumeFromClientLlmWait(this.context, ...args);+ }++ private restoreClientLlmWait(...args: MethodArgs<typeof restoreClientLlmWait>) {+ return restoreClientLlmWait(this.context, ...args);+ }++ private revertClientWaitResumeWithRetry(+ ...args: MethodArgs<typeof revertClientWaitResumeWithRetry>+ ) {+ return revertClientWaitResumeWithRetry(this.context, ...args);+ }++ listClientLlmWaits(...args: MethodArgs<typeof listClientLlmWaits>) {+ return listClientLlmWaits(this.context, ...args);+ }++ private expireClientLlmWait(...args: MethodArgs<typeof expireClientLlmWait>) {+ return expireClientLlmWait(this.context, ...args);+ }++ private endExpiredClientLlmWait(...args: MethodArgs<typeof endExpiredClientLlmWait>) {+ return endExpiredClientLlmWait(this.context, ...args);+ }++ private updateAssistantRowWithRetry(...args: MethodArgs<typeof updateAssistantRowWithRetry>) {+ return updateAssistantRowWithRetry(this.context, ...args);+ }++ private finishClientLlmWaitExpiry(...args: MethodArgs<typeof finishClientLlmWaitExpiry>) {+ return finishClientLlmWaitExpiry(this.context, ...args);+ }++ private publishSubAgentProgress(...args: MethodArgs<typeof publishSubAgentProgress>) {+ return publishSubAgentProgress(this.context, ...args);+ }++ completeSubAgentBridge(...args: MethodArgs<typeof completeSubAgentBridge>) {+ return completeSubAgentBridge(this.context, ...args);+ }++ private isCallSubAgentToolMessage(...args: MethodArgs<typeof isCallSubAgentToolMessage>) {+ return isCallSubAgentToolMessage(this.context, ...args);+ }++ loadGroupMemberBridge(...args: MethodArgs<typeof loadGroupMemberBridge>) {+ return loadGroupMemberBridge(this.context, ...args);+ }++ private countFulfilledMemberAnchors(...args: MethodArgs<typeof countFulfilledMemberAnchors>) {+ return countFulfilledMemberAnchors(this.context, ...args);+ }++ completeGroupActionMember(...args: MethodArgs<typeof completeGroupActionMember>) {+ return completeGroupActionMember(this.context, ...args);+ }++ completeGroupMemberBarrier(...args: MethodArgs<typeof completeGroupMemberBarrier>) {+ return completeGroupMemberBarrier(this.context, ...args);+ }++ scheduleGroupMemberTimeout(...args: MethodArgs<typeof scheduleGroupMemberTimeout>) {+ return scheduleGroupMemberTimeout(this.context, ...args);+ }++ private handleGroupMemberTimeout(...args: MethodArgs<typeof handleGroupMemberTimeout>) {+ return handleGroupMemberTimeout(this.context, ...args);+ }++ private setupLocalExecutionCallback(...args: MethodArgs<typeof setupLocalExecutionCallback>) {+ return setupLocalExecutionCallback(this.context, ...args);+ }++ private resolveLlmExecutor(...args: MethodArgs<typeof resolveLlmExecutor>) {+ return resolveLlmExecutor(this.context, ...args);+ }++ getLlmExecutor(...args: MethodArgs<typeof getLlmExecutor>) {+ return getLlmExecutor(this.context, ...args);+ }++ private createAgentRuntime(...args: MethodArgs<typeof createAgentRuntime>) {+ return createAgentRuntime(this.context, ...args);+ }++ private computeDeviceContext(...args: MethodArgs<typeof computeDeviceContext>) {+ return computeDeviceContext(this.context, ...args);+ }++ private shouldContinueExecution(...args: Parameters<typeof shouldContinueExecution>) {+ return shouldContinueExecution(...args);+ }++ private calculateStepDelay(...args: Parameters<typeof calculateStepDelay>) {+ return calculateStepDelay(...args);+ }++ private calculatePriority(...args: Parameters<typeof calculatePriority>) {+ return calculatePriority(...args);+ }++ private determineCompletionReason(...args: Parameters<typeof determineCompletionReason>) {+ return determineCompletionReason(...args);+ }++ executeSync(...args: MethodArgs<typeof executeSync>) {+ return executeSync(this.context, ...args);+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/intervention.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/intervention.tsnew file mode 100644index 00000000000..c721096dc82--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/intervention.ts@@ -0,0 +1,421 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';++import {+ deriveAgentInterventionQueueDeduplicationId,+ matchesAgentInterventionContinuationProvenance,+} from '@/business/server/agent-run/agentInterventionIdentity';++import { type PendingInterventionsResult } from '../types';+import { INTERVENTION_LIFECYCLE_CHECKPOINT_KEY } from './constants';+import type { AgentRuntimeServiceContext, InterventionLifecycleCheckpoint } from './types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type InterventionDeps = Pick<+ AgentRuntimeServiceContext,+ | 'agentOperationModel'+ | 'baseURL'+ | 'coordinator'+ | 'persistInterventionDispatchAck'+ | 'queueService'+>;++/** Load the authoritative runtime state for a deterministic intervention continuation. */+export async function loadInterventionContinuationState(+ deps: InterventionDeps,+ operationId: string,+): Promise<AgentState | null> {+ return deps.coordinator.loadAgentState(operationId);+}++/**+ * Re-enqueue a continuation whose durable state was written but whose first+ * queue delivery may have been lost with the resolving HTTP process. The+ * operation id and step index are stable, so the ordinary distributed step+ * lock de-duplicates concurrent/repeated schedules.+ */+export async function ensureInterventionContinuationStarted(+ deps: InterventionDeps,+ operationId: string,+): Promise<'already_started' | 'missing' | 'scheduled'> {+ const state = await deps.coordinator.loadAgentState(operationId);+ if (!state) return 'missing';++ const provenance = state.origin?.continuation as+ | {+ resolutionRequestId?: unknown;+ sourceOperationId?: unknown;+ sourceToolMessageIds?: unknown;+ }+ | undefined;+ const preparation = state.metadata?.agentInterventionPreparation as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ stepIndex?: unknown;+ }+ | undefined;+ if (+ typeof provenance?.resolutionRequestId !== 'string' ||+ typeof provenance.sourceOperationId !== 'string' ||+ !Array.isArray(provenance.sourceToolMessageIds) ||+ !provenance.sourceToolMessageIds.every((id) => typeof id === 'string')+ ) {+ throw new Error(`Intervention continuation provenance missing: ${operationId}`);+ }+ if (+ preparation?.state !== 'ready' ||+ preparation.resolutionRequestId !== provenance.resolutionRequestId ||+ typeof preparation.stepIndex !== 'number' ||+ !Number.isSafeInteger(preparation.stepIndex) ||+ preparation.stepIndex < 0+ ) {+ throw new Error(`Intervention continuation is not ready to schedule: ${operationId}`);+ }+ const stepIndex = preparation.stepIndex;+ const deduplicationId = deriveAgentInterventionQueueDeduplicationId(operationId, stepIndex);+ if (preparation.deduplicationId !== deduplicationId) {+ throw new Error(`Intervention continuation dedupe provenance conflict: ${operationId}`);+ }+ const operation = await deps.agentOperationModel.findById(operationId);+ if (+ !operation ||+ !matchesAgentInterventionContinuationProvenance(+ operation.metadata?.agentInterventionContinuation,+ provenance as {+ resolutionRequestId: string;+ sourceOperationId: string;+ sourceToolMessageIds: string[];+ },+ )+ ) {+ throw new Error(`Intervention continuation durable provenance conflict: ${operationId}`);+ }+ const durablePreparation = operation.metadata?.agentInterventionPreparation as+ | {+ deduplicationId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ stepIndex?: unknown;+ }+ | undefined;+ if (+ durablePreparation &&+ (durablePreparation.state !== 'ready' ||+ durablePreparation.resolutionRequestId !== provenance.resolutionRequestId ||+ durablePreparation.stepIndex !== stepIndex ||+ durablePreparation.deduplicationId !== deduplicationId)+ ) {+ throw new Error(`Intervention continuation durable preparation conflict: ${operationId}`);+ }+ if (!durablePreparation) {+ const persisted = await deps.agentOperationModel.recordAgentInterventionPreparation(+ operationId,+ {+ deduplicationId,+ resolutionRequestId: provenance.resolutionRequestId,+ state: 'ready',+ stepIndex,+ },+ );+ if (!persisted) {+ throw new Error(`Failed to backfill intervention preparation: ${operationId}`);+ }+ }+ const dispatchMarker = operation.metadata?.agentInterventionDispatch as+ | {+ deduplicationId?: unknown;+ messageId?: unknown;+ resolutionRequestId?: unknown;+ state?: unknown;+ }+ | undefined;+ if (dispatchMarker) {+ if (+ dispatchMarker.state !== 'scheduled' ||+ dispatchMarker.resolutionRequestId !== provenance.resolutionRequestId ||+ dispatchMarker.deduplicationId !== deduplicationId+ ) {+ throw new Error(`Intervention continuation dispatch marker conflict: ${operationId}`);+ }+ return 'already_started';+ }+ if (!deps.queueService) {+ throw new Error(`Cannot schedule intervention continuation ${operationId}`);+ }++ // Missing provider ACK is never inferred from `state.status`: a worker may+ // have raced the HTTP response and advanced this state to running/terminal.+ // Re-publish with the same provider dedupe key to recover the ACK without a+ // second actual delivery, then persist the authoritative dispatch marker.+ const messageId = await deps.queueService.scheduleMessage({+ context: (state as AgentState & { initialContext: AgentRuntimeContext }).initialContext,+ deduplicationId,+ delay: 0,+ endpoint: `${deps.baseURL}/run`,+ operationId,+ priority: 'high',+ retryDelay:+ typeof state.host?.queue?.retryDelay === 'string' ? state.host?.queue?.retryDelay : undefined,+ retries:+ typeof state.host?.queue?.retries === 'number' ? state.host?.queue?.retries : undefined,+ stepIndex,+ });+ await deps.persistInterventionDispatchAck({+ deduplicationId,+ messageId,+ operationId,+ resolutionRequestId: provenance.resolutionRequestId,+ });++ return 'scheduled';+}++export async function persistInterventionDispatchAck(+ deps: InterventionDeps,+ params: {+ deduplicationId: string;+ messageId: string;+ operationId: string;+ resolutionRequestId: string;+ },+): Promise<void> {+ const marker = {+ deduplicationId: params.deduplicationId,+ messageId: params.messageId,+ resolutionRequestId: params.resolutionRequestId,+ scheduledAt: new Date().toISOString(),+ state: 'scheduled' as const,+ };+ const persisted = await deps.agentOperationModel.recordAgentInterventionDispatch(+ params.operationId,+ marker,+ );+ if (!persisted) {+ throw new Error(`Failed to persist intervention queue ACK: ${params.operationId}`);+ }+}++/**+ * Get list of pending human interventions+ */+export async function getPendingInterventions(+ deps: InterventionDeps,+ params: {+ operationId?: string;+ userId?: string;+ },+): Promise<PendingInterventionsResult> {+ const { operationId, userId } = params;++ try {+ log('Getting pending interventions for operationId: %s, userId: %s', operationId, userId);++ let operations: string[] = [];++ if (operationId) {+ operations = [operationId];+ } else if (userId) {+ // Get all active operations for the user+ try {+ const activeOperations = await deps.coordinator.getActiveOperations();++ // Filter operations belonging to this user+ const userOperations = [];+ for (const operation of activeOperations) {+ try {+ const metadata = await deps.coordinator.getOperationMetadata(operation);+ if (metadata?.userId === userId) {+ userOperations.push(operation);+ }+ } catch (error) {+ log('Failed to get metadata for operation %s: %O', operation, error);+ }+ }+ operations = userOperations;+ } catch (error) {+ log('Failed to get active operations: %O', error);+ operations = [];+ }+ }++ // Check status of each operation+ const pendingInterventions = [];++ for (const operation of operations) {+ try {+ const [state, metadata] = await Promise.all([+ deps.coordinator.loadAgentState(operation),+ deps.coordinator.getOperationMetadata(operation),+ ]);++ if (state?.status === 'waiting_for_human') {+ const intervention: any = {+ lastModified: state.lastModified,+ modelRuntimeConfig: metadata?.modelRuntimeConfig,+ operationId: operation,+ status: state.status,+ stepCount: state.stepCount,+ userId: metadata?.userId,+ };++ // Add specific pending content+ if (state.pendingToolsCalling) {+ intervention.type = 'tool_approval';+ intervention.pendingToolsCalling = state.pendingToolsCalling;+ } else if (state.pendingHumanPrompt) {+ intervention.type = 'human_prompt';+ intervention.pendingHumanPrompt = state.pendingHumanPrompt;+ } else if (state.pendingHumanSelect) {+ intervention.type = 'human_select';+ intervention.pendingHumanSelect = state.pendingHumanSelect;+ }++ pendingInterventions.push(intervention);+ }+ } catch (error) {+ log('Failed to get state for operation %s: %O', operation, error);+ }+ }++ return {+ pendingInterventions,+ timestamp: new Date().toISOString(),+ totalCount: pendingInterventions.length,+ };+ } catch (error) {+ log('Failed to get pending interventions: %O', error);+ throw error;+ }+}++/**+ * Process human intervention+ */+export async function processHumanIntervention(+ deps: InterventionDeps,+ params: {+ action: 'approve' | 'reject' | 'reject_continue' | 'input' | 'select';+ approvedToolCall?: any;+ humanInput?: any;+ operationId: string;+ rejectAndContinue?: boolean;+ rejectionReason?: string;+ stepIndex: number;+ toolMessageId?: string;+ },+): Promise<{ messageId?: string }> {+ const {+ operationId,+ stepIndex,+ action,+ approvedToolCall,+ humanInput,+ rejectAndContinue,+ rejectionReason,+ toolMessageId,+ } = params;++ try {+ log(+ 'Processing human intervention for operation %s:%d (action: %s)',+ operationId,+ stepIndex,+ action,+ );++ // Schedule execution with high priority (if queue service is available)+ let messageId: string | undefined;+ if (deps.queueService) {+ messageId = await deps.queueService.scheduleMessage({+ context: undefined, // Will be retrieved from state manager+ delay: 100,+ endpoint: `${deps.baseURL}/run`,+ operationId,+ payload: {+ approvedToolCall,+ humanInput,+ rejectAndContinue,+ rejectionReason,+ toolMessageId,+ },+ priority: 'high',+ stepIndex,+ });+ log('Scheduled immediate execution for operation %s (messageId: %s)', operationId, messageId);+ } else {+ log('Queue service disabled, skipping schedule for operation %s', operationId);+ }++ return { messageId };+ } catch (error) {+ log('Failed to process human intervention for operation %s: %O', operationId, error);+ throw error;+ }+}++/**+ * Identify a provider redelivery that must replay a completed approval+ * lifecycle instead of being acknowledged as an ordinary stale step.+ *+ * `pendingApprovalBatch` is the durable, sealed runtime marker written before+ * Review publication. The QStash retry header distinguishes a failed request+ * redelivery from a benign duplicate that arrived after a successful ACK.+ */+export function shouldReplayPendingInterventionLifecycle(+ state: AgentState,+ stepIndex: number,+ externalRetryCount: number,+): boolean {+ const checkpoint = state.metadata?.[INTERVENTION_LIFECYCLE_CHECKPOINT_KEY] as+ InterventionLifecycleCheckpoint | undefined;++ return (+ externalRetryCount > 0 &&+ state.status === 'waiting_for_human' &&+ state.pendingApprovalBatch?.sealed === true &&+ // A missing checkpoint is a rollout-compatible pending state. Once a+ // successful lifecycle writes `completed`, a lost HTTP response can be+ // ACKed without publishing the Review or onComplete hook a second time.+ (!checkpoint || (checkpoint.stepIndex === stepIndex && checkpoint.state === 'pending'))+ );+}++/**+ * Checkpoint a fully delivered Review + onComplete lifecycle before the step+ * request returns. This closes the common response-loss window: QStash may+ * redeliver, but the stale-step guard can ACK a completed checkpoint without+ * duplicating either side effect. The Review itself remains batch-idempotent+ * for the smaller crash window before this checkpoint is saved.+ */+export async function recordInterventionLifecycleCompletion(+ deps: InterventionDeps,+ operationId: string,+ state: AgentState,+ stepIndex: number,+): Promise<void> {+ state.metadata = {+ ...state.metadata,+ [INTERVENTION_LIFECYCLE_CHECKPOINT_KEY]: {+ state: 'completed',+ stepIndex,+ } satisfies InterventionLifecycleCheckpoint,+ };++ try {+ await deps.coordinator.saveAgentState(operationId, state);+ } catch (error) {+ // The Review and hook are already delivered. Do not turn a best-effort+ // dedup checkpoint failure into an agent error; a rare later redelivery+ // safely retries the batch-idempotent Review and at-least-once hook.+ log(+ '[%s][%d] Failed to save intervention lifecycle checkpoint: %O',+ operationId,+ stepIndex,+ error,+ );+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.tsnew file mode 100644index 00000000000..31862dacf2a--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts@@ -0,0 +1,347 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { parse } from '@lobechat/conversation-flow';+import { type ChatToolPayload, type UIChatMessage } from '@lobechat/types';++import { hasNonPersistedMessage } from '@/server/modules/AgentRuntime/messagePersistence';+import { FileService } from '@/server/services/file';+import { resolveRunWorkAccessScope } from '@/server/services/workRegistration';++import { resolveMessageFileUrls } from '../../message/resolveMessageFileUrls';+import {+ extractTextFromMessage,+ findLastAssistantMessage,+ normalizeCompletionMessages,+} from '../CompletionLifecycle';+import type { AgentRuntimeServiceContext } from './types';++/** What this module reads off the service. */+export type MessagesDeps = Pick<+ AgentRuntimeServiceContext,+ 'messageModel' | 'messageService' | 'queryMessagesFromDB' | 'serverDB' | 'userId'+>;++/**+ * Query the canonical UIChatMessage[] snapshot for the active topic — the+ * same shape the `message.getMessages` trpc lambda returns to the client.+ * Attached to step_start / agent_runtime_end stream events so the client+ * can use the pushed payload directly instead of refetching from DB.+ *+ * Returns undefined when the topic isn't known yet (e.g. very early in+ * bootstrap before the topic row has been committed) so callers can skip+ * the `uiMessages` field entirely instead of pushing an empty array.+ */+export async function queryUiMessages(+ deps: MessagesDeps,+ agentState: AgentState,+ options?: {+ /**+ * Skip the Work-summary assembly for mid-stream (step_start) snapshots —+ * each step would otherwise re-run the per-type Work queries. Terminal+ * (agent_runtime_end) snapshots keep works so the settled message list+ * carries the round's Work chips. The client preserves previously+ * rendered works when applying a skipped snapshot (`preserveWorks`).+ */+ skipWorks?: boolean;+ },+): Promise<UIChatMessage[] | undefined> {+ 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?.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?.origin?.threadId ?? undefined;+ if (!agentId || !topicId) return undefined;++ // A share visitor's Works are registered under the visitor's share scope+ // (`registerFileWorks`), which the ordinary scope never resolves — without+ // it the terminal snapshot carries no Work card and the visitor only sees+ // it after a reload through `shareChat.getMessages`. The visitor surface+ // always opts in to file Works on that read path, and visitor runs never+ // use message patches, so this snapshot only ever reaches that client.+ const workAccessScope = resolveRunWorkAccessScope({+ shareVisitor: agentState?.principal?.actor?.shareVisitor,+ topicId,+ });+ const isShareVisitorRun = !!workAccessScope;+ // `file` Works stay out of the push unless the receiving client declared+ // it renders them: released desktop builds crash on the unknown type.+ const includeFileWorks = isShareVisitorRun || agentState?.host?.acceptsFileWorks === true;++ try {+ return await deps.messageService.queryMessages(+ {+ agentId,+ groupId,+ ...(includeFileWorks && { includeFileWorks: true }),+ skipWorks: options?.skipWorks,+ threadId,+ topicId,+ },+ // The run's own topic is already resolved and authorized; an agent-share+ // visitor run executes under the CREATOR's identity, so without this the+ // creator-facing exclusion in `MessageModel.query()` returns an EMPTY+ // snapshot for the visitor's topic, and the client applies it as the+ // terminal Source of Truth — wiping the conversation the run just+ // produced. Visitor-facing redaction of the pushed snapshot happens in+ // `GatewayStreamNotifier`.+ { allowShareVisitor: true, ...(workAccessScope && { workAccessScope }) },+ );+ } catch (error) {+ // Stream events must never fail the step. If the DB hiccups, fall back+ // to letting the client refresh as before.+ console.error('[queryUiMessages] Failed to load uiMessages snapshot: %O', error);+ return undefined;+ }+}++/** Native harness + Gateway mux is the only producer of message patches. */+/**+ * Whether this run reconciles the client's message list through+ * `message_patch` revisions instead of pushing whole `uiMessages` snapshots.+ *+ * Decided by the capability the starting client declared when the operation+ * was created (`host.clientProtocol`), NOT by a user preference: the run is+ * delivered to whatever bundle that client is, and a desktop build older than+ * `message_patch` would drop every mid-run reconciliation it was sent.+ *+ * A share visitor is always excluded — the visitor surface has no+ * owner-scoped read to reconcile against.+ */+export function usesGatewayMessagePatch(agentState: AgentState): boolean {+ if (agentState.principal?.actor?.shareVisitor) return false;+ return agentState.host?.clientProtocol === 2;+}++export async function queryMessagesFromDB(deps: MessagesDeps, state: AgentState) {+ let postProcessUrl: ((path: string | null) => Promise<string>) | undefined;+ try {+ const fileService = new FileService(deps.serverDB, deps.userId);+ postProcessUrl = (path: string | null) => fileService.getFullFileUrl(path);+ } catch {+ postProcessUrl = undefined;+ }++ // MODEL, not `messageService.queryMessages`: this read feeds the LLM+ // context and must keep every tool result whole. The service read path may+ // reduce tool payloads to render-facing view models (see+ // `@lobechat/tool-view-model`), which would silently strip the results the+ // model is supposed to remember.+ return deps.messageModel.query(+ {+ 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.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+ // of `query()`'s creator-facing agent-share exclusion.+ { allowShareVisitor: true, postProcessUrl },+ );+}++/**+ * Reload the conversation messages from the database and flatten them for the+ * runtime. Used when resuming a parked op so the next LLM step sees tool+ * results written out-of-band (e.g. by a sub-agent completion bridge).+ */+export async function refreshMessagesFromDB(+ deps: MessagesDeps,+ state: AgentState,+): Promise<AgentState['messages']> {+ const dbMessages = await deps.queryMessagesFromDB(state);++ const { flatList } = parse(dbMessages, undefined, { threadId: state.origin?.threadId });+ return flatList as AgentState['messages'];+}++/**+ * Use conversation-flow to select the active final assistant leaf, then+ * recover that leaf from the original query result. FlatListBuilder moves+ * child metadata onto its display-only group/first child, so the parsed leaf+ * alone cannot reliably identify serialized multimodal content.+ */+export async function resolveLastAssistantMessageFromDB(+ deps: MessagesDeps,+ state: AgentState,+): Promise<unknown> {+ const dbMessages = await deps.queryMessagesFromDB(state);+ const { flatList } = parse(dbMessages, undefined, { threadId: state.origin?.threadId });+ const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(flatList));+ const lastAssistantId = typeof lastAssistant?.id === 'string' ? lastAssistant.id : undefined;++ return (+ (lastAssistantId ? dbMessages.find((message) => message.id === lastAssistantId) : undefined) ??+ lastAssistant+ );+}++/**+ * Fallback content resolution for a heterogeneous (CLI-driven) sub-agent+ * child in queue mode. `coordinator.loadAgentState`/`finalState` is always+ * empty here: a hetero run never writes into the Redis-backed runtime state+ * this class's step loop maintains (only `saveAgentState` calls under the+ * homogeneous step loop populate it), and the completion webhook's+ * `eventFields` deliberately excludes `lastAssistantContent` to keep the+ * QStash payload lean (see `createSubAgentBridgeHook`'s doc comment) —+ * `heteroFinish` already resolves the real answer server-side before+ * dispatching, but that resolution never reaches this callback.+ *+ * The child's own conversation is queryable directly by its isolation+ * `threadId` regardless — the same source `heteroFinish` itself reads via+ * `heteroCurrentMsgId` before completion. Scoping by `threadId` alone is+ * sufficient: thread ids are unique, so no `agentId`/`topicId` is needed to+ * disambiguate.+ */+export async function resolveLastAssistantContentFromThread(+ deps: MessagesDeps,+ threadId: string,+): Promise<string | undefined> {+ const messages = await deps.messageModel.query({ threadId }, { allowShareVisitor: true });+ const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(messages));+ return extractTextFromMessage(lastAssistant) || undefined;+}++/**+ * Overwrite `state.messages` in place with the canonical DB conversation at+ * step entry, making the DB the single source of truth for messages.+ *+ * Guarded against regressions:+ * - Ops carrying a non-persisted (ephemeral / suppressed) message — e.g. the+ * group-member supervisor instruction, which has no DB row — keep their+ * full working set in Redis (see `AgentStateManager.serializeStateForPersist`),+ * so leave the loaded array intact instead of clobbering it with a DB-only+ * view that would drop the prompt.+ * - `state.messages` is guaranteed to end up an array, so a missing-identifier+ * early return or an empty/failed read never hands `undefined` to downstream+ * consumers (e.g. `shouldCompress(state.messages)`).+ * - A populated working set is never replaced with an empty one or on a DB+ * error, so a transient read miss can't blank the conversation mid-op.+ * Reads once for UI, model hydration and same-step device discovery.+ * Undefined rows mean the read was skipped or failed; [] is a successful read.+ */+export async function queryStepEntryMessages(+ deps: MessagesDeps,+ state: AgentState,+): Promise<{+ messages?: UIChatMessage[];+ uiMessages?: UIChatMessage[];+}> {+ if (!Array.isArray(state.messages)) state.messages = [];+ if (!state.origin?.agentId || !state.origin?.topicId) return {};++ let messages: UIChatMessage[];+ try {+ // Keep full tool payloads and raw attachment paths. Each consumer derives+ // its own view; mid-stream Work summaries are not used by the runtime.+ messages = await deps.messageModel.query(+ {+ agentId: state.origin.agentId,+ groupId: state.origin.groupId,+ skipWorks: true,+ threadId: state.origin.threadId,+ topicId: state.origin.topicId,+ },+ { allowShareVisitor: true },+ );+ } catch (error) {+ console.error('[queryStepEntryMessages] Failed to load messages: %O', error);+ return {};+ }++ const [uiResult] = await Promise.all([+ (async () => {+ try {+ return await deps.messageService.prepareUiMessages(messages);+ } catch (error) {+ console.error('[queryStepEntryMessages] Failed to prepare UI messages: %O', error);+ return undefined;+ }+ })(),+ (async () => {+ // Transient/id-less input must not be replaced by persisted history.+ if (hasNonPersistedMessage(state.messages)) return;+ try {+ let fileService: FileService | undefined;+ try {+ fileService = new FileService(deps.serverDB, deps.userId);+ } catch (error) {+ // Match the model read's fallback when file storage is unavailable.+ console.error('[queryStepEntryMessages] File service unavailable: %O', error);+ }+ const resolved = fileService+ ? await resolveMessageFileUrls(messages, (file) => fileService!.getFullFileUrl(file.url))+ : messages;+ const { flatList } = parse(resolved, undefined, { threadId: state.origin?.threadId });+ if (flatList.length > 0) state.messages = flatList as AgentState['messages'];+ } catch (error) {+ console.error('[queryStepEntryMessages] Failed to hydrate runtime messages: %O', error);+ }+ })(),+ ]);+ return { messages, uiMessages: uiResult };+}++export function resolveAsyncToolResumeParentMessageId(+ messages: AgentState['messages'],+ pendingTools: ChatToolPayload[],+): string | undefined {+ const fallbackParentMessageId = messages.at(-1)?.id;+ if (pendingTools.length === 0) return fallbackParentMessageId;++ const toolResultMessageIds = new Map<string, string>();++ const collectToolResultIds = (message: unknown) => {+ if (!message || typeof message !== 'object') return;++ const candidate = message as {+ children?: unknown;+ id?: unknown;+ tool_call_id?: unknown;+ tools?: unknown;+ };++ if (typeof candidate.tool_call_id === 'string' && typeof candidate.id === 'string') {+ toolResultMessageIds.set(candidate.tool_call_id, candidate.id);+ }++ if (Array.isArray(candidate.tools)) {+ for (const tool of candidate.tools) {+ if (!tool || typeof tool !== 'object') continue;++ const toolPayload = tool as { id?: unknown; result_msg_id?: unknown };+ if (typeof toolPayload.id === 'string' && typeof toolPayload.result_msg_id === 'string') {+ toolResultMessageIds.set(toolPayload.id, toolPayload.result_msg_id);+ }+ }+ }++ if (Array.isArray(candidate.children)) {+ for (const child of candidate.children) {+ collectToolResultIds(child);+ }+ }+ };++ for (const message of messages) {+ collectToolResultIds(message);+ }++ for (let index = pendingTools.length - 1; index >= 0; index -= 1) {+ const pendingTool = pendingTools[index];+ if (pendingTool.result_msg_id) return pendingTool.result_msg_id;++ const resultMessageId = toolResultMessageIds.get(pendingTool.id);+ if (resultMessageId) return resultMessageId;+ }++ return fallbackParentMessageId;+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.tsnew file mode 100644index 00000000000..f74103830cd--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts@@ -0,0 +1,509 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { isParkedStatus } from '@lobechat/agent-runtime';+import debug from 'debug';++import { hookDispatcher } from '../hooks';+import {+ controlDeferredToolResult,+ type DeferredToolResultControlInput,+ loadDurableToolResultHooks,+} from '../hooks/deferredToolResultControl';+import {+ type AgentStepContinuation,+ type OperationStatusResult,+ type StartExecutionParams,+ type StartExecutionResult,+} from '../types';+import {+ DEAD_OPERATION_LEASE_MS,+ DURABLE_LEASE_HEARTBEAT_EVERY_TICKS,+ STEP_LOCK_HEARTBEAT_MS,+ STEP_LOCK_TTL_SECONDS,+} from './constants';+import type { AgentRuntimeServiceContext } from './types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type OperationControlDeps = Pick<+ AgentRuntimeServiceContext,+ | 'agentOperationModel'+ | 'baseURL'+ | 'completionLifecycle'+ | 'coordinator'+ | 'endExpiredClientLlmWait'+ | 'messageModel'+ | 'queueService'+ | 'streamManager'+ | 'traceRecorder'+ | 'userId'+ | 'workspaceId'+>;++export function startStepLockHeartbeat(+ deps: OperationControlDeps,+ operationId: string,+ stepIndex: number,+ ownerId: string,+): () => void {+ let heartbeatTick = 0;+ const timer = setInterval(() => {+ heartbeatTick += 1;+ const refreshDurableLease = heartbeatTick % DURABLE_LEASE_HEARTBEAT_EVERY_TICKS === 0;++ Promise.all([+ deps.coordinator.refreshStepLock(operationId, stepIndex, STEP_LOCK_TTL_SECONDS, ownerId),+ refreshDurableLease+ ? deps.agentOperationModel.touchRunning(operationId)+ : Promise.resolve(true),+ ])+ .then(([refreshed, leaseRefreshed]) => {+ if (!refreshed) {+ log(+ '[%s][%d] Step lock heartbeat did not refresh; ownership may have changed',+ operationId,+ stepIndex,+ );+ }+ if (!leaseRefreshed) {+ log(+ '[%s][%d] Durable operation lease was lost; terminal persistence will be rejected',+ operationId,+ stepIndex,+ );+ }+ })+ .catch((error) => {+ log('[%s][%d] Step lock heartbeat failed: %O', operationId, stepIndex, error);+ });+ }, STEP_LOCK_HEARTBEAT_MS);++ const timerWithUnref = timer as { unref?: () => void };+ timerWithUnref.unref?.();++ return () => clearInterval(timer);+}++/**+ * Whether someone already asked this run to stop (the interrupt sentinel is+ * set), even though it may still be finishing its current step.+ */+export async function isOperationInterrupted(+ deps: OperationControlDeps,+ operationId: string,+): Promise<boolean> {+ return deps.coordinator.isInterrupted(operationId);+}++/**+ * Interrupt a running agent operation by setting its state to 'interrupted'.+ * The agent will stop at the next step boundary (cannot abort an in-flight LLM call).+ * Works with both Redis and InMemory state managers via the coordinator abstraction.+ *+ * @returns true if interruption is acknowledged (including an already terminal operation),+ * false if missing runtime state prevents confirming that the operation has stopped.+ */+export async function interruptOperation(+ deps: OperationControlDeps,+ operationId: string,+): Promise<boolean> {+ const state = await deps.coordinator.loadAgentState(operationId);+ if (!state) {+ // Runtime state can expire before the task-topic completion callback lands.+ // Absence alone is not proof of exit (e.g. another in-memory worker owns+ // the run). Only an owned, durably terminal operation can acknowledge it.+ const operation = await deps.agentOperationModel.findById(operationId);+ if (!operation) return false;+ if (['done', 'error', 'interrupted', 'abandoned'].includes(operation.status)) return true;++ // A `running` row with no runtime state whose durable lease stopped+ // refreshing long ago has nothing executing it: the step heartbeat moves+ // `updatedAt` every few minutes while a step is live. Without this, the+ // row stays `running` forever and every stop request on its task is+ // refused as unconfirmed. Retire it atomically — a concurrent heartbeat+ // moves `updatedAt` past the cutoff and wins, keeping a live run alive.+ if (+ operation.status === 'running' &&+ operation.updatedAt &&+ new Date(operation.updatedAt).getTime() < Date.now() - DEAD_OPERATION_LEASE_MS+ ) {+ return deps.agentOperationModel.settleStaleRunning(+ operationId,+ new Date(Date.now() - DEAD_OPERATION_LEASE_MS),+ );+ }+ return false;+ }++ if (state.status === 'done' || state.status === 'error' || state.status === 'interrupted') {+ // A retried stop must be able to settle a stale running task-topic without+ // overwriting the original completion outcome or emitting another stop.+ return true;+ }++ // Sentinel FIRST: the poller and the step-boundary check read only the+ // sentinel, so it must become visible no later than the interrupted+ // state — otherwise a boundary check landing between the two writes+ // reads false and the following saveStepResult clobbers the+ // interruption. Writing it first also keeps failure atomic: if the+ // sentinel write throws, the state below is never marked either, so the+ // two never diverge. A sentinel that lands without the state save+ // (crash between the writes) only stops the op earlier than the record+ // shows — the step-boundary check then persists the interrupted state.+ await deps.coordinator.markInterrupted(operationId);++ const parkedWait = state.status === 'waiting_for_client' ? state.clientLlmWait : undefined;+ const interruptedState: AgentState = {+ ...state,+ ...(state.status === 'waiting_for_client' && { clientLlmWait: undefined }),+ lastModified: new Date().toISOString(),+ status: 'interrupted',+ };+ await deps.coordinator.saveAgentState(operationId, interruptedState);++ // A run parked for a client has no step that would reach a boundary and+ // settle it, so settle it here — otherwise the row and the topic stay live+ // until the wait expires. Its waiting card goes too: nothing can continue it.+ if (state.status === 'waiting_for_client') {+ if (parkedWait?.assistantMessageId) {+ await deps.messageModel+ .update(parkedWait.assistantMessageId, { error: null })+ .catch((error) => log('[%s] Failed to clear the waiting notice: %O', operationId, error));+ }+ if (await deps.agentOperationModel.settleClientWait(operationId, 'interrupted')) {+ await deps.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');+ } else if (parkedWait) {+ // The wait's expiry claimed the row first and has not finished (its+ // Redis state still read this park). Its retry would find the state+ // this Stop just wrote and give up, so finish it here as the row says.+ const row = await deps.agentOperationModel.findById(operationId).catch(() => undefined);+ if (row?.status === 'error') {+ log('[%s] Stop lost to the wait expiry; finishing the expiry', operationId);+ await deps.endExpiredClientLlmWait(operationId, state, parkedWait);+ }+ }+ }++ log('[%s] Operation interrupted', operationId);+ return true;+}++/**+ * Whether the client that started this operation declared it renders `file`+ * Works. An unknown or expired operation reads as `false`, so a continuation+ * then keeps the pushed snapshot every client can render.+ */+export async function acceptsFileWorks(+ deps: OperationControlDeps,+ operationId: string,+): Promise<boolean> {+ try {+ const state = await deps.coordinator.loadAgentState(operationId);+ return state?.host?.acceptsFileWorks === true;+ } catch (error) {+ log('[%s] Failed to read the file Works declaration: %O', operationId, error);+ return false;+ }+}++/**+ * Whether the client that started this operation declared it handles+ * `member_runtime_end`. An unknown or expired operation reads as `false`, so+ * a continuation then keeps the verbatim terminal every client understands.+ */+export async function acceptsMemberRuntimeEnd(+ deps: OperationControlDeps,+ operationId: string,+): Promise<boolean> {+ const metadata = await deps.coordinator.getOperationMetadata(operationId).catch(() => null);+ return metadata?.acceptsMemberRuntimeEnd === true;+}++/**+ * Record whether the client still holds user messages queued behind a run.+ * Only the run's owner may flag it; an unknown or foreign operation is a+ * no-op, so a caller cannot touch another user's run by guessing its id.+ *+ * @returns true when the flag was written+ */+export async function setQueuedMessages(+ deps: OperationControlDeps,+ operationId: string,+ pending: boolean,+): Promise<boolean> {+ const metadata = await deps.coordinator.getOperationMetadata(operationId);+ if (!metadata || metadata.userId !== deps.userId) return false;++ await deps.coordinator.setQueuedMessages(operationId, pending);+ log('[%s] Queued messages flag set to %s', operationId, pending);+ return true;+}++/**+ * Read the queued-messages flag for a step. A failed read keeps the run+ * going: the follow-up still starts once the run ends, exactly as it did+ * before the flag existed, instead of failing the step.+ */+export async function readQueuedMessagesFlag(+ deps: OperationControlDeps,+ operationId: string,+ stepIndex: number,+): Promise<boolean> {+ try {+ return await deps.coordinator.hasQueuedMessages(operationId);+ } catch (error) {+ log('[%s][%d] Queued messages flag read failed: %O', operationId, stepIndex, error);+ return false;+ }+}++/** Review out-of-band results before any subsequent history read can expose them. */+export async function controlCompletedToolResult(+ deps: OperationControlDeps,+ input: DeferredToolResultControlInput,+) {+ const controlled = await controlDeferredToolResult(+ {+ dispatcher: hookDispatcher,+ loadState: (operationId) => deps.coordinator.loadAgentState(operationId),+ loadDurableHooks: (operationId) =>+ loadDurableToolResultHooks(deps.agentOperationModel, operationId),+ messageModel: deps.messageModel,+ userId: deps.userId,+ workspaceId: deps.workspaceId,+ },+ input,+ );+ return controlled;+}++/**+ * Publish a continuation that `executeStep` handed back instead of queueing.+ * The inline step loop calls this when it runs out of invocation budget, so+ * the remaining steps resume in a fresh invocation.+ */+export async function scheduleContinuation(+ deps: OperationControlDeps,+ continuation: AgentStepContinuation,+): Promise<void> {+ if (!deps.queueService) {+ throw new Error(+ `Cannot schedule continuation for ${continuation.operationId}: no queue service`,+ );+ }++ // The steps this invocation inlined are still only in memory — the+ // invocation that picks the run up reads the partial from the store, and+ // the gateway pushes it issued have nothing else to carry them.+ await deps.traceRecorder.flushPartial();+ await deps.streamManager.drainPushes?.(continuation.operationId);++ await deps.queueService.scheduleMessage({+ ...continuation,+ endpoint: `${deps.baseURL}/run`,+ });++ log('[%s] Handed step %d back to the queue', continuation.operationId, continuation.stepIndex);+}++/**+ * Release a lock that was retained across an inline step loop. Owner-scoped,+ * so it is a no-op when this invocation never held the lock.+ */+export async function releaseOperationLock(+ deps: OperationControlDeps,+ operationId: string,+ stepLockOwner: string,+): Promise<void> {+ await deps.coordinator.releaseStepLock(operationId, 0, stepLockOwner);+}++/**+ * Get operation status+ */+export async function getOperationStatus(+ deps: OperationControlDeps,+ params: {+ historyLimit?: number;+ includeHistory?: boolean;+ operationId: string;+ },+): Promise<OperationStatusResult | null> {+ const { operationId, includeHistory = false, historyLimit = 10 } = params;++ try {+ log('Getting operation status for %s', operationId);++ // Get current state and metadata+ const [currentState, operationMetadata] = await Promise.all([+ deps.coordinator.loadAgentState(operationId),+ deps.coordinator.getOperationMetadata(operationId),+ ]);++ // Operation may have expired or does not exist, return null+ if (!currentState || !operationMetadata) {+ log('Operation %s not found (may have expired)', operationId);+ return null;+ }++ // Get execution history (if needed)+ let executionHistory;+ if (includeHistory) {+ try {+ executionHistory = await deps.coordinator.getExecutionHistory(operationId, historyLimit);+ } catch (error) {+ log('Failed to load execution history: %O', error);+ executionHistory = [];+ }+ }++ // Get recent stream events (for debugging)+ let recentEvents;+ if (includeHistory) {+ try {+ recentEvents = await deps.streamManager.getStreamHistory(operationId, 20);+ } catch (error) {+ log('Failed to load recent events: %O', error);+ recentEvents = [];+ }+ }++ // Calculate operation statistics+ const stats = {+ lastActiveTime: operationMetadata.lastActiveAt+ ? Date.now() - new Date(operationMetadata.lastActiveAt).getTime()+ : 0,+ totalCost: currentState.cost?.total || 0,+ totalMessages: currentState.messages?.length || 0,+ totalSteps: currentState.stepCount || 0,+ uptime: operationMetadata.createdAt+ ? Date.now() - new Date(operationMetadata.createdAt).getTime()+ : 0,+ };++ return {+ currentState: {+ cost: currentState.cost,+ costLimit: currentState.costLimit,+ error: currentState.error,+ interruption: currentState.interruption,+ lastModified: currentState.lastModified,+ maxSteps: currentState.maxSteps,+ pendingHumanPrompt: currentState.pendingHumanPrompt,+ pendingHumanSelect: currentState.pendingHumanSelect,+ pendingToolsCalling: currentState.pendingToolsCalling,+ status: currentState.status,+ stepCount: currentState.stepCount,+ usage: currentState.usage,+ },+ executionHistory: executionHistory?.slice(0, historyLimit),+ hasError: currentState.status === 'error',+ isActive: currentState.status === 'running' || isParkedStatus(currentState.status),+ isCompleted: currentState.status === 'done',+ metadata: operationMetadata,+ needsHumanInput: currentState.status === 'waiting_for_human',+ operationId,+ recentEvents: recentEvents?.slice(0, 10),+ stats,+ };+ } catch (error) {+ log('Failed to get operation status for %s: %O', operationId, error);+ throw error;+ }+}++/**+ * Explicitly start operation execution+ */+export async function startExecution(+ deps: OperationControlDeps,+ params: StartExecutionParams,+): Promise<StartExecutionResult> {+ const { operationId, context, priority = 'normal', delay = 50 } = params;++ try {+ log('Starting execution for operation %s', operationId);++ // Check if operation exists+ const operationMetadata = await deps.coordinator.getOperationMetadata(operationId);+ if (!operationMetadata) {+ throw new Error(`Operation ${operationId} not found`);+ }++ // Get current state+ const currentState = await deps.coordinator.loadAgentState(operationId);+ if (!currentState) {+ throw new Error(`Agent state not found for operation ${operationId}`);+ }++ // Check operation status+ if (currentState.status === 'running') {+ throw new Error(`Operation ${operationId} is already running`);+ }++ if (currentState.status === 'done') {+ throw new Error(`Operation ${operationId} is already completed`);+ }++ if (currentState.status === 'error') {+ throw new Error(`Operation ${operationId} is in error state`);+ }++ if (currentState.status === 'interrupted') {+ throw new Error(`Operation ${operationId} is interrupted`);+ }++ // Build execution context+ let executionContext = context;+ if (!executionContext) {+ // If no context provided, build default context from metadata+ // Note: AgentRuntimeContext requires sessionId for compatibility with @lobechat/agent-runtime+ executionContext = {+ payload: {+ isFirstMessage: true,+ message: [{ content: '' }],+ },+ phase: 'user_input' as const,+ session: {+ messageCount: currentState.messages?.length || 0,+ sessionId: operationId,+ status: 'idle' as const,+ stepCount: currentState.stepCount || 0,+ },+ };+ }++ // Update operation status to running+ await deps.coordinator.saveAgentState(operationId, {+ ...currentState,+ lastModified: new Date().toISOString(),+ status: 'running',+ });++ // Schedule execution (if queue service is available)+ let messageId: string | undefined;+ if (deps.queueService) {+ messageId = await deps.queueService.scheduleMessage({+ context: executionContext,+ delay,+ endpoint: `${deps.baseURL}/run`,+ operationId,+ priority,+ stepIndex: currentState.stepCount || 0,+ });+ log('Scheduled execution for operation %s (messageId: %s)', operationId, messageId);+ } else {+ log('Queue service disabled, skipping schedule for operation %s', operationId);+ }++ return {+ messageId,+ operationId,+ scheduled: !!messageId,+ success: true,+ };+ } catch (error) {+ log('Failed to start execution for operation %s: %O', operationId, error);+ throw error;+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.tsnew file mode 100644index 00000000000..8d013da09ea--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts@@ -0,0 +1,290 @@+import type { AgentRunLlmExecutor, AgentState } from '@lobechat/agent-runtime';+import { AgentRuntime, findInMessages, GeneralChatAgent } from '@lobechat/agent-runtime';+import { DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';+import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';+import { getModelPropertyWithFallback } from '@lobechat/model-runtime';+import { type UIChatMessage } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';+import debug from 'debug';++import {+ createRuntimeExecutors,+ type RuntimeExecutorContext,+} from '@/server/modules/AgentRuntime/RuntimeExecutors';+import { LocalQueueServiceImpl } from '@/server/services/queue/impls';+import { createWidgetDryRunAudit } from '@/server/services/widget/dryRunAudit';+import { stateHasEntityFileEdits } from '@/server/services/workRegistration';++import { hookDispatcher } from '../hooks';+import { EVAL_TOOL_FORWARDING_HOOK_ID } from './constants';+import { createEvalToolForwardingHook } from './evalToolForwardingHook';+import type { AgentRuntimeServiceContext } from './types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type RuntimeFactoryDeps = Pick<+ AgentRuntimeServiceContext,+ | 'agentFactory'+ | 'completeGroupMemberBarrier'+ | 'coordinator'+ | 'delegate'+ | 'executeStep'+ | 'messageModel'+ | 'queueService'+ | 'serverDB'+ | 'streamManager'+ | 'toolExecutionService'+ | 'userId'+ | 'workspaceId'+>;++/**+ * Setup execution callback for LocalQueueServiceImpl+ * This breaks the circular dependency by using callback injection+ */+export function setupLocalExecutionCallback(deps: RuntimeFactoryDeps): void {+ if (!deps.queueService) return;++ const impl = deps.queueService.getImpl();+ if (impl instanceof LocalQueueServiceImpl) {+ log('Setting up local execution callback');+ impl.setExecutionCallback(async (operationId, stepIndex, context, payload) => {+ // Mirror the QStash path where payload fields (approvedToolCall,+ // toolMessageId, resumeAsyncTool, …) ride the request body into+ // executeStep. Without this spread, local/in-memory resumes silently+ // lose their intervention/resume signal.+ await deps.executeStep({ context, operationId, stepIndex, ...payload });+ });+ }+}++/**+ * The relay executor a new run carries: the one its client declared, else+ * its parent's, so a child run (group member, `callSubAgent` / `callAgent`+ * sub-agent) on the same local model reaches the same device. No client+ * subscribes to the child's own channel — the gateway only hands+ * `llm_execute` to subscribers of the op it is sent on — so the inherited+ * executor names the channel its tab does listen on: the parent's, or the+ * one the parent already inherited. The parent stays subscribed meanwhile: it+ * is parked (`waiting_for_async_tool`) or supervising its members.+ * Only the caller's own parent in this workspace counts: a client can name+ * any `parentOperationId`, and a foreign run's executor would hand this+ * child's LLM payload to another user's tab, or to a tab of the same user+ * relaying with another workspace's providers.+ * Best-effort: an expired parent leaves the child without one.+ */+export async function resolveLlmExecutor(+ deps: RuntimeFactoryDeps,+ declared: AgentRunLlmExecutor | undefined,+ parentOperationId: string | undefined,+): Promise<AgentRunLlmExecutor | undefined> {+ if (declared) return declared;+ if (!parentOperationId) return;++ let parent: AgentState | null | undefined;+ try {+ parent = await deps.coordinator.loadAgentState(parentOperationId);+ } catch (error) {+ log('[%s] Failed to read the parent relay executor: %O', parentOperationId, error);+ return;+ }+ if (+ parent?.origin?.userId !== deps.userId ||+ (parent.origin.workspaceId ?? undefined) !== (deps.workspaceId ?? undefined)+ )+ return;++ const inherited = parent.host?.llmExecutor;+ if (!inherited) return;++ return {+ ...inherited,+ channelOperationId: inherited.channelOperationId ?? parentOperationId,+ };+}++/**+ * The relay executor an operation carries, e.g. for an approval continuation+ * that the parked operation's client resumes. Best-effort: an unknown or+ * expired operation reads as none.+ */+export async function getLlmExecutor(+ deps: RuntimeFactoryDeps,+ operationId: string,+): Promise<AgentRunLlmExecutor | undefined> {+ try {+ const state = await deps.coordinator.loadAgentState(operationId);+ return state?.host?.llmExecutor;+ } catch (error) {+ log('[%s] Failed to read the relay executor: %O', operationId, error);+ return;+ }+}++/**+ * Create Agent Runtime instance+ */+export async function createAgentRuntime(+ deps: RuntimeFactoryDeps,+ {+ abortSignal,+ agentState,+ operationId,+ stepIndex,+ tracingContextEngine,+ }: {+ /** Cancels in-flight tool work when this step's operation is interrupted. */+ abortSignal?: AbortSignal;+ /**+ * Current runtime state, when the caller has it. Only consulted to decide+ * whether the early final-answer `visible_output_end` must be suppressed+ * (entity-file edits ⇒ completion still has to export + register file+ * Works, so loading should cover that window).+ */+ agentState?: any;+ operationId: string;+ stepIndex: number;+ tracingContextEngine?: (input: unknown, output: unknown, metadata?: unknown) => void;+ },+) {+ const state = agentState as AgentState | undefined;+ const modelRuntimeConfig = state?.modelRuntimeConfig;+ const contextWindowTokens =+ modelRuntimeConfig?.model && modelRuntimeConfig?.provider+ ? await getModelPropertyWithFallback<number | undefined>(+ modelRuntimeConfig.model,+ 'contextWindowTokens',+ modelRuntimeConfig.provider,+ )+ : undefined;++ const world = state?.world;+ const origin = state?.origin;+ const plan = state?.plan;+ const principal = state?.principal;++ // Create Agent instance — use custom factory if provided, otherwise default to GeneralChatAgent+ const generalConfig = {+ agentConfig: world?.agent,+ compressionConfig: {+ enabled: world?.agent?.chatConfig?.enableContextCompression ?? true,+ maxWindowToken: contextWindowTokens ?? undefined,+ },+ dynamicInterventionAudits: {+ ...dynamicInterventionAudits,+ [DASHBOARD_DRY_RUN_AUDIT]: createWidgetDryRunAudit(+ deps.serverDB,+ origin?.userId ?? deps.userId,+ deps.workspaceId,+ ),+ },+ modelRuntimeConfig,+ operationId,+ userId: origin?.userId,+ };++ if (+ origin?.trigger === RequestTrigger.Eval &&+ plan?.eval?.toolForwarding &&+ !hookDispatcher.hasHook(operationId, EVAL_TOOL_FORWARDING_HOOK_ID)+ ) {+ hookDispatcher.register(operationId, [+ createEvalToolForwardingHook(plan.eval.toolForwarding, plan.eval.caseId),+ ]);+ }++ const agent = deps.agentFactory+ ? deps.agentFactory(generalConfig)+ : new GeneralChatAgent(generalConfig);++ // Create streaming executor context+ const executorContext: RuntimeExecutorContext = {+ abortSignal,+ // The factory may be a Graph-aware dispatcher that still returns the+ // default agent for ordinary conversations. Keep the early visible+ // output end behavior tied to the actual agent, not factory presence.+ //+ // Additionally suppressed once the run edited entity-format files:+ // completion still exports + registers them as `file` Works BEFORE the+ // terminal snapshot (see `CompletionLifecycle.registerFileWorks`), and+ // an early hint would end the visible loading seconds before that card+ // can exist. Deferring to the terminal `visible_output_end` lets loading+ // cover the export and the card land with `agent_runtime_end`.+ agentShareVisitor: principal?.actor?.shareVisitor,+ allowEarlyFinalAnswerVisibleOutputEnd:+ agent instanceof GeneralChatAgent && !stateHasEntityFileEdits(agentState),+ botContext: principal?.actor?.bot,+ execSubAgent: deps.delegate.execSubAgent,+ execVirtualSubAgent: deps.delegate.execVirtualSubAgent,+ execGroupMember: deps.delegate.execGroupMember,+ onGroupMemberResult: (params) => deps.completeGroupMemberBarrier(params),+ hookDispatcher,+ loadAgentState: deps.coordinator.loadAgentState.bind(deps.coordinator),+ messageModel: deps.messageModel,+ modelRuntimeConfig,+ operationId,+ serverDB: deps.serverDB,+ stepIndex,+ stream: plan?.stream,+ streamManager: deps.streamManager,+ toolExecutionService: deps.toolExecutionService,+ topicId: origin?.topicId,+ tracingContextEngine,+ userId: origin?.userId,+ workspaceId: deps.workspaceId,+ };++ // Create Agent Runtime instance+ const runtime = new AgentRuntime(agent as any, {+ executors: createRuntimeExecutors(executorContext),+ });++ return { agent, runtime };+}++/**+ * Compute device context from DB messages at step boundary.+ * Uses findInMessages visitor to scan tool messages for device activation.+ */+export async function computeDeviceContext(+ deps: RuntimeFactoryDeps,+ state: any,+ entryMessages?: UIChatMessage[],+) {+ try {+ const dbMessages =+ entryMessages ??+ (await deps.messageModel.query(+ {+ 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.origin?.groupId,+ threadId: state.origin?.threadId,+ topicId: state.origin?.topicId,+ },+ { allowShareVisitor: true },+ ));++ return findInMessages(+ dbMessages,+ (msg) => {+ const activeDeviceId = msg.pluginState?.metadata?.activeDeviceId;+ if (activeDeviceId) {+ return {+ activeDeviceId,+ devicePlatform: msg.pluginState?.metadata?.devicePlatform as string | undefined,+ deviceSystemInfo: msg.pluginState?.metadata?.deviceSystemInfo as+ Record<string, string> | undefined,+ };+ }+ },+ { role: 'tool' },+ );+ } catch (error) {+ log('computeDeviceContext error: %O', error);+ }++ return undefined;+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/shareRunGate.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/shareRunGate.tsnew file mode 100644index 00000000000..ae3262d9b03--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/shareRunGate.ts@@ -0,0 +1,68 @@+import type { AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';++import { type AgentExecutionResult } from '../types';+import type { AgentRuntimeServiceContext } from './types';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type ShareRunGateDeps = Pick<+ AgentRuntimeServiceContext,+ 'completionLifecycle' | 'coordinator' | 'interruptOperation'+>;++/**+ * Terminate an Agent Share visitor run whose authorization was revoked+ * mid-flight (see the per-step check in `executeStep`).+ *+ * Persists `interrupted` onto the already-loaded state — the same terminal+ * status a visitor's own Stop produces — so the client's stream settles+ * normally instead of hanging. Falls back to `interruptOperation` when no+ * state was readable. A persistence failure is logged, never rethrown: the+ * run must stop regardless of whether the terminal status could be written.+ *+ * The completion lifecycle (`emitSignalEvents` + `dispatchHooks`) must run+ * here too: this abort short-circuits `executeStep` before `runtime.step()`,+ * so no downstream path is left to persist the terminal status. Without it+ * `saveAgentState` would only update the runtime-state cache and publish the+ * terminal stream event, leaving `agent_operations` stuck on `running` —+ * which `TopicModel.tryReserveTaskCallback` then reads as a live run and+ * blocks the visitor's next send on that topic for the abandoned-run TTL.+ */+export async function buildShareAbortResult(+ deps: ShareRunGateDeps,+ operationId: string,+ state: AgentState | null | undefined,+): Promise<AgentExecutionResult> {+ log('[%s] Aborting share visitor run — the share is no longer authorized', operationId);++ try {+ if (state) {+ const interruptedState: AgentState = {+ ...state,+ lastModified: new Date().toISOString(),+ status: 'interrupted',+ };+ await deps.coordinator.saveAgentState(operationId, interruptedState);++ await deps.completionLifecycle.emitSignalEvents(operationId, interruptedState, 'interrupted');+ await deps.completionLifecycle.dispatchHooks(operationId, interruptedState, 'interrupted');+ } else {+ await deps.interruptOperation(operationId);+ }+ } catch (error) {+ log(+ '[%s] Failed to persist interrupted state for an aborted share run: %O',+ operationId,+ error,+ );+ }++ return {+ nextStepScheduled: false,+ state: { status: 'interrupted' },+ stepResult: null,+ success: false,+ };+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/stepPolicy.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/stepPolicy.tsnew file mode 100644index 00000000000..b7e5b6c7ae6--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/stepPolicy.ts@@ -0,0 +1,94 @@+import type { AgentState } from '@lobechat/agent-runtime';++import { type StepCompletionReason } from '../types';++/**+ * Decide whether to continue execution+ */+export function shouldContinueExecution(state: any, context?: any): boolean {+ // Completed+ if (state.status === 'done') return false;++ // Needs human intervention+ if (state.status === 'waiting_for_human') return false;++ // Parked waiting for an async tool result (client tool / sub-agent)+ if (state.status === 'waiting_for_async_tool') return false;++ // Parked waiting for a client to run the next LLM call+ if (state.status === 'waiting_for_client') return false;++ // Error occurred+ if (state.status === 'error') return false;++ // Interrupted+ if (state.status === 'interrupted') return false;++ // maxSteps is handled by runtime.step() which sets forceFinish → status:'done'+ // No redundant check here — trust the runtime state machine++ // Exceeded cost limit+ if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) {+ return state.costLimit.onExceeded !== 'stop';+ }++ // No next context+ if (!context) return false;++ return true;+}++/**+ * Calculate step delay+ */+export function calculateStepDelay(stepResult: any): number {+ const baseDelay = 50;++ // If there are tool calls, add longer delay+ if (stepResult.events?.some((e: any) => e.type === 'tool_result')) {+ return baseDelay + 50;+ }++ // If there are errors, use exponential backoff+ if (stepResult.events?.some((e: any) => e.type === 'error')) {+ return Math.min(baseDelay * 2, 1000);+ }++ return baseDelay;+}++/**+ * Calculate priority+ */+export function calculatePriority(stepResult: any): 'high' | 'normal' | 'low' {+ // If human intervention needed, high priority+ if (stepResult.newState?.status === 'waiting_for_human') {+ return 'high';+ }++ // If there are errors, normal priority+ if (stepResult.events?.some((e: any) => e.type === 'error')) {+ return 'normal';+ }++ return 'normal';+}++/**+ * Determine operation completion reason+ */+export function determineCompletionReason(state: AgentState): StepCompletionReason {+ if (state.status === 'error') return 'error';+ if (state.status === 'interrupted') return 'interrupted';+ if (state.status === 'waiting_for_human') return 'waiting_for_human';+ if (state.status === 'waiting_for_async_tool') return 'waiting_for_async_tool';+ if (state.status === 'waiting_for_client') return 'waiting_for_client';+ // Checked ahead of 'done' on purpose: a run the repeat guard cut short ends+ // in exactly that status, having emitted a turn with no tool calls. Reading+ // it as a plain 'done' is what made these runs uncountable.+ if (state.toolCallRepeatGuard?.stoppedByRepeatLimit) return 'tool_call_repeat_limit';+ if (state.status === 'done') return 'done';+ if (state.maxSteps && state.stepCount >= state.maxSteps) return 'max_steps';+ if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) return 'cost_limit';+ return 'done';+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.tsnew file mode 100644index 00000000000..74b2e693f89--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/subAgentBridge.ts@@ -0,0 +1,247 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { appendSubAgentReference, isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';+import debug from 'debug';++import {+ extractTextFromMessage,+ findLastAssistantMessage,+ normalizeCompletionMessages,+} from '../CompletionLifecycle';+import { type SubAgentBridgeParams } from '../types';+import type { AgentRuntimeServiceContext } from './types';+import { formatErrorForMetadata, formatSubAgentErrorReason } from './utils';++const log = debug('lobe-server:agent-runtime-service');++/** What this module reads off the service. */+export type SubAgentBridgeDeps = Pick<+ AgentRuntimeServiceContext,+ | 'controlCompletedToolResult'+ | 'coordinator'+ | 'isCallSubAgentToolMessage'+ | 'messageModel'+ | 'resolveLastAssistantContentFromThread'+ | 'resolveLastAssistantMessageFromDB'+ | 'streamManager'+ | 'tryResumeParentFromAsyncTool'+>;++/**+ * Stream a `callSubAgent` child's running totals to the client, once per step.+ *+ * Addressed to the PARENT's operationId, not the child's: the client opens one+ * WebSocket per operation and never subscribes to the child's channel. The+ * parent's channel is still live because parking at `waiting_for_async_tool`+ * deliberately does not publish a stream-end event (see+ * `AgentRuntimeCoordinator.STREAM_END_STATUSES`).+ *+ * Rides `step_complete` rather than a new event type because `AgentStreamEventType`+ * is a closed union shared with the out-of-repo gateway worker; `phase` is the+ * established discriminator and unknown phases are ignored by older clients.+ *+ * The three stat fields are read from exactly the same state paths that+ * `completeSubAgentBridge` uses for its final backfill, so the live numbers+ * converge on the persisted ones instead of jumping when the run ends.+ *+ * Best-effort: a publish failure must not fail the sub-agent's step.+ */+export async function publishSubAgentProgress(+ deps: SubAgentBridgeDeps,+ state: AgentState,+ stepIndex: number,+): Promise<void> {+ const anchor = state?.origin?.lineage?.progressAnchor as+ { parentOperationId: string; toolMessageId: string } | undefined;+ if (!anchor?.parentOperationId || !anchor.toolMessageId) return;++ try {+ await deps.streamManager.publishStreamEvent(anchor.parentOperationId, {+ data: {+ model: state?.modelRuntimeConfig?.model,+ phase: 'subagent_progress',+ toolMessageId: anchor.toolMessageId,+ totalCost: state?.cost?.total,+ totalInputTokens: state?.usage?.llm?.tokens?.input,+ totalOutputTokens: state?.usage?.llm?.tokens?.output,+ totalTokens: state?.usage?.llm?.tokens?.total,+ totalToolCalls: state?.usage?.tools?.totalCalls,+ },+ stepIndex,+ type: 'step_complete',+ });+ } catch (error) {+ log('[%s] failed to publish sub-agent progress (non-fatal): %O', state?.operationId, error);+ }+}++/**+ * Sub-agent completion bridge for the server `callSubAgent` deferred-tool+ * path. Runs when a child sub-agent op reaches a terminal state — invoked+ * in-process by the child's `onComplete` hook handler (local mode) or via+ * the QStash-delivered `/webhooks/subagent-callback` endpoint (queue mode,+ * where in-memory handler hooks don't survive cross-process steps).+ *+ * 1. Backfill the parent's placeholder tool message with the sub-agent's+ * final answer (success) or an error note (failure), plus pluginState+ * so the UI render can resolve the isolation thread.+ * 2. Resume the parked parent: barrier-check + CAS via+ * `tryResumeParentFromAsyncTool`, arming the delayed verify when the+ * parent isn't resumable yet.+ *+ * THROWS on infrastructure failure of either half (state load, backfill,+ * resume) so the queue-mode callback returns non-2xx and QStash redelivers+ * the whole bridge — the delayed verify alone cannot recover a failed+ * backfill, it only re-reads the barrier. Redelivery is safe: the backfill+ * rewrites the same content and the resume is CAS-guarded.+ *+ * Returns true when this call won the resume CAS.+ */+export async function completeSubAgentBridge(+ deps: SubAgentBridgeDeps,+ params: SubAgentBridgeParams,+): Promise<boolean> {+ const { operationId, parentOperationId, reason, threadId, toolMessageId } = params;+ const failed = reason === 'error' || reason === 'interrupted';++ // Infra errors propagate; a null state (expired) degrades to a stub note.+ const finalState =+ params.finalState ?? (await deps.coordinator.loadAgentState(operationId)) ?? undefined;++ log(+ '[%s] sub-agent bridge → parent %s (reason: %s, state: %s)',+ operationId,+ parentOperationId,+ reason,+ finalState ? 'loaded' : 'missing',+ );++ // 1. Backfill the placeholder tool message with the result.+ // `updateToolMessage` swallows transaction errors into `success: false`,+ // so the flag must be checked — an unfulfilled message would hold the+ // parent's barrier forever while the callback acked with 200.+ //+ // A state loaded via the fallback above arrives without `messages` (the+ // persisted Redis blob no longer carries them — see+ // AgentStateManager.serializeStateForPersist). Resolve the final leaf from+ // the parsed DB conversation, then recover the original row by id so its+ // serialized content stays paired with metadata.isMultimodal. An in-process+ // params.finalState already carries messages and skips this query.+ let lastAssistant: unknown;+ if (!failed && finalState && !Array.isArray(finalState.messages)) {+ try {+ lastAssistant = await deps.resolveLastAssistantMessageFromDB(finalState);+ } catch (error) {+ console.error(+ '[%s] sub-agent bridge: failed to resolve final assistant from DB: %O',+ operationId,+ error,+ );+ }+ }+ const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];+ lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));+ let lastAssistantContent = extractTextFromMessage(lastAssistant);++ // Gated on `!finalState`, not merely an empty `lastAssistantContent`: a+ // real (authoritative) final state whose last turn is legitimately+ // textless (image-only, or the "preserve an empty leaf" case in+ // `normalizeCompletionMessages`) must keep the stub below, not go dig+ // through the thread's own message history — a lagging read could+ // surface an EARLIER real reply from the same thread and silently show+ // stale text instead of the correct empty-answer signal. `!finalState`+ // is exactly the case this fallback exists for: heterogeneous (CLI-driven)+ // children never populate it at all (see+ // `resolveLastAssistantContentFromThread`'s doc comment), so there is no+ // authoritative signal here to override.+ if (!failed && !finalState && threadId) {+ try {+ lastAssistantContent = await deps.resolveLastAssistantContentFromThread(threadId);+ } catch (error) {+ console.error(+ '[%s] sub-agent bridge: failed to resolve content from thread %s: %O',+ operationId,+ threadId,+ error,+ );+ }+ }+ const errorReason = failed+ ? formatSubAgentErrorReason(finalState?.error ?? params.errorMessage)+ : undefined;+ const resultContent = failed+ ? errorReason+ ? `Sub-agent did not complete (${reason}): ${errorReason}`+ : `Sub-agent did not complete (${reason}).`+ : lastAssistantContent || 'Sub-agent completed without a textual answer.';+ // callSubAgent results carry the sub-agent id so the parent can later send+ // this same sub-agent a follow-up (`callSubAgent({ subAgentId })`) — e.g.+ // to hand over what it gathered before failing — instead of redoing it.+ const content = (await deps.isCallSubAgentToolMessage(toolMessageId, threadId))+ ? appendSubAgentReference(resultContent, threadId)+ : resultContent;++ const { result: completed, blocked } = await deps.controlCompletedToolResult({+ preserveUsage: true,+ operationId: parentOperationId,+ toolMessageId,+ result: {+ content,+ success: !failed,+ error: failed ? formatErrorForMetadata(finalState?.error ?? params.errorMessage) : undefined,+ state: {+ model: finalState?.modelRuntimeConfig?.model,+ status: failed ? 'error' : 'completed',+ threadId,+ // The child's spend rides on this anchor row so the parent's usage tray can+ // account for it. The tray sums per-MESSAGE usage, and the child's own+ // assistant messages live in an isolation thread the parent never loads —+ // this row is the only place the child's cost surfaces in the parent's own+ // message list.+ totalCost: finalState?.cost?.total,+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,+ totalToolCalls: finalState?.usage?.tools?.totalCalls,+ totalTokens: finalState?.usage?.llm?.tokens?.total,+ },+ },+ });+ const backfill = await deps.messageModel.updateToolMessage(toolMessageId, {+ content: completed.content,+ pluginError: completed.error ?? null,+ pluginState: completed.state,+ onlyIfEmpty: true,+ ...(blocked && { replacePluginState: true }),+ });+ if (!backfill.success) {+ throw new Error(+ `Sub-agent bridge: failed to backfill tool message ${toolMessageId} for parent ${parentOperationId}`,+ );+ }++ // 2. Barrier + CAS + resume the parent op (infra errors propagate too).+ // Pass the just-backfilled message id so the barrier trusts this write+ // instead of re-reading a possibly-stale replica.+ return deps.tryResumeParentFromAsyncTool(+ { parentOperationId },+ { knownFulfilledMessageId: toolMessageId, scheduleVerifyOnHold: true },+ );+}++/**+ * Whether the bridged placeholder belongs to `lobe-agent.callSubAgent` (the+ * same bridge also serves `callAgent`, whose children cannot be continued).+ * Best-effort: a failed lookup only drops the id trailer, never the bridge.+ */+export async function isCallSubAgentToolMessage(+ deps: SubAgentBridgeDeps,+ toolMessageId: string,+ threadId: string | undefined,+): Promise<boolean> {+ if (!threadId) return false;+ try {+ return isCallSubAgentCall(await deps.messageModel.findMessagePlugin(toolMessageId));+ } catch (error) {+ log('[%s] sub-agent bridge: failed to read tool plugin: %O', toolMessageId, error);+ return false;+ }+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.tsnew file mode 100644index 00000000000..c7a8cfb4b42--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts@@ -0,0 +1,325 @@+import type { Agent, GeneralAgentConfig } from '@lobechat/agent-runtime';+import type { ISnapshotStore } from '@lobechat/agent-tracing';+import {+ type ExecSubAgentParams,+ type ExecSubAgentResult,+ type ExecVirtualSubAgentParams,+} from '@lobechat/types';++import type { AgentOperationModel } from '@/database/models/agentOperation';+import type { MessageModel } from '@/database/models/message';+import type { LobeChatDatabase } from '@/database/type';+import type {+ AgentRuntimeCoordinator,+ AgentRuntimeCoordinatorOptions,+} from '@/server/modules/AgentRuntime';+import type { IStreamEventManager } from '@/server/modules/AgentRuntime/types';+import type { MessageService } from '@/server/services/message';+import type { QueueService } from '@/server/services/queue';+import type { ToolExecutionService } from '@/server/services/toolExecution';++import type { CompletionLifecycle } from '../CompletionLifecycle';+import type { HumanInterventionHandler } from '../HumanInterventionHandler';+import type { OperationTraceRecorder } from '../OperationTraceRecorder';+import { type ExecGroupMemberParams, type ExecGroupMemberResult } from '../types';+import type {+ allPendingToolsFulfilled,+ maybeScheduleAsyncToolVerify,+ resolveAsyncToolOnComplete,+ tryResumeParentFromAsyncTool,+} from './asyncTool';+import type {+ endExpiredClientLlmWait,+ expireClientLlmWait,+ finishClientLlmWaitExpiry,+ listClientLlmWaits,+ parkForClientLlm,+ restoreClientLlmWait,+ resumeFromClientLlmWait,+ revertClientWaitResumeWithRetry,+ updateAssistantRowWithRetry,+} from './clientLlmWait';+import type { createOperation } from './createOperation';+import type { executeStep } from './executeStep/index';+import type { executeSync } from './executeSync';+import type {+ completeGroupActionMember,+ completeGroupMemberBarrier,+ countFulfilledMemberAnchors,+ handleGroupMemberTimeout,+ loadGroupMemberBridge,+ scheduleGroupMemberTimeout,+} from './groupMember';+import type {+ ensureInterventionContinuationStarted,+ getPendingInterventions,+ loadInterventionContinuationState,+ persistInterventionDispatchAck,+ processHumanIntervention,+ recordInterventionLifecycleCompletion,+ shouldReplayPendingInterventionLifecycle,+} from './intervention';+import type {+ queryMessagesFromDB,+ queryStepEntryMessages,+ queryUiMessages,+ refreshMessagesFromDB,+ resolveAsyncToolResumeParentMessageId,+ resolveLastAssistantContentFromThread,+ resolveLastAssistantMessageFromDB,+ usesGatewayMessagePatch,+} from './messages';+import type {+ acceptsFileWorks,+ acceptsMemberRuntimeEnd,+ controlCompletedToolResult,+ getOperationStatus,+ interruptOperation,+ isOperationInterrupted,+ readQueuedMessagesFlag,+ releaseOperationLock,+ scheduleContinuation,+ setQueuedMessages,+ startExecution,+ startStepLockHeartbeat,+} from './operationControl';+import type {+ computeDeviceContext,+ createAgentRuntime,+ getLlmExecutor,+ resolveLlmExecutor,+ setupLocalExecutionCallback,+} from './runtimeFactory';+import type { buildShareAbortResult } from './shareRunGate';+import type {+ calculatePriority,+ calculateStepDelay,+ determineCompletionReason,+ shouldContinueExecution,+} from './stepPolicy';+import type {+ completeSubAgentBridge,+ isCallSubAgentToolMessage,+ publishSubAgentProgress,+} from './subAgentBridge';++export interface InterventionLifecycleCheckpoint {+ state: 'completed' | 'pending';+ stepIndex: number;+}++/**+ * Operations the runtime delegates UP to its owning layer (AiAgentService).+ *+ * The dependency arrow is one-way: AiAgentService → AgentRuntimeService. The+ * runtime is the low-level step executor — it cannot resolve agent configs,+ * build tool engines, manage threads, or run the full `execAgent` pipeline;+ * those live in the layer above it. Yet some tools (e.g. `lobe-agent.callSubAgent`)+ * need exactly such a high-level action *mid-step*. Rather than import+ * AiAgentService (which would be a circular dependency), the runtime delegates+ * these operations back to its owner through callbacks injected here.+ *+ * Convention: every future "the runtime, mid-execution, must trigger a+ * higher-layer pipeline" capability belongs on this delegate — not as a loose+ * top-level option. One named home for the whole upward-call surface.+ */+export interface AgentRuntimeDelegate {+ /**+ * Fork a group member ("call agent member") under a `lobe-group-management`+ * tool call. Handles both in-group (non-isolated, shared group session) and+ * isolated members, installing the group-action member completion bridge that+ * enforces the K=N member barrier before resuming/finishing the supervisor.+ */+ execGroupMember?: (params: ExecGroupMemberParams) => Promise<ExecGroupMemberResult>;+ /**+ * Run a legacy agent invocation through the full high-level pipeline+ * (AiAgentService.execSubAgent → execAgent: agent-config resolution, tool+ * engine, context engineering, createOperation).+ */+ execSubAgent?: (params: ExecSubAgentParams) => Promise<ExecSubAgentResult>;+ /**+ * Fork a `lobe-agent.callSubAgent` virtual child run. The child is marked as a+ * sub-agent and owns the completion bridge that backfills the parent tool+ * placeholder before resuming the parked parent operation.+ */+ execVirtualSubAgent?: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;+ /**+ * Re-check that an Agent Share visitor run is STILL authorized to continue,+ * called on EVERY step. Without it, a revocation that lands mid-run (link →+ * private, share disabled, agent deleted) would only stop NEW requests: the+ * already-created operation keeps its tool snapshot and gateway channel and+ * keeps running under the CREATOR's credentials and budget, unstoppable by+ * the visitor (whose Stop button re-resolves the now-private share and gets+ * `FORBIDDEN`). Re-checking at every step boundary means a revocation always+ * takes effect within one step, with no durable interrupt-retry machinery.+ *+ * Implemented by AiAgentService via `AgentShareModel.isRunStillAuthorized`.+ * Returns `false` (not a throw) for an ordinary "no longer authorized"+ * outcome; the caller treats a THROWN error the same as `false` — fail+ * closed, never fail open.+ */+ verifyShareRunStillAuthorized?: (params: {+ agentId: string;+ shareId: string;+ }) => Promise<boolean>;+}++export interface AgentRuntimeServiceOptions {+ /**+ * Custom agent factory. When provided, this function is called instead of+ * the default `new GeneralChatAgent(config)` to create the Agent instance.+ * This allows injecting alternative Agent implementations (e.g. GraphAgent)+ * without the service needing to know about them.+ */+ agentFactory?: (config: GeneralAgentConfig) => Agent;+ /**+ * Coordinator configuration options+ * Allows injection of custom stateManager and streamEventManager+ */+ coordinatorOptions?: AgentRuntimeCoordinatorOptions;+ /**+ * Operations the runtime delegates up to its owning layer. See+ * {@link AgentRuntimeDelegate}. Injected by AiAgentService so the runtime can+ * trigger high-level pipelines (e.g. sub-agent forking) mid-step without a+ * circular import.+ */+ delegate?: AgentRuntimeDelegate;+ /**+ * Opt IN to agent-share visitor rows for the models this service owns.+ * Reserved for share-runtime entry points that drive a visitor turn under+ * the CREATOR's `userId`. Defaults to false. See+ * {@link import('@/database/models/message').MessageModelOptions}.+ */+ includeShareVisitor?: boolean;+ /**+ * Custom QueueService+ * Set to null to disable queue scheduling (for synchronous execution tests)+ */+ queueService?: QueueService | null;+ /**+ * Optional snapshot store for persisting agent execution traces.+ * When provided, execution snapshots are recorded on every step and finalized on completion.+ * In dev mode without this option, falls back to FileSnapshotStore automatically.+ */+ snapshotStore?: ISnapshotStore;+ /**+ * Custom StreamEventManager+ * Defaults to Redis-based StreamEventManager+ * Can pass InMemoryStreamEventManager in test environments+ */+ streamEventManager?: IStreamEventManager;+ /**+ * Workspace id for scoping all DB reads/writes (messages, agent_operations).+ * Falls back to user-personal scope when omitted.+ */+ workspaceId?: string;+}++/**+ * Agent Runtime Service+ * Encapsulates Agent execution logic and provides a unified service interface+ *+ * Supports dependency injection for testing with in-memory implementations:+ * ```ts+ * // Production environment (uses Redis by default)+ * const service = new AgentRuntimeService(db, userId);+ *+ * // Test environment+ * const service = new AgentRuntimeService(db, userId, {+ * streamEventManager: new InMemoryStreamEventManager(),+ * queueService: null, // Disable queue, use executeSync+ * });+ * ```+ */++/** A sibling-module function's arguments after the service it runs against. */+export type MethodArgs<F> = F extends (svc: any, ...args: infer A) => any ? A : never;++/** A sibling-module function bound to the service it runs against. */+type Bound<F> = F extends (svc: any, ...args: infer A) => infer R ? (...args: A) => R : never;++/**+ * What the sibling modules read off the service: its collaborators and the+ * methods they call back into. The service hands each module this view (each+ * module picks the members it uses), so the members stay private on the class.+ */+export interface AgentRuntimeServiceContext {+ acceptsFileWorks: Bound<typeof acceptsFileWorks>;+ acceptsMemberRuntimeEnd: Bound<typeof acceptsMemberRuntimeEnd>;+ readonly agentFactory: ((config: GeneralAgentConfig) => Agent) | undefined;+ readonly agentOperationModel: AgentOperationModel;+ allPendingToolsFulfilled: Bound<typeof allPendingToolsFulfilled>;+ readonly baseURL: string;+ buildShareAbortResult: Bound<typeof buildShareAbortResult>;+ calculatePriority: typeof calculatePriority;+ calculateStepDelay: typeof calculateStepDelay;+ completeGroupActionMember: Bound<typeof completeGroupActionMember>;+ completeGroupMemberBarrier: Bound<typeof completeGroupMemberBarrier>;+ completeSubAgentBridge: Bound<typeof completeSubAgentBridge>;+ readonly completionLifecycle: CompletionLifecycle;+ computeDeviceContext: Bound<typeof computeDeviceContext>;+ controlCompletedToolResult: Bound<typeof controlCompletedToolResult>;+ readonly coordinator: AgentRuntimeCoordinator;+ countFulfilledMemberAnchors: Bound<typeof countFulfilledMemberAnchors>;+ createAgentRuntime: Bound<typeof createAgentRuntime>;+ createOperation: Bound<typeof createOperation>;+ readonly delegate: AgentRuntimeDelegate;+ determineCompletionReason: typeof determineCompletionReason;+ endExpiredClientLlmWait: Bound<typeof endExpiredClientLlmWait>;+ ensureInterventionContinuationStarted: Bound<typeof ensureInterventionContinuationStarted>;+ executeStep: Bound<typeof executeStep>;+ executeSync: Bound<typeof executeSync>;+ expireClientLlmWait: Bound<typeof expireClientLlmWait>;+ finishClientLlmWaitExpiry: Bound<typeof finishClientLlmWaitExpiry>;+ getLlmExecutor: Bound<typeof getLlmExecutor>;+ getOperationStatus: Bound<typeof getOperationStatus>;+ getPendingInterventions: Bound<typeof getPendingInterventions>;+ handleGroupMemberTimeout: Bound<typeof handleGroupMemberTimeout>;+ readonly humanIntervention: HumanInterventionHandler;+ interruptOperation: Bound<typeof interruptOperation>;+ isCallSubAgentToolMessage: Bound<typeof isCallSubAgentToolMessage>;+ isOperationInterrupted: Bound<typeof isOperationInterrupted>;+ listClientLlmWaits: Bound<typeof listClientLlmWaits>;+ loadGroupMemberBridge: Bound<typeof loadGroupMemberBridge>;+ loadInterventionContinuationState: Bound<typeof loadInterventionContinuationState>;+ maybeScheduleAsyncToolVerify: Bound<typeof maybeScheduleAsyncToolVerify>;+ readonly messageModel: MessageModel;+ readonly messageService: MessageService;+ parkForClientLlm: Bound<typeof parkForClientLlm>;+ persistInterventionDispatchAck: Bound<typeof persistInterventionDispatchAck>;+ processHumanIntervention: Bound<typeof processHumanIntervention>;+ publishSubAgentProgress: Bound<typeof publishSubAgentProgress>;+ queryMessagesFromDB: Bound<typeof queryMessagesFromDB>;+ queryStepEntryMessages: Bound<typeof queryStepEntryMessages>;+ queryUiMessages: Bound<typeof queryUiMessages>;+ readonly queueService: QueueService | null;+ readQueuedMessagesFlag: Bound<typeof readQueuedMessagesFlag>;+ recordInterventionLifecycleCompletion: Bound<typeof recordInterventionLifecycleCompletion>;+ refreshMessagesFromDB: Bound<typeof refreshMessagesFromDB>;+ releaseOperationLock: Bound<typeof releaseOperationLock>;+ resolveAsyncToolOnComplete: Bound<typeof resolveAsyncToolOnComplete>;+ resolveAsyncToolResumeParentMessageId: typeof resolveAsyncToolResumeParentMessageId;+ resolveLastAssistantContentFromThread: Bound<typeof resolveLastAssistantContentFromThread>;+ resolveLastAssistantMessageFromDB: Bound<typeof resolveLastAssistantMessageFromDB>;+ resolveLlmExecutor: Bound<typeof resolveLlmExecutor>;+ restoreClientLlmWait: Bound<typeof restoreClientLlmWait>;+ resumeFromClientLlmWait: Bound<typeof resumeFromClientLlmWait>;+ revertClientWaitResumeWithRetry: Bound<typeof revertClientWaitResumeWithRetry>;+ scheduleContinuation: Bound<typeof scheduleContinuation>;+ scheduleGroupMemberTimeout: Bound<typeof scheduleGroupMemberTimeout>;+ readonly serverDB: LobeChatDatabase;+ setQueuedMessages: Bound<typeof setQueuedMessages>;+ setupLocalExecutionCallback: Bound<typeof setupLocalExecutionCallback>;+ shouldContinueExecution: typeof shouldContinueExecution;+ shouldReplayPendingInterventionLifecycle: typeof shouldReplayPendingInterventionLifecycle;+ startExecution: Bound<typeof startExecution>;+ startStepLockHeartbeat: Bound<typeof startStepLockHeartbeat>;+ readonly streamManager: IStreamEventManager;+ readonly toolExecutionService: ToolExecutionService;+ readonly traceRecorder: OperationTraceRecorder;+ tryResumeParentFromAsyncTool: Bound<typeof tryResumeParentFromAsyncTool>;+ updateAssistantRowWithRetry: Bound<typeof updateAssistantRowWithRetry>;+ readonly userId: string;+ usesGatewayMessagePatch: typeof usesGatewayMessagePatch;+ readonly workspaceId: string | undefined;+}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/utils.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/utils.tsnew file mode 100644index 00000000000..0a7f69ba933--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/utils.ts@@ -0,0 +1,161 @@+import { randomUUID } from 'node:crypto';++import { ABANDONED_OPERATION_ERROR_PREFIX } from '@lobechat/const/goal';+import { ChatErrorType } from '@lobechat/types';++import type { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';+import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';++import {+ ASYNC_TOOL_VERIFY_DELAY_MS,+ ASYNC_TOOL_VERIFY_MAX_DELAY_MS,+ STEP_LOCK_RETRY_BASE_DELAY_MS,+ STEP_LOCK_RETRY_MAX_DELAY_MS,+} from './constants';++/**+ * Drop the frozen model facts from a copy of `modelRuntimeConfig`.+ *+ * They exist so a live run's steps stop re-reading the model bank and the+ * user's rows, and the run reads them back off its Redis state. The durable+ * `agent_operations` row and the operation metadata only ever surface the model+ * and provider, so neither needs to keep ~0.5KB of cards per operation — the row+ * keeps them forever.+ */+export const withoutFrozenModelFacts = (modelRuntimeConfig?: any) => {+ if (!modelRuntimeConfig?.modelFacts) return modelRuntimeConfig;+ const { modelFacts: _frozen, ...rest } = modelRuntimeConfig;+ return rest;+};++/**+ * Exponential backoff for the Nth (1-based) lock-conflict re-delivery:+ * 15s, 30s, 60s, 120s, then capped at {@link STEP_LOCK_RETRY_MAX_DELAY_MS}.+ */+export const stepLockRetryDelayMs = (attempt: number): number =>+ Math.min(+ STEP_LOCK_RETRY_BASE_DELAY_MS * 2 ** (Math.max(1, attempt) - 1),+ STEP_LOCK_RETRY_MAX_DELAY_MS,+ );++/**+ * Exponential backoff delay for the Nth (1-based) watchdog re-check:+ * 15s, 30s, 60s, 120s, 240s, capped at {@link ASYNC_TOOL_VERIFY_MAX_DELAY_MS}.+ */+export const asyncToolVerifyDelayMs = (attempt: number): number =>+ Math.min(+ ASYNC_TOOL_VERIFY_DELAY_MS * 2 ** (Math.max(1, attempt) - 1),+ ASYNC_TOOL_VERIFY_MAX_DELAY_MS,+ );++export const createStepLockOwner = (operationId: string, stepIndex: number): string =>+ `${operationId}:${stepIndex}:${process.pid}:${Date.now()}:${randomUUID()}`;++/**+ * Format error for storage in message pluginError metadata.+ * Handles Error objects which don't serialize properly with JSON.stringify.+ */+export const formatErrorForMetadata = (error: unknown): Record<string, any> | undefined => {+ if (!error) return undefined;+ if (error instanceof Error) return { message: error.message, name: error.name };+ if (typeof error === 'object' && 'message' in error) return error as Record<string, any>;+ return { message: String(error) };+};++export const SUB_AGENT_CREDIT_ERROR_TYPES = new Set<string>([+ ChatErrorType.FreePlanLimit,+ ChatErrorType.InsufficientBudgetForModel,+ ChatErrorType.SubscriptionPlanLimit,+]);++/**+ * A child stopped by the cost-admission gate fails with the bare message+ * "Budget exceeded", which reads like a per-sub-agent allowance. The parent+ * then retries or fans out more sub-agents against the same limit. Say which+ * limit it is and who can lift it.+ *+ * Mirrors the bot reply copy (`bot/replyTemplate.ts`): the payer is not+ * addressed as "you" and figures are never quoted, because a bot run is billed+ * to its owner while the parent's reply may reach a shared channel.+ */+export const formatSubAgentCreditErrorReason = (error: unknown): string | undefined => {+ if (!error || typeof error !== 'object') return;+ const { body, errorType, type } = error as {+ body?: { budget?: { budgetTypeAtError?: unknown } };+ errorType?: unknown;+ type?: unknown;+ };+ const creditType = [type, errorType].find(+ (value): value is string =>+ typeof value === 'string' && SUB_AGENT_CREDIT_ERROR_TYPES.has(value),+ );+ if (!creditType) return;++ const budgetType = body?.budget?.budgetTypeAtError;+ // InsufficientBudgetForModel means the allowance still has credits, just not+ // enough for this model's estimated cost — a cheaper model may still fit, so+ // the no-retry claim only holds for the same model (bot/replyTemplate gives+ // the same "switch to a less expensive model" advice).+ const modelCostShortfall = creditType === ChatErrorType.InsufficientBudgetForModel;+ const shortfall = modelCostShortfall ? "can't cover this model's estimated cost" : 'are used up';+ const limit =+ budgetType === 'workspace'+ ? `the workspace's shared LobeHub credits ${shortfall}; a workspace admin has to add credits`+ : budgetType === 'workspace_member'+ ? `this member's workspace credit allowance ${modelCostShortfall ? shortfall : 'is used up'}; a workspace admin has to raise it`+ : modelCostShortfall+ ? "the account's LobeHub credits are too low for this model; the account owner has to top up or upgrade"+ : "the account's LobeHub plan limit was reached or the plan does not cover this model; the account owner has to upgrade the plan";++ const advice = modelCostShortfall+ ? 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents on the same model will not get past it; a sub-agent that runs on a less expensive model may still fit. ' ++ 'Otherwise finish with what you already have and tell the user about the limit.'+ : 'This limit is shared by every sub-agent and by this conversation, so retrying or dispatching more sub-agents will not get past it. ' ++ 'Finish with what you already have and tell the user about the limit.';++ return `stopped by a LobeHub billing limit (${creditType}): ${limit}. ${advice}`;+};++/**+ * Extract a short, human-readable reason string from a failed operation's+ * `state.error`, for inlining into the tool-result `content` a parent agent+ * sees. Without this the supervising agent only gets the opaque generic note+ * ("Sub-agent did not complete (error).") and cannot tell *why* a `callAgent`+ * dispatch failed — so it can't retry, switch target, or report the cause; it+ * silently falls back to answering itself (issue #16257). The full structured+ * error still rides on `pluginError`; this is just the readable summary.+ */+export const formatSubAgentErrorReason = (error: unknown): string | undefined => {+ const creditReason = formatSubAgentCreditErrorReason(error);+ if (creditReason) return creditReason;++ const message = formatErrorForMetadata(error)?.message;+ if (typeof message !== 'string') return undefined;+ const trimmed = message.trim();+ if (!trimmed) return undefined;+ // "Operation abandoned: inactivity_watchdog" names an internal mechanism;+ // the parent needs to know the child went silent and that its work survives.+ if (trimmed.startsWith(ABANDONED_OPERATION_ERROR_PREFIX)) {+ const cause = trimmed.slice(ABANDONED_OPERATION_ERROR_PREFIX.length).trim();+ return (+ `the sub-agent stopped making progress and the platform ended it (${cause || 'abandoned'}). ` ++ 'Anything it already did (searches, pages read, documents written) is kept in its thread.'+ );+ }+ // Keep the tool result compact — a runaway provider error body would otherwise+ // bloat the parent's LLM context.+ return trimmed.length > 300 ? `${trimmed.slice(0, 300)}…` : trimmed;+};++export const toAgentSignalSnapshotEvents = (+ emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,+) => {+ if (!emission || emission.deduped) return [];++ return toAgentSignalTraceEvents({+ actions: emission.orchestration.actions,+ results: emission.orchestration.results,+ signals: emission.orchestration.emittedSignals,+ source: emission.source,+ });+};diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.mdindex bac1015ec22..712cb1cbdb6 100644--- a/apps/server/src/services/aiAgent/shareGate/README.md+++ b/apps/server/src/services/aiAgent/shareGate/README.md@@ -152,7 +152,7 @@ absence of a known exploit.4. Activations restored from history. `operationPrep` re-derives them into`activatableToolIds` (`apps/server/src/services/aiAgent/pipeline/operationPrep.ts:535`) before the sharegate prunes that list, and `AgentRuntimeService` restores only ids still- in it (`apps/server/src/services/agentRuntime/AgentRuntimeService.ts:1350`).+ in it (`apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts:182`).5. Its skill fallback. `activateTools` retries a non-tool id as a skillname. That lookup re-checks `shareConfig.skillGrants` on every source itopens (`apps/server/src/services/toolExecution/serverRuntimes/activator.ts:97`), the same rule thediff --git a/docs/development/basic/chat-api.mdx b/docs/development/basic/chat-api.mdxindex c834e2a6304..6b05e7018ff 100644--- a/docs/development/basic/chat-api.mdx+++ b/docs/development/basic/chat-api.mdx@@ -342,7 +342,7 @@ depends on the scenario:API/Cron triggers. The loop runs on the server,streaming events to the client via SSE, entry point is`AgentRuntimeService.executeStep()`- (`apps/server/src/services/agentRuntime/AgentRuntimeService.ts`),+ (`apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts`),tRPC route at `apps/server/src/routers/lambda/aiAgent.ts`## Model Runtimediff --git a/docs/development/basic/chat-api.zh-CN.mdx b/docs/development/basic/chat-api.zh-CN.mdxindex 5a861b17e62..5fa65ce9907 100644--- a/docs/development/basic/chat-api.zh-CN.mdx+++ b/docs/development/basic/chat-api.zh-CN.mdx@@ -310,7 +310,7 @@ Agent Runtime 循环的执行位置取决于场景:子 agent 任务、API/Cron 触发。循环在服务端运行,通过 SSE 流式推送事件到客户端,入口为 `AgentRuntimeService.executeStep()`- (`apps/server/src/services/agentRuntime/AgentRuntimeService.ts`),+ (`apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts`),tRPC 路由为 `apps/server/src/routers/lambda/aiAgent.ts`## Model Runtimediff --git a/packages/agent-signal/README.md b/packages/agent-signal/README.mdindex 1a388f9b01a..cc705e7945f 100644--- a/packages/agent-signal/README.md+++ b/packages/agent-signal/README.md@@ -97,8 +97,8 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv| Source event | Constant | Primary producer | Payload intent || ------------------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |-| `agent.execution.completed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService.ts) | Server agent execution completed with operation, step, topic, and context metadata. |-| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. |+| `agent.execution.completed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle.ts) | Server agent execution completed with operation, step, topic, and context metadata. |+| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../apps/server/src/services/agentRuntime/CompletionLifecycle.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. || `agent.user.message` | `AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage` | [Workflow bridge](../../apps/server/src/workflows/agentSignal/run.ts), [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts) | User feedback/message content that policies can analyze for memory, prompt, document, or skill changes. || `bot.message.merged` | `AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged` | [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts) | Bot-platform message content merged into a conversation scope. || `client.gateway.error` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway error for a client-side runtime operation. |@@ -107,8 +107,8 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv| `client.gateway.stream_start` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart` | [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts) | Browser gateway stream started with operation and first step metadata. || `client.runtime.complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime completed with operation, topic, thread, and status metadata. || `client.runtime.start` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart` | [Chat streaming executor](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts) | Browser chat runtime started; workflow may bridge this into `agent.user.message` with serialized context. |-| `runtime.after_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService.ts) | Server runtime step finished with operation, step index, topic, and context metadata. |-| `runtime.before_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService.ts) | Server runtime step is about to run with operation, step index, topic, and context metadata. |+| `runtime.after_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts) | Server runtime step finished with operation, step index, topic, and context metadata. |+| `runtime.before_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep` | [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/hooks.ts) | Server runtime step is about to run with operation, step index, topic, and context metadata. |`AGENT_SIGNAL_CLIENT_SOURCE_TYPES` is the allow-list for browser-originated events accepted by [apps/server/src/routers/lambda/agentSignal.ts](../../apps/server/src/routers/lambda/agentSignal.ts). It currently includes only the `client.*` source events.@@ -125,7 +125,7 @@ See [apps/server/src/services/agentSignal/emitter.ts](../../apps/server/src/serv- [Source dedupe store](../../apps/server/src/services/agentSignal/sources/index.ts): source event dedupe, scope locking, and source node rendering.- [Workflow trigger](../../apps/server/src/workflows/agentSignal/index.ts): async Upstash Workflow handoff.- [Workflow runner](../../apps/server/src/workflows/agentSignal/run.ts): workflow execution and client runtime bridge.-- [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService.ts): server runtime source event producers.+- [Agent Runtime](../../apps/server/src/services/agentRuntime/AgentRuntimeService/): server runtime source event producers.- [Chat](../../src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts): browser chat runtime source event producer.- [Gateway event handler](../../src/store/chat/slices/agentRun/actions/transports/gateway/gatewayEventHandler.ts): browser gateway source event producer.- [Bot router](../../apps/server/src/services/bot/BotMessageRouter.ts): bot-platform source event producer.