🤯 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
✨ feat(observability): instrument Agent Runtime with OTel GenAI semantic conventions (#15123)
Arvin Xu248d6ecf7693
diff --git a/packages/observability-otel/package.json b/packages/observability-otel/package.jsonindex 8d139502187..0fbd7a114bf 100644--- a/packages/observability-otel/package.json+++ b/packages/observability-otel/package.json@@ -7,6 +7,7 @@"./api": "./src/api.ts","./trpc": "./src/trpc/index.ts","./gen-ai": "./src/gen-ai/index.ts",+ "./modules/agent-runtime": "./src/modules/agent-runtime/index.ts","./modules/agent-signal": "./src/modules/agent-signal/index.ts","./modules/memory-user-memory": "./src/modules/memory-user-memory/index.ts","./modules/upstash-workflow": "./src/modules/upstash-workflow/index.ts"diff --git a/packages/observability-otel/src/modules/agent-runtime/attributes.test.ts b/packages/observability-otel/src/modules/agent-runtime/attributes.test.tsnew file mode 100644index 00000000000..d1f0a253e9c--- /dev/null+++ b/packages/observability-otel/src/modules/agent-runtime/attributes.test.ts@@ -0,0 +1,169 @@+import { describe, expect, it } from 'vitest';++import {+ buildChatRequestAttributes,+ buildChatResponseAttributes,+ buildContextEngineeringAttributes,+ buildExecuteToolAttributes,+ buildExecuteToolResultAttributes,+ buildInvokeAgentAttributes,+ buildInvokeAgentResultAttributes,+ chatSpanName,+ CONTEXT_ENGINEERING_SPAN_NAME,+ executeToolSpanName,+ invokeAgentSpanName,+} from './attributes';++describe('agent-runtime attribute builders', () => {+ it('builds invoke_agent attributes and drops undefined fields', () => {+ const attrs = buildInvokeAgentAttributes({+ agentId: 'agent_123',+ agentName: 'researcher',+ conversationId: 'topic_abc',+ operationId: 'op_xyz',+ provider: 'openai',+ requestModel: 'gpt-5',+ stepIndex: 0,+ });++ expect(attrs).toEqual({+ 'gen_ai.operation.name': 'invoke_agent',+ 'gen_ai.agent.id': 'agent_123',+ 'gen_ai.agent.name': 'researcher',+ 'gen_ai.provider.name': 'openai',+ 'gen_ai.request.model': 'gpt-5',+ 'gen_ai.conversation.id': 'topic_abc',+ 'lobehub.agent.operation.id': 'op_xyz',+ 'lobehub.agent.step.index': 0,+ });+ expect(attrs).not.toHaveProperty('gen_ai.agent.description');+ });++ it('builds invoke_agent result attributes with completion reason', () => {+ const attrs = buildInvokeAgentResultAttributes({+ completionReason: 'done',+ inputTokens: 1000,+ outputTokens: 200,+ stepCount: 5,+ });++ expect(attrs).toEqual({+ 'gen_ai.usage.input_tokens': 1000,+ 'gen_ai.usage.output_tokens': 200,+ 'lobehub.agent.step.count': 5,+ 'lobehub.agent.completion_reason': 'done',+ });+ });++ it('builds chat request attributes including stream flag', () => {+ const attrs = buildChatRequestAttributes({+ operationId: 'op_xyz',+ provider: 'openai',+ requestModel: 'gpt-5',+ stepIndex: 2,+ stream: true,+ temperature: 0.7,+ });++ expect(attrs['gen_ai.operation.name']).toBe('chat');+ expect(attrs['gen_ai.provider.name']).toBe('openai');+ expect(attrs['gen_ai.request.stream']).toBe(true);+ expect(attrs['gen_ai.request.temperature']).toBe(0.7);+ expect(attrs).not.toHaveProperty('gen_ai.request.max_tokens');+ });++ it('builds chat response attributes including TTFT seconds and cache tokens', () => {+ const attrs = buildChatResponseAttributes({+ cacheReadInputTokens: 30,+ finishReasons: ['stop'],+ inputTokens: 120,+ outputTokens: 80,+ reasoningOutputTokens: 50,+ responseId: 'chatcmpl-123',+ responseModel: 'gpt-5-2026-01-01',+ timeToFirstChunkMs: 480,+ });++ expect(attrs).toEqual({+ 'gen_ai.response.id': 'chatcmpl-123',+ 'gen_ai.response.model': 'gpt-5-2026-01-01',+ 'gen_ai.response.finish_reasons': ['stop'],+ 'gen_ai.response.time_to_first_chunk': 0.48,+ 'gen_ai.usage.input_tokens': 120,+ 'gen_ai.usage.output_tokens': 80,+ 'gen_ai.usage.cache_read.input_tokens': 30,+ 'gen_ai.usage.reasoning.output_tokens': 50,+ });+ });++ it('builds execute_tool attributes including tool type and call id', () => {+ const attrs = buildExecuteToolAttributes({+ operationId: 'op_xyz',+ stepIndex: 1,+ toolCallId: 'call_42',+ toolName: 'web_search',+ toolSource: 'builtin',+ toolType: 'function',+ });++ expect(attrs).toMatchObject({+ 'gen_ai.operation.name': 'execute_tool',+ 'gen_ai.tool.name': 'web_search',+ 'gen_ai.tool.type': 'function',+ 'gen_ai.tool.call.id': 'call_42',+ 'lobehub.tool.source': 'builtin',+ 'lobehub.agent.operation.id': 'op_xyz',+ 'lobehub.agent.step.index': 1,+ });+ });++ it('builds execute_tool result attributes', () => {+ const attrs = buildExecuteToolResultAttributes({+ attempts: 2,+ success: false,+ });++ expect(attrs).toEqual({+ 'lobehub.tool.success': false,+ 'lobehub.tool.attempts': 2,+ });+ });++ it('builds context_engineering attributes for snapshot-level metadata', () => {+ const attrs = buildContextEngineeringAttributes({+ hasImages: true,+ historyCompressed: false,+ knowledgeCount: 3,+ knowledgeInjected: true,+ memoryInjected: true,+ messageCount: 12,+ operationId: 'op_xyz',+ stepIndex: 0,+ systemRoleLength: 1024,+ toolCount: 7,+ });++ expect(attrs).toMatchObject({+ 'lobehub.context.message_count': 12,+ 'lobehub.context.knowledge_injected': true,+ 'lobehub.context.knowledge_count': 3,+ 'lobehub.context.history_compressed': false,+ 'lobehub.context.memory_injected': true,+ 'lobehub.context.system_role_length': 1024,+ 'lobehub.context.tool_count': 7,+ 'lobehub.context.has_images': true,+ 'lobehub.agent.operation.id': 'op_xyz',+ 'lobehub.agent.step.index': 0,+ });+ expect(attrs).not.toHaveProperty('lobehub.context.token_usage');+ expect(attrs).not.toHaveProperty('lobehub.context.window_ratio');+ });++ it('formats span names per gen_ai convention', () => {+ expect(invokeAgentSpanName('researcher')).toBe('invoke_agent researcher');+ expect(invokeAgentSpanName()).toBe('invoke_agent');+ expect(chatSpanName('gpt-5')).toBe('chat gpt-5');+ expect(executeToolSpanName('web_search')).toBe('execute_tool web_search');+ expect(CONTEXT_ENGINEERING_SPAN_NAME).toBe('context_engineering');+ });+});diff --git a/packages/observability-otel/src/modules/agent-runtime/attributes.ts b/packages/observability-otel/src/modules/agent-runtime/attributes.tsnew file mode 100644index 00000000000..13cb8ef504b--- /dev/null+++ b/packages/observability-otel/src/modules/agent-runtime/attributes.ts@@ -0,0 +1,253 @@+import type { Attributes } from '@opentelemetry/api';++import {+ ATTR_GEN_AI_AGENT_DESCRIPTION,+ ATTR_GEN_AI_AGENT_ID,+ ATTR_GEN_AI_AGENT_NAME,+ ATTR_GEN_AI_AGENT_VERSION,+ ATTR_GEN_AI_CONVERSATION_ID,+ ATTR_GEN_AI_DATA_SOURCE_ID,+ ATTR_GEN_AI_OPERATION_NAME,+ ATTR_GEN_AI_PROVIDER_NAME,+ ATTR_GEN_AI_REQUEST_MAX_TOKENS,+ ATTR_GEN_AI_REQUEST_MODEL,+ ATTR_GEN_AI_REQUEST_STREAM,+ ATTR_GEN_AI_REQUEST_TEMPERATURE,+ ATTR_GEN_AI_REQUEST_TOP_P,+ ATTR_GEN_AI_RESPONSE_FINISH_REASONS,+ ATTR_GEN_AI_RESPONSE_ID,+ ATTR_GEN_AI_RESPONSE_MODEL,+ ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,+ ATTR_GEN_AI_TOOL_CALL_ARGUMENTS,+ ATTR_GEN_AI_TOOL_CALL_ID,+ ATTR_GEN_AI_TOOL_CALL_RESULT,+ ATTR_GEN_AI_TOOL_DESCRIPTION,+ ATTR_GEN_AI_TOOL_NAME,+ ATTR_GEN_AI_TOOL_TYPE,+ ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,+ ATTR_GEN_AI_USAGE_INPUT_TOKENS,+ ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,+ ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,+ ATTR_LOBEHUB_AGENT_COMPLETION_REASON,+ ATTR_LOBEHUB_AGENT_OPERATION_ID,+ ATTR_LOBEHUB_AGENT_STEP_COUNT,+ ATTR_LOBEHUB_AGENT_STEP_INDEX,+ ATTR_LOBEHUB_CONTEXT_HAS_IMAGES,+ ATTR_LOBEHUB_CONTEXT_HISTORY_COMPRESSED,+ ATTR_LOBEHUB_CONTEXT_KNOWLEDGE_COUNT,+ ATTR_LOBEHUB_CONTEXT_KNOWLEDGE_INJECTED,+ ATTR_LOBEHUB_CONTEXT_MEMORY_INJECTED,+ ATTR_LOBEHUB_CONTEXT_MESSAGE_COUNT,+ ATTR_LOBEHUB_CONTEXT_SYSTEM_ROLE_LENGTH,+ ATTR_LOBEHUB_CONTEXT_TOKEN_USAGE,+ ATTR_LOBEHUB_CONTEXT_TOOL_COUNT,+ ATTR_LOBEHUB_CONTEXT_WINDOW_RATIO,+ ATTR_LOBEHUB_TOOL_ATTEMPTS,+ ATTR_LOBEHUB_TOOL_SOURCE,+ ATTR_LOBEHUB_TOOL_SUCCESS,+ GEN_AI_OPERATION_CHAT,+ GEN_AI_OPERATION_EXECUTE_TOOL,+ GEN_AI_OPERATION_INVOKE_AGENT,+} from './semconv';++/**+ * Drop attributes with `undefined` values so OTel exporters don't receive them.+ * OTel rejects undefined attribute values; null/empty strings are kept verbatim+ * because the caller may have an intentional reason to record them.+ */+const compact = (input: Record<string, unknown>): Attributes => {+ const out: Attributes = {};+ for (const [key, value] of Object.entries(input)) {+ if (value !== undefined) {+ out[key] = value as Attributes[string];+ }+ }+ return out;+};++// ---- invoke_agent span ----++export interface InvokeAgentAttributes {+ agentDescription?: string;+ agentId?: string;+ agentName?: string;+ agentVersion?: string;+ conversationId?: string;+ dataSourceId?: string;+ operationId: string;+ provider?: string;+ requestModel?: string;+ stepIndex?: number;+}++export const buildInvokeAgentAttributes = (input: InvokeAgentAttributes): Attributes =>+ compact({+ [ATTR_GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_INVOKE_AGENT,+ [ATTR_GEN_AI_AGENT_ID]: input.agentId,+ [ATTR_GEN_AI_AGENT_NAME]: input.agentName,+ [ATTR_GEN_AI_AGENT_DESCRIPTION]: input.agentDescription,+ [ATTR_GEN_AI_AGENT_VERSION]: input.agentVersion,+ [ATTR_GEN_AI_PROVIDER_NAME]: input.provider,+ [ATTR_GEN_AI_REQUEST_MODEL]: input.requestModel,+ [ATTR_GEN_AI_CONVERSATION_ID]: input.conversationId,+ [ATTR_GEN_AI_DATA_SOURCE_ID]: input.dataSourceId,+ [ATTR_LOBEHUB_AGENT_OPERATION_ID]: input.operationId,+ [ATTR_LOBEHUB_AGENT_STEP_INDEX]: input.stepIndex,+ });++export interface InvokeAgentResultAttributes {+ completionReason?: string;+ inputTokens?: number;+ outputTokens?: number;+ stepCount?: number;+}++export const buildInvokeAgentResultAttributes = (input: InvokeAgentResultAttributes): Attributes =>+ compact({+ [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: input.inputTokens,+ [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: input.outputTokens,+ [ATTR_LOBEHUB_AGENT_STEP_COUNT]: input.stepCount,+ [ATTR_LOBEHUB_AGENT_COMPLETION_REASON]: input.completionReason,+ });++export const invokeAgentSpanName = (agentName?: string) =>+ agentName ? `${GEN_AI_OPERATION_INVOKE_AGENT} ${agentName}` : GEN_AI_OPERATION_INVOKE_AGENT;++// ---- chat span ----++export interface ChatRequestAttributes {+ conversationId?: string;+ maxTokens?: number;+ operationId?: string;+ provider: string;+ requestModel: string;+ stepIndex?: number;+ stream?: boolean;+ temperature?: number;+ topP?: number;+}++export const buildChatRequestAttributes = (input: ChatRequestAttributes): Attributes =>+ compact({+ [ATTR_GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_CHAT,+ [ATTR_GEN_AI_REQUEST_MODEL]: input.requestModel,+ [ATTR_GEN_AI_PROVIDER_NAME]: input.provider,+ [ATTR_GEN_AI_REQUEST_STREAM]: input.stream,+ [ATTR_GEN_AI_REQUEST_MAX_TOKENS]: input.maxTokens,+ [ATTR_GEN_AI_REQUEST_TEMPERATURE]: input.temperature,+ [ATTR_GEN_AI_REQUEST_TOP_P]: input.topP,+ [ATTR_GEN_AI_CONVERSATION_ID]: input.conversationId,+ [ATTR_LOBEHUB_AGENT_OPERATION_ID]: input.operationId,+ [ATTR_LOBEHUB_AGENT_STEP_INDEX]: input.stepIndex,+ });++export interface ChatResponseAttributes {+ cacheReadInputTokens?: number;+ finishReasons?: string[];+ inputTokens?: number;+ outputTokens?: number;+ reasoningOutputTokens?: number;+ responseId?: string;+ responseModel?: string;+ timeToFirstChunkMs?: number;+}++export const buildChatResponseAttributes = (input: ChatResponseAttributes): Attributes =>+ compact({+ [ATTR_GEN_AI_RESPONSE_ID]: input.responseId,+ [ATTR_GEN_AI_RESPONSE_MODEL]: input.responseModel,+ [ATTR_GEN_AI_RESPONSE_FINISH_REASONS]: input.finishReasons,+ [ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK]:+ input.timeToFirstChunkMs === undefined ? undefined : input.timeToFirstChunkMs / 1000,+ [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: input.inputTokens,+ [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: input.outputTokens,+ [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: input.cacheReadInputTokens,+ [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: input.reasoningOutputTokens,+ });++export const chatSpanName = (model: string) => `${GEN_AI_OPERATION_CHAT} ${model}`;++// ---- execute_tool span ----++/**+ * `gen_ai.tool.type` value. Spec examples include `function`, `extension`,+ * and `datastore`; kept as a string because the OTel enum is open.+ */+export type ToolType = string;++export interface ExecuteToolAttributes {+ argumentsJson?: string;+ description?: string;+ operationId?: string;+ stepIndex?: number;+ toolCallId?: string;+ toolName: string;+ toolSource?: string;+ toolType?: ToolType;+}++export const buildExecuteToolAttributes = (input: ExecuteToolAttributes): Attributes =>+ compact({+ [ATTR_GEN_AI_OPERATION_NAME]: GEN_AI_OPERATION_EXECUTE_TOOL,+ [ATTR_GEN_AI_TOOL_NAME]: input.toolName,+ [ATTR_GEN_AI_TOOL_TYPE]: input.toolType,+ [ATTR_GEN_AI_TOOL_CALL_ID]: input.toolCallId,+ [ATTR_GEN_AI_TOOL_DESCRIPTION]: input.description,+ [ATTR_GEN_AI_TOOL_CALL_ARGUMENTS]: input.argumentsJson,+ [ATTR_LOBEHUB_TOOL_SOURCE]: input.toolSource,+ [ATTR_LOBEHUB_AGENT_OPERATION_ID]: input.operationId,+ [ATTR_LOBEHUB_AGENT_STEP_INDEX]: input.stepIndex,+ });++export interface ExecuteToolResultAttributes {+ attempts?: number;+ resultJson?: string;+ success: boolean;+}++export const buildExecuteToolResultAttributes = (input: ExecuteToolResultAttributes): Attributes =>+ compact({+ [ATTR_LOBEHUB_TOOL_SUCCESS]: input.success,+ [ATTR_LOBEHUB_TOOL_ATTEMPTS]: input.attempts,+ [ATTR_GEN_AI_TOOL_CALL_RESULT]: input.resultJson,+ });++export const executeToolSpanName = (toolName: string) =>+ `${GEN_AI_OPERATION_EXECUTE_TOOL} ${toolName}`;++// ---- context_engineering span (LobeHub-only) ----++export interface ContextEngineeringAttributes {+ hasImages?: boolean;+ historyCompressed?: boolean;+ knowledgeCount?: number;+ knowledgeInjected?: boolean;+ memoryInjected?: boolean;+ messageCount?: number;+ operationId?: string;+ stepIndex?: number;+ systemRoleLength?: number;+ tokenUsage?: number;+ toolCount?: number;+ windowRatio?: number;+}++export const buildContextEngineeringAttributes = (+ input: ContextEngineeringAttributes,+): Attributes =>+ compact({+ [ATTR_LOBEHUB_CONTEXT_MESSAGE_COUNT]: input.messageCount,+ [ATTR_LOBEHUB_CONTEXT_TOKEN_USAGE]: input.tokenUsage,+ [ATTR_LOBEHUB_CONTEXT_WINDOW_RATIO]: input.windowRatio,+ [ATTR_LOBEHUB_CONTEXT_KNOWLEDGE_INJECTED]: input.knowledgeInjected,+ [ATTR_LOBEHUB_CONTEXT_KNOWLEDGE_COUNT]: input.knowledgeCount,+ [ATTR_LOBEHUB_CONTEXT_HISTORY_COMPRESSED]: input.historyCompressed,+ [ATTR_LOBEHUB_CONTEXT_MEMORY_INJECTED]: input.memoryInjected,+ [ATTR_LOBEHUB_CONTEXT_SYSTEM_ROLE_LENGTH]: input.systemRoleLength,+ [ATTR_LOBEHUB_CONTEXT_TOOL_COUNT]: input.toolCount,+ [ATTR_LOBEHUB_CONTEXT_HAS_IMAGES]: input.hasImages,+ [ATTR_LOBEHUB_AGENT_OPERATION_ID]: input.operationId,+ [ATTR_LOBEHUB_AGENT_STEP_INDEX]: input.stepIndex,+ });++export const CONTEXT_ENGINEERING_SPAN_NAME = 'context_engineering' as const;diff --git a/packages/observability-otel/src/modules/agent-runtime/index.ts b/packages/observability-otel/src/modules/agent-runtime/index.tsnew file mode 100644index 00000000000..43c39eff78f--- /dev/null+++ b/packages/observability-otel/src/modules/agent-runtime/index.ts@@ -0,0 +1,14 @@+import { trace } from '@opentelemetry/api';++/**+ * Tracer for Agent Runtime semantic spans (invoke_agent / chat / execute_tool /+ * context_engineering). Shared across `AgentRuntimeService`, `RuntimeExecutors`,+ * and the server-side `serverMessagesEngine`.+ *+ * When OTEL is not initialized, `getTracer` returns a no-op provider, so calling+ * `tracer.startActiveSpan` is safe and cheap in environments without telemetry.+ */+export const tracer = trace.getTracer('@lobechat/agent-runtime', '0.0.1');++export * from './attributes';+export * from './semconv';diff --git a/packages/observability-otel/src/modules/agent-runtime/semconv.ts b/packages/observability-otel/src/modules/agent-runtime/semconv.tsnew file mode 100644index 00000000000..a8fcab77d7a--- /dev/null+++ b/packages/observability-otel/src/modules/agent-runtime/semconv.ts@@ -0,0 +1,108 @@+/**+ * OTel GenAI Semantic Convention attribute names used by the Agent Runtime+ * instrumentation, alongside LobeHub-specific (`lobehub.*`) extensions.+ *+ * Aligned with OTel GenAI Semantic Conventions v1.41:+ * https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/+ *+ * Attribute names that already live in our generated `gen-ai/semconv.ts` copy+ * are re-exported here instead of being re-declared, keeping that generated+ * file as the source of truth.+ */++// ---- gen_ai.* (generated OTel semconv copy) ----++export {+ ATTR_GEN_AI_OPERATION_NAME,+ ATTR_GEN_AI_REQUEST_MAX_TOKENS,+ ATTR_GEN_AI_REQUEST_MODEL,+ ATTR_GEN_AI_REQUEST_TEMPERATURE,+ ATTR_GEN_AI_REQUEST_TOP_P,+ ATTR_GEN_AI_RESPONSE_FINISH_REASONS,+ ATTR_GEN_AI_RESPONSE_ID,+ ATTR_GEN_AI_RESPONSE_MODEL,+ ATTR_GEN_AI_USAGE_INPUT_TOKENS,+ ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,+} from '../../gen-ai/semconv';++// ---- gen_ai.* (OTel spec, not yet in the generated local copy) ----++/** Provider name — `openai`, `anthropic`, `lobehub`, etc. */+export const ATTR_GEN_AI_PROVIDER_NAME = 'gen_ai.provider.name' as const;++/** Conversation / topic id this span belongs to. */+export const ATTR_GEN_AI_CONVERSATION_ID = 'gen_ai.conversation.id' as const;++/** Whether the request was issued in streaming mode. */+export const ATTR_GEN_AI_REQUEST_STREAM = 'gen_ai.request.stream' as const;++/** Time to first chunk for streaming responses (TTFT), recorded in seconds. */+export const ATTR_GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK =+ 'gen_ai.response.time_to_first_chunk' as const;++/** Cache-hit input tokens. */+export const ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS =+ 'gen_ai.usage.cache_read.input_tokens' as const;++/** Reasoning output tokens (thinking). */+export const ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS =+ 'gen_ai.usage.reasoning.output_tokens' as const;++/** Agent identity. */+export const ATTR_GEN_AI_AGENT_ID = 'gen_ai.agent.id' as const;+export const ATTR_GEN_AI_AGENT_NAME = 'gen_ai.agent.name' as const;+export const ATTR_GEN_AI_AGENT_DESCRIPTION = 'gen_ai.agent.description' as const;+export const ATTR_GEN_AI_AGENT_VERSION = 'gen_ai.agent.version' as const;+export const ATTR_GEN_AI_DATA_SOURCE_ID = 'gen_ai.data_source.id' as const;++/** Tool span attributes. */+export const ATTR_GEN_AI_TOOL_NAME = 'gen_ai.tool.name' as const;+export const ATTR_GEN_AI_TOOL_TYPE = 'gen_ai.tool.type' as const;+export const ATTR_GEN_AI_TOOL_DESCRIPTION = 'gen_ai.tool.description' as const;+export const ATTR_GEN_AI_TOOL_CALL_ID = 'gen_ai.tool.call.id' as const;+export const ATTR_GEN_AI_TOOL_CALL_ARGUMENTS = 'gen_ai.tool.call.arguments' as const;+export const ATTR_GEN_AI_TOOL_CALL_RESULT = 'gen_ai.tool.call.result' as const;++// ---- lobehub.* (LobeHub-specific extensions) ----++/** Internal operation id assigned by the Agent Runtime. */+export const ATTR_LOBEHUB_AGENT_OPERATION_ID = 'lobehub.agent.operation.id' as const;++/** Total step count for the agent invocation. */+export const ATTR_LOBEHUB_AGENT_STEP_COUNT = 'lobehub.agent.step.count' as const;++/** Current step index within the agent invocation. */+export const ATTR_LOBEHUB_AGENT_STEP_INDEX = 'lobehub.agent.step.index' as const;++/** Completion reason: `done` / `error` / `max_steps` / `cost_limit` / `interrupted` / `waiting_for_human`. */+export const ATTR_LOBEHUB_AGENT_COMPLETION_REASON = 'lobehub.agent.completion_reason' as const;++/** Tool execution success flag (gen_ai spec uses error.type for failures only). */+export const ATTR_LOBEHUB_TOOL_SUCCESS = 'lobehub.tool.success' as const;++/** Attempts taken to execute a tool (1 for first-try success). */+export const ATTR_LOBEHUB_TOOL_ATTEMPTS = 'lobehub.tool.attempts' as const;++/** Internal LobeHub tool source (`builtin` / `client` / `mcp` / `klavis` / `lobehubSkill`). */+export const ATTR_LOBEHUB_TOOL_SOURCE = 'lobehub.tool.source' as const;++/** Context engineering metadata. */+export const ATTR_LOBEHUB_CONTEXT_MESSAGE_COUNT = 'lobehub.context.message_count' as const;+export const ATTR_LOBEHUB_CONTEXT_TOKEN_USAGE = 'lobehub.context.token_usage' as const;+export const ATTR_LOBEHUB_CONTEXT_WINDOW_RATIO = 'lobehub.context.window_ratio' as const;+export const ATTR_LOBEHUB_CONTEXT_KNOWLEDGE_INJECTED =+ 'lobehub.context.knowledge_injected' as const;+export const ATTR_LOBEHUB_CONTEXT_KNOWLEDGE_COUNT = 'lobehub.context.knowledge_count' as const;+export const ATTR_LOBEHUB_CONTEXT_HISTORY_COMPRESSED =+ 'lobehub.context.history_compressed' as const;+export const ATTR_LOBEHUB_CONTEXT_MEMORY_INJECTED = 'lobehub.context.memory_injected' as const;+export const ATTR_LOBEHUB_CONTEXT_SYSTEM_ROLE_LENGTH =+ 'lobehub.context.system_role_length' as const;+export const ATTR_LOBEHUB_CONTEXT_TOOL_COUNT = 'lobehub.context.tool_count' as const;+export const ATTR_LOBEHUB_CONTEXT_HAS_IMAGES = 'lobehub.context.has_images' as const;++// ---- Fixed operation.name values ----++export const GEN_AI_OPERATION_CHAT = 'chat' as const;+export const GEN_AI_OPERATION_INVOKE_AGENT = 'invoke_agent' as const;+export const GEN_AI_OPERATION_EXECUTE_TOOL = 'execute_tool' as const;diff --git a/packages/observability-otel/vitest.config.mts b/packages/observability-otel/vitest.config.mtsnew file mode 100644index 00000000000..3a7adcecec5--- /dev/null+++ b/packages/observability-otel/vitest.config.mts@@ -0,0 +1,9 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ globals: true,+ include: ['src/**/*.{test,spec}.?(c|m)[jt]s?(x)'],+ },+});diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 108e0791456..c6d45f6d88b 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -32,6 +32,24 @@ import {} from '@lobechat/context-engine';import { parse } from '@lobechat/conversation-flow';import { consumeStreamUntilDone } from '@lobechat/model-runtime';+import {+ context as otelContext,+ SpanKind,+ SpanStatusCode,+ trace as otelTrace,+} from '@lobechat/observability-otel/api';+import {+ buildChatRequestAttributes,+ buildChatResponseAttributes,+ buildContextEngineeringAttributes,+ buildExecuteToolAttributes,+ buildExecuteToolResultAttributes,+ chatSpanName,+ CONTEXT_ENGINEERING_SPAN_NAME,+ executeToolSpanName,+ type ToolType,+ tracer as agentRuntimeTracer,+} from '@lobechat/observability-otel/modules/agent-runtime';import { chainCompressContext } from '@lobechat/prompts';import {type ChatToolPayload,@@ -92,6 +110,8 @@ const LLM_MAX_RETRIES = 5;const LLM_RETRY_BASE_DELAY_MS = 1000;const LLM_RETRY_MAX_DELAY_MS = 30_000;+const GEN_AI_FUNCTION_TOOL_TYPE: ToolType = 'function';+type ToolFailureKind = 'replan' | 'retry' | 'stop';const getToolFailureKind = (result: ToolExecutionResultResponse): ToolFailureKind | undefined => {@@ -724,7 +744,49 @@ export const createRuntimeExecutors = (...(onboardingContext && { onboardingContext }),};- processedMessages = await serverMessagesEngine(contextEngineInput);+ processedMessages = await agentRuntimeTracer.startActiveSpan(+ CONTEXT_ENGINEERING_SPAN_NAME,+ {+ attributes: buildContextEngineeringAttributes({+ hasImages: (llmPayload.messages as Array<{ content?: unknown }>).some(+ (m) =>+ Array.isArray(m.content) &&+ (m.content as Array<{ type?: string }>).some((p) => p?.type === 'image_url'),+ ),+ historyCompressed:+ Array.isArray(llmPayload.messages) &&+ llmPayload.messages.some((m: { role?: string }) => m?.role === 'compressedGroup'),+ knowledgeCount:+ (contextEngineInput.knowledge?.knowledgeBases?.length ?? 0) ++ (contextEngineInput.knowledge?.fileContents?.length ?? 0),+ knowledgeInjected:+ (contextEngineInput.knowledge?.knowledgeBases?.length ?? 0) > 0 ||+ (contextEngineInput.knowledge?.fileContents?.length ?? 0) > 0,+ memoryInjected: Boolean(contextEngineInput.userMemory?.memories),+ messageCount: llmPayload.messages.length,+ operationId,+ stepIndex,+ systemRoleLength: contextEngineInput.systemRole?.length,+ toolCount: contextEngineInput.toolsConfig?.tools?.length ?? 0,+ }),+ },+ async (ceSpan) => {+ try {+ const result = await serverMessagesEngine(contextEngineInput);+ ceSpan.setAttribute('lobehub.context.message_count', result.length);+ return result;+ } catch (error) {+ ceSpan.recordException(error as Error);+ ceSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ throw error;+ } finally {+ ceSpan.end();+ }+ },+ );// Hand context engine input/output to the trace sink out-of-band.// Omit large/redundant fields to reduce snapshot size:@@ -818,430 +880,487 @@ export const createRuntimeExecutors = (const llmMaxRetries = resolveLLMMaxRetries(provider);const maxAttempts = llmMaxRetries + 1;- for (let attempt = 1; attempt <= maxAttempts; attempt++) {- let content = '';- let toolsCalling: ChatToolPayload[] = [];- let tool_calls: MessageToolCall[] = [];- let thinkingContent = '';- const imageList: any[] = [];- let grounding: any = null;- let currentStepUsage: any = undefined;- let currentStepFinishReason: string | undefined = undefined;- let streamError: any = undefined;- const contentParts: ContentPart[] = [];- const reasoningParts: ContentPart[] = [];- const hasContentImages = false;- const hasReasoningImages = false;- textBuffer = '';- reasoningBuffer = '';-- const clearAttemptBuffers = () => {- if (textBufferTimer) {- clearTimeout(textBufferTimer);- textBufferTimer = null;- }+ // OTel chat span — wraps all retry attempts; TTFT recorded on the first+ // text/reasoning chunk regardless of which attempt produced it (the+ // semantic span represents the LLM call from the agent's perspective).+ const llmStartTime = Date.now();+ let firstChunkAt: number | undefined;+ const chatSpan = agentRuntimeTracer.startSpan(chatSpanName(model), {+ attributes: buildChatRequestAttributes({+ conversationId: state.metadata?.topicId,+ operationId,+ provider,+ requestModel: model,+ stepIndex,+ stream,+ }),+ kind: SpanKind.CLIENT,+ });+ const chatCtx = otelTrace.setSpan(otelContext.active(), chatSpan);- if (reasoningBufferTimer) {- clearTimeout(reasoningBufferTimer);- reasoningBufferTimer = null;- }+ try {+ return await otelContext.with(chatCtx, async () => {+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {+ let content = '';+ let toolsCalling: ChatToolPayload[] = [];+ let tool_calls: MessageToolCall[] = [];+ let thinkingContent = '';+ const imageList: any[] = [];+ let grounding: any = null;+ let currentStepUsage: any = undefined;+ let currentStepFinishReason: string | undefined = undefined;+ let streamError: any = undefined;+ const contentParts: ContentPart[] = [];+ const reasoningParts: ContentPart[] = [];+ const hasContentImages = false;+ const hasReasoningImages = false;+ textBuffer = '';+ reasoningBuffer = '';++ const clearAttemptBuffers = () => {+ if (textBufferTimer) {+ clearTimeout(textBufferTimer);+ textBufferTimer = null;+ }- textBuffer = '';- reasoningBuffer = '';- };+ if (reasoningBufferTimer) {+ clearTimeout(reasoningBufferTimer);+ reasoningBufferTimer = null;+ }- try {- log(- `${stagePrefix} calling model-runtime chat (attempt %d/%d, model: %s, messages: %d, tools: %d)`,- attempt,- maxAttempts,- model,- processedMessages.length,- tools?.length ?? 0,- );+ textBuffer = '';+ reasoningBuffer = '';+ };- // Call model-runtime chat- const response = await modelRuntime.chat(chatPayload, {- callback: {- onCompletion: async (data) => {- // Capture usage (may or may not include cost)- if (data.usage) {- currentStepUsage = data.usage;- }- // Capture provider's terminal finishReason so soft interrupts- // (e.g. Gemini RECITATION / MAX_TOKENS with empty content)- // are visible in tracing instead of being silently swallowed.- if (data.finishReason) {- currentStepFinishReason = data.finishReason;- }- },- onGrounding: async (groundingData) => {- log(`[${operationLogId}][grounding] %O`, groundingData);- grounding = groundingData;+ try {+ log(+ `${stagePrefix} calling model-runtime chat (attempt %d/%d, model: %s, messages: %d, tools: %d)`,+ attempt,+ maxAttempts,+ model,+ processedMessages.length,+ tools?.length ?? 0,+ );- await streamManager.publishStreamChunk(operationId, stepIndex, {- chunkType: 'grounding',- grounding: groundingData,- });- },- onText: async (text) => {- timing(- '[%s] onText received chunk at %d, length: %d',- operationLogId,- Date.now(),- text.length,- );- content += text;+ // Call model-runtime chat+ const response = await modelRuntime.chat(chatPayload, {+ callback: {+ onCompletion: async (data) => {+ // Capture usage (may or may not include cost)+ if (data.usage) {+ currentStepUsage = data.usage;+ }+ // Capture provider's terminal finishReason so soft interrupts+ // (e.g. Gemini RECITATION / MAX_TOKENS with empty content)+ // are visible in tracing instead of being silently swallowed.+ if (data.finishReason) {+ currentStepFinishReason = data.finishReason;+ }+ },+ onGrounding: async (groundingData) => {+ log(`[${operationLogId}][grounding] %O`, groundingData);+ grounding = groundingData;++ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'grounding',+ grounding: groundingData,+ });+ },+ onText: async (text) => {+ if (firstChunkAt === undefined) {+ firstChunkAt = Date.now() - llmStartTime;+ }+ timing(+ '[%s] onText received chunk at %d, length: %d',+ operationLogId,+ Date.now(),+ text.length,+ );+ content += text;++ textBuffer += text;++ // If no timer exists, create one+ if (!textBufferTimer) {+ textBufferTimer = setTimeout(async () => {+ await flushTextBuffer();+ textBufferTimer = null;+ }, BUFFER_INTERVAL);+ }+ },+ onThinking: async (reasoning) => {+ if (firstChunkAt === undefined) {+ firstChunkAt = Date.now() - llmStartTime;+ }+ timing(+ '[%s] onThinking received chunk at %d, length: %d',+ operationLogId,+ Date.now(),+ reasoning.length,+ );+ thinkingContent += reasoning;++ // Buffer reasoning content+ reasoningBuffer += reasoning;++ // If no timer exists, create one+ if (!reasoningBufferTimer) {+ reasoningBufferTimer = setTimeout(async () => {+ await flushReasoningBuffer();+ reasoningBufferTimer = null;+ }, BUFFER_INTERVAL);+ }+ },+ onToolsCalling: async ({ toolsCalling: raw }) => {+ const resolvedCalls = new ToolNameResolver().resolve(raw, resolved.manifestMap);+ // Attach source (origin) and executor (dispatch target) for routing.+ // `arguments` are kept RAW here on purpose so the tool executor can+ // still detect malformed JSON and return an `INVALID_JSON_ARGUMENTS`+ // tool-result with the original bad string — that's the+ // self-reflection signal the model needs to fix its own output.+ // Sanitization happens later, only at the persist boundaries+ // (DB write and state.messages push) to protect strict providers+ // replaying history. See .+ const payload = resolvedCalls.map((p) => ({+ ...p,+ executor: resolved.executorMap?.[p.identifier],+ source: resolved.sourceMap[p.identifier],+ }));+ // log(`[${operationLogId}][toolsCalling]`, payload);+ toolsCalling = payload;+ tool_calls = raw;++ // If textBuffer exists, flush it first+ if (!!textBuffer) {+ await flushTextBuffer();+ }++ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'tools_calling',+ toolsCalling: payload,+ });+ },+ onError: async (errorData) => {+ streamError = errorData;+ console.error(`[${operationLogId}][stream_error]`, errorData);+ },+ },+ metadata: {+ operationId,+ topicId: state.metadata?.topicId,+ trigger: state.metadata?.trigger,+ },+ user: ctx.userId,+ });- textBuffer += text;+ // Consume stream to ensure all callbacks complete execution+ await consumeStreamUntilDone(response);- // If no timer exists, create one- if (!textBufferTimer) {- textBufferTimer = setTimeout(async () => {- await flushTextBuffer();- textBufferTimer = null;- }, BUFFER_INTERVAL);- }- },- onThinking: async (reasoning) => {- timing(- '[%s] onThinking received chunk at %d, length: %d',- operationLogId,- Date.now(),- reasoning.length,+ // If a stream error was captured via onError callback, throw to propagate the error+ if (streamError) {+ const streamExecutionError = new Error(+ typeof streamError.message === 'string'+ ? `LLM stream error: ${streamError.message}`+ : `LLM stream error: ${JSON.stringify(streamError)}`,);- thinkingContent += reasoning;-- // Buffer reasoning content- reasoningBuffer += reasoning;-- // If no timer exists, create one- if (!reasoningBufferTimer) {- reasoningBufferTimer = setTimeout(async () => {- await flushReasoningBuffer();- reasoningBufferTimer = null;- }, BUFFER_INTERVAL);- }- },- onToolsCalling: async ({ toolsCalling: raw }) => {- const resolvedCalls = new ToolNameResolver().resolve(raw, resolved.manifestMap);- // Attach source (origin) and executor (dispatch target) for routing.- // `arguments` are kept RAW here on purpose so the tool executor can- // still detect malformed JSON and return an `INVALID_JSON_ARGUMENTS`- // tool-result with the original bad string — that's the- // self-reflection signal the model needs to fix its own output.- // Sanitization happens later, only at the persist boundaries- // (DB write and state.messages push) to protect strict providers- // replaying history. See .- const payload = resolvedCalls.map((p) => ({- ...p,- executor: resolved.executorMap?.[p.identifier],- source: resolved.sourceMap[p.identifier],- }));- // log(`[${operationLogId}][toolsCalling]`, payload);- toolsCalling = payload;- tool_calls = raw;-- // If textBuffer exists, flush it first- if (!!textBuffer) {- await flushTextBuffer();- }-- await streamManager.publishStreamChunk(operationId, stepIndex, {- chunkType: 'tools_calling',- toolsCalling: payload,- });- },- onError: async (errorData) => {- streamError = errorData;- console.error(`[${operationLogId}][stream_error]`, errorData);- },- },- metadata: {- operationId,- topicId: state.metadata?.topicId,- trigger: state.metadata?.trigger,- },- user: ctx.userId,- });-- // Consume stream to ensure all callbacks complete execution- await consumeStreamUntilDone(response);+ const { message: _message, ...restStreamError } = streamError as Record<+ string,+ unknown+ >;+ Object.assign(streamExecutionError, restStreamError);+ throw streamExecutionError;+ }- // If a stream error was captured via onError callback, throw to propagate the error- if (streamError) {- const streamExecutionError = new Error(- typeof streamError.message === 'string'- ? `LLM stream error: ${streamError.message}`- : `LLM stream error: ${JSON.stringify(streamError)}`,- );- const { message: _message, ...restStreamError } = streamError as Record<- string,- unknown- >;- Object.assign(streamExecutionError, restStreamError);- throw streamExecutionError;- }+ await flushTextBuffer();+ await flushReasoningBuffer();+ clearAttemptBuffers();- await flushTextBuffer();- await flushReasoningBuffer();- clearAttemptBuffers();+ log(+ `[${operationLogId}] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s`,+ content.length,+ thinkingContent.length,+ toolsCalling.length,+ currentStepUsage ? 'yes' : 'none',+ );- log(- `[${operationLogId}] finish model-runtime calling | content: %d chars | reasoning: %d chars | tools: %d | usage: %s`,- content.length,- thinkingContent.length,- toolsCalling.length,- currentStepUsage ? 'yes' : 'none',- );+ if (thinkingContent) {+ log(`[${operationLogId}][reasoning]`, thinkingContent);+ }+ if (content) {+ log(`[${operationLogId}][content]`, content);+ }+ if (toolsCalling.length > 0) {+ log(`[${operationLogId}][toolsCalling] `, toolsCalling);+ }- if (thinkingContent) {- log(`[${operationLogId}][reasoning]`, thinkingContent);- }- if (content) {- log(`[${operationLogId}][content]`, content);- }- if (toolsCalling.length > 0) {- log(`[${operationLogId}][toolsCalling] `, toolsCalling);- }+ // Log usage information+ if (currentStepUsage) {+ log(`[${operationLogId}][usage] %O`, currentStepUsage);+ }- // Log usage information- if (currentStepUsage) {- log(`[${operationLogId}][usage] %O`, currentStepUsage);- }+ // Add a complete llm_stream event (including all streaming chunks)+ events.push({+ result: {+ content,+ finishReason: currentStepFinishReason,+ reasoning: thinkingContent,+ tool_calls,+ usage: currentStepUsage,+ },+ type: 'llm_result',+ });- // Add a complete llm_stream event (including all streaming chunks)- events.push({- result: {- content,- finishReason: currentStepFinishReason,- reasoning: thinkingContent,- tool_calls,- usage: currentStepUsage,- },- type: 'llm_result',- });+ // Publish stream end event+ await streamManager.publishStreamEvent(operationId, {+ data: {+ finalContent: content,+ grounding,+ ...(stepLabel && { stepLabel }),+ imageList: imageList.length > 0 ? imageList : undefined,+ reasoning: thinkingContent || undefined,+ toolsCalling,+ usage: currentStepUsage,+ },+ stepIndex,+ type: 'stream_end',+ });- // Publish stream end event- await streamManager.publishStreamEvent(operationId, {- data: {- finalContent: content,- grounding,- ...(stepLabel && { stepLabel }),- imageList: imageList.length > 0 ? imageList : undefined,- reasoning: thinkingContent || undefined,- toolsCalling,- usage: currentStepUsage,- },- stepIndex,- type: 'stream_end',- });+ log('[%s:%d] call_llm completed', operationId, stepIndex);++ // ===== 1. First save original usage to message.metadata =====+ // Determine final content - use serialized parts if has images, otherwise plain text+ const finalContent = hasContentImages+ ? serializePartsForStorage(contentParts)+ : content;++ // Determine final reasoning - handle multimodal reasoning+ let finalReasoning: any = undefined;+ if (hasReasoningImages) {+ // Has images, use multimodal format+ finalReasoning = {+ content: serializePartsForStorage(reasoningParts),+ isMultimodal: true,+ };+ } else if (thinkingContent) {+ // Has text from reasoning but no images+ finalReasoning = {+ content: thinkingContent,+ };+ }- log('[%s:%d] call_llm completed', operationId, stepIndex);+ try {+ // Build metadata object+ const metadata: Record<string, any> = {};+ if (currentStepUsage && typeof currentStepUsage === 'object') {+ Object.assign(metadata, currentStepUsage);+ }+ if (hasContentImages) {+ metadata.isMultimodal = true;+ }- // ===== 1. First save original usage to message.metadata =====- // Determine final content - use serialized parts if has images, otherwise plain text- const finalContent = hasContentImages ? serializePartsForStorage(contentParts) : content;+ // Sanitize tool_call `arguments` before persisting to DB so malformed+ // JSON (e.g. Qwen emitting `{, ...}`) can't poison future context+ // builds and 400 strict providers like NVIDIA NIM. See .+ const persistedTools =+ toolsCalling.length > 0+ ? toolsCalling.map((t) => ({+ ...t,+ arguments: sanitizeToolCallArguments(t.arguments),+ }))+ : undefined;++ await ctx.messageModel.update(assistantMessageItem.id, {+ content: finalContent,+ imageList: imageList.length > 0 ? imageList : undefined,+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,+ reasoning: finalReasoning,+ search: grounding,+ tools: persistedTools,+ });+ } catch (error) {+ console.error('[call_llm] Failed to update message:', error);+ }- // Determine final reasoning - handle multimodal reasoning- let finalReasoning: any = undefined;- if (hasReasoningImages) {- // Has images, use multimodal format- finalReasoning = {- content: serializePartsForStorage(reasoningParts),- isMultimodal: true,- };- } else if (thinkingContent) {- // Has text from reasoning but no images- finalReasoning = {- content: thinkingContent,- };- }+ // ===== 2. Then accumulate to AgentState =====+ const newState = structuredClone(state);++ // state.messages flows into the next LLM call payload, so entries+ // must be safe for strict-provider history replay:+ // - drop tool_calls with empty name (undispatchable, and strict+ // providers 400 on nameless entries)+ // - coerce malformed JSON `arguments` to valid JSON+ const sanitizedToolCalls =+ tool_calls.length > 0+ ? tool_calls+ .filter((tc) => !!tc.function.name)+ .map((tc) => ({+ ...tc,+ function: {+ ...tc.function,+ arguments: sanitizeToolCallArguments(tc.function.arguments),+ },+ }))+ : [];+ const stateToolCalls = sanitizedToolCalls.length > 0 ? sanitizedToolCalls : undefined;++ newState.messages.push({+ content,+ id: assistantMessageItem.id,+ reasoning: finalReasoning,+ role: 'assistant',+ tool_calls: stateToolCalls,+ });- try {- // Build metadata object- const metadata: Record<string, any> = {};- if (currentStepUsage && typeof currentStepUsage === 'object') {- Object.assign(metadata, currentStepUsage);- }- if (hasContentImages) {- metadata.isMultimodal = true;- }+ if (currentStepUsage) {+ // Use UsageCounter to uniformly accumulate usage and cost+ const { usage, cost } = UsageCounter.accumulateLLM({+ cost: newState.cost,+ model: llmPayload.model,+ modelUsage: currentStepUsage,+ provider: llmPayload.provider,+ usage: newState.usage,+ });- // Sanitize tool_call `arguments` before persisting to DB so malformed- // JSON (e.g. Qwen emitting `{, ...}`) can't poison future context- // builds and 400 strict providers like NVIDIA NIM. See .- const persistedTools =- toolsCalling.length > 0- ? toolsCalling.map((t) => ({- ...t,- arguments: sanitizeToolCallArguments(t.arguments),- }))- : undefined;-- await ctx.messageModel.update(assistantMessageItem.id, {- content: finalContent,- imageList: imageList.length > 0 ? imageList : undefined,- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,- reasoning: finalReasoning,- search: grounding,- tools: persistedTools,- });- } catch (error) {- console.error('[call_llm] Failed to update message:', error);- }+ newState.usage = usage;+ if (cost) newState.cost = cost;+ }- // ===== 2. Then accumulate to AgentState =====- const newState = structuredClone(state);+ // Propagate stepLabel from instruction to state metadata for hook consumers+ if (stepLabel) {+ if (!newState.metadata) newState.metadata = {};+ newState.metadata._stepLabel = stepLabel;+ }- // state.messages flows into the next LLM call payload, so entries- // must be safe for strict-provider history replay:- // - drop tool_calls with empty name (undispatchable, and strict- // providers 400 on nameless entries)- // - coerce malformed JSON `arguments` to valid JSON- const sanitizedToolCalls =- tool_calls.length > 0- ? tool_calls- .filter((tc) => !!tc.function.name)- .map((tc) => ({- ...tc,- function: {- ...tc.function,- arguments: sanitizeToolCallArguments(tc.function.arguments),- },- }))- : [];- const stateToolCalls = sanitizedToolCalls.length > 0 ? sanitizedToolCalls : undefined;-- newState.messages.push({- content,- id: assistantMessageItem.id,- reasoning: finalReasoning,- role: 'assistant',- tool_calls: stateToolCalls,- });+ // Record chat response attributes on the OTel span.+ const usageRecord = currentStepUsage as+ | {+ inputCachedTokens?: number;+ outputReasoningTokens?: number;+ totalInputTokens?: number;+ totalOutputTokens?: number;+ }+ | undefined;+ chatSpan.setAttributes(+ buildChatResponseAttributes({+ cacheReadInputTokens: usageRecord?.inputCachedTokens,+ finishReasons: currentStepFinishReason ? [currentStepFinishReason] : undefined,+ inputTokens: usageRecord?.totalInputTokens,+ outputTokens: usageRecord?.totalOutputTokens,+ reasoningOutputTokens: usageRecord?.outputReasoningTokens,+ timeToFirstChunkMs: firstChunkAt,+ }),+ );- if (currentStepUsage) {- // Use UsageCounter to uniformly accumulate usage and cost- const { usage, cost } = UsageCounter.accumulateLLM({- cost: newState.cost,- model: llmPayload.model,- modelUsage: currentStepUsage,- provider: llmPayload.provider,- usage: newState.usage,- });+ return {+ events,+ newState,+ nextContext: {+ payload: {+ hasToolsCalling: toolsCalling.length > 0,+ // Pass assistant message ID as parentMessageId for tool calls+ parentMessageId: assistantMessageItem.id,+ result: { content, tool_calls },+ toolsCalling,+ } as GeneralAgentCallLLMResultPayload,+ phase: 'llm_result' as const,+ session: {+ eventCount: events.length,+ messageCount: newState.messages.length,+ sessionId: operationId,+ status: 'running' as const,+ stepCount: state.stepCount + 1,+ },+ stepUsage: currentStepUsage,+ },+ };+ } catch (error) {+ clearAttemptBuffers();- newState.usage = usage;- if (cost) newState.cost = cost;- }+ const classified = classifyLLMError(error);+ const interrupted = await isOperationInterrupted(ctx);- // Propagate stepLabel from instruction to state metadata for hook consumers- if (stepLabel) {- if (!newState.metadata) newState.metadata = {};- newState.metadata._stepLabel = stepLabel;- }+ if (!interrupted && shouldRetryLLM(classified.kind, attempt, llmMaxRetries)) {+ const delayMs = getLLMRetryDelayMs(attempt);- return {- events,- newState,- nextContext: {- payload: {- hasToolsCalling: toolsCalling.length > 0,- // Pass assistant message ID as parentMessageId for tool calls- parentMessageId: assistantMessageItem.id,- result: { content, tool_calls },- toolsCalling,- } as GeneralAgentCallLLMResultPayload,- phase: 'llm_result',- session: {- eventCount: events.length,- messageCount: newState.messages.length,- sessionId: operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- stepUsage: currentStepUsage,- },- };- } catch (error) {- clearAttemptBuffers();+ log(+ '[%s] LLM call failed with kind=%s (attempt %d/%d), retrying in %dms ...',+ operationLogId,+ classified.kind,+ attempt,+ maxAttempts,+ delayMs,+ );- const classified = classifyLLMError(error);- const interrupted = await isOperationInterrupted(ctx);+ await streamManager.publishStreamEvent(operationId, {+ data: { attempt: attempt + 1, delayMs, maxAttempts },+ stepIndex,+ type: 'stream_retry',+ });- if (!interrupted && shouldRetryLLM(classified.kind, attempt, llmMaxRetries)) {- const delayMs = getLLMRetryDelayMs(attempt);+ await sleep(delayMs);- log(- '[%s] LLM call failed with kind=%s (attempt %d/%d), retrying in %dms ...',- operationLogId,- classified.kind,- attempt,- maxAttempts,- delayMs,- );+ if (await isOperationInterrupted(ctx)) {+ throw error;+ }- await streamManager.publishStreamEvent(operationId, {- data: { attempt: attempt + 1, delayMs, maxAttempts },- stepIndex,- type: 'stream_retry',- });+ continue;+ }- await sleep(delayMs);+ // LOBE-9523: cancel/interrupt path — the model-runtime stream was aborted+ // before reaching the post-stream finalize, so the DB row is still the+ // LOADING_FLAT placeholder. Persist whatever partial content the stream+ // callbacks already accumulated so reload/end snapshots do not clobber+ // the client's in-memory streamed content.+ if (interrupted && (content || thinkingContent || toolsCalling.length > 0)) {+ try {+ const persistedTools =+ toolsCalling.length > 0+ ? toolsCalling.map((t) => ({+ ...t,+ arguments: sanitizeToolCallArguments(t.arguments),+ }))+ : undefined;+ const interruptedReasoning = thinkingContent+ ? { content: thinkingContent }+ : undefined;+ const interruptedMetadata: Record<string, any> = { interruptedMidStream: true };+ if (currentStepUsage && typeof currentStepUsage === 'object') {+ Object.assign(interruptedMetadata, currentStepUsage);+ }+ await ctx.messageModel.update(assistantMessageItem.id, {+ content,+ metadata: interruptedMetadata,+ reasoning: interruptedReasoning,+ tools: persistedTools,+ });+ log(+ '[%s] Interrupted finalize: persisted partial content (c=%d r=%d tools=%d)',+ operationLogId,+ content.length,+ thinkingContent.length,+ toolsCalling.length,+ );+ } catch (persistErr) {+ log('[%s] Interrupted finalize update failed: %O', operationLogId, persistErr);+ }+ }- if (await isOperationInterrupted(ctx)) {throw error;}-- continue;- }-- // Cancel/interrupt path — the model-runtime stream was aborted- // before reaching the post-stream finalize at line 1078, so the DB row is- // still the LOADING_FLAT placeholder. Persist whatever partial content the- // `onText` / `onThinking` / `onToolsCalling` callbacks already accumulated- // so (a) a subsequent reload still shows the user's streamed answer, and- // (b) the agent_runtime_end uiMessages snapshot doesn't carry placeholder- // values that would clobber the client's in-memory streamed content.- if (interrupted && (content || thinkingContent || toolsCalling.length > 0)) {- try {- const persistedTools =- toolsCalling.length > 0- ? toolsCalling.map((t) => ({- ...t,- arguments: sanitizeToolCallArguments(t.arguments),- }))- : undefined;- const interruptedReasoning = thinkingContent- ? { content: thinkingContent }- : undefined;- const interruptedMetadata: Record<string, any> = { interruptedMidStream: true };- if (currentStepUsage && typeof currentStepUsage === 'object') {- Object.assign(interruptedMetadata, currentStepUsage);- }- await ctx.messageModel.update(assistantMessageItem.id, {- content,- metadata: interruptedMetadata,- reasoning: interruptedReasoning,- tools: persistedTools,- });- log(- '[%s] Interrupted finalize: persisted partial content (c=%d r=%d tools=%d)',- operationLogId,- content.length,- thinkingContent.length,- toolsCalling.length,- );- } catch (persistErr) {- log('[%s] Interrupted finalize update failed: %O', operationLogId, persistErr);- }}- throw error;- }+ throw new Error('LLM execution retry loop exited unexpectedly');+ });+ } catch (error) {+ chatSpan.recordException(error as Error);+ chatSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ throw error;+ } finally {+ chatSpan.end();}-- throw new Error('LLM execution retry loop exited unexpectedly');} catch (error) {// Publish error eventawait streamManager.publishStreamEvent(operationId, {@@ -1600,450 +1719,479 @@ export const createRuntimeExecutors = (// Keep malformed tool arguments as an empty preview payload; execution still uses raw args.}+ // OTel execute_tool span. Created up-front so it survives every exit path+ // (client-tool pause / success / error), ended in finally.+ const toolSource =+ state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??+ state.toolSourceMap?.[chatToolPayload.identifier];+ const executeToolSpan = agentRuntimeTracer.startSpan(executeToolSpanName(toolName), {+ attributes: buildExecuteToolAttributes({+ operationId,+ stepIndex,+ toolCallId: chatToolPayload.id,+ toolName,+ toolSource,+ toolType: GEN_AI_FUNCTION_TOOL_TYPE,+ }),+ });+try {- // Check if this is a client-side function tool — pause instead of executing- const toolSource =- state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??- state.toolSourceMap?.[chatToolPayload.identifier];-- if (toolSource === 'client') {- log(`[${operationLogId}] Client function tool detected: ${toolName}, pausing for client`);-- // Publish tool call info so streaming can emit function_call events- await streamManager.publishStreamChunk(operationId, stepIndex, {- chunkType: 'tools_calling',- toolsCalling: [chatToolPayload] as any,- });+ try {+ if (toolSource === 'client') {+ log(`[${operationLogId}] Client function tool detected: ${toolName}, pausing for client`);- const newState = structuredClone(state);- newState.lastModified = new Date().toISOString();- newState.status = 'interrupted';- newState.interruption = {- canResume: true,- interruptedAt: new Date().toISOString(),- interruptedInstruction: instruction,- reason: 'client_tool_execution',- };- newState.pendingToolsCalling = [chatToolPayload];+ // Publish tool call info so streaming can emit function_call events+ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'tools_calling',+ toolsCalling: [chatToolPayload] as any,+ });- return {- events: [- {- canResume: true,- interruptedAt: new Date().toISOString(),- reason: 'client_tool_execution',- type: 'interrupted',- },- ],- newState,- // No nextContext — loop stops, waiting for client to provide tool result+ const newState = structuredClone(state);+ newState.lastModified = new Date().toISOString();+ newState.status = 'interrupted';+ newState.interruption = {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ interruptedInstruction: instruction,+ reason: 'client_tool_execution',+ };+ newState.pendingToolsCalling = [chatToolPayload];++ return {+ events: [+ {+ canResume: true,+ interruptedAt: new Date().toISOString(),+ reason: 'client_tool_execution',+ type: 'interrupted',+ },+ ],+ newState,+ // No nextContext — loop stops, waiting for client to provide tool result+ };+ }++ // Extract toolResultMaxLength from agent config+ const agentConfig = state.metadata?.agentConfig;+ const toolResultMaxLength = agentConfig?.chatConfig?.toolResultMaxLength;++ // Build effective manifest map (operation + step-level activations)+ const effectiveManifestMap = {+ ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),+ ...Object.fromEntries(+ (state.activatedStepTools ?? [])+ .filter((a) => a.manifest)+ .map((a) => [a.id, a.manifest!]),+ ),};- }- // Extract toolResultMaxLength from agent config- const agentConfig = state.metadata?.agentConfig;- const toolResultMaxLength = agentConfig?.chatConfig?.toolResultMaxLength;-- // Build effective manifest map (operation + step-level activations)- const effectiveManifestMap = {- ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),- ...Object.fromEntries(- (state.activatedStepTools ?? [])- .filter((a) => a.manifest)- .map((a) => [a.id, a.manifest!]),- ),- };+ // Route to client via Agent Gateway WS when the tool is marked+ // executor='client' and the current stream manager can reach a gateway.+ // Falls through to the normal server path if either is unavailable.+ const canDispatchToClient =+ chatToolPayload.executor === 'client' &&+ typeof streamManager.sendToolExecute === 'function';++ let toolCallMocked = false;+ const hookResult = ctx.hookDispatcher+ ? await (async () => {+ // 1. dispatch for observation (webhook in production, local handler logging)+ ctx+ .hookDispatcher!.dispatch(+ operationId,+ 'beforeToolCall',+ {+ apiName: chatToolPayload.apiName,+ args: parsedArgs,+ callIndex,+ identifier: chatToolPayload.identifier,+ operationId,+ stepIndex,+ userId: ctx.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});+ // 2. dispatchBeforeToolCall for mock support (local-only)+ return ctx.hookDispatcher!.dispatchBeforeToolCall(operationId, {+ apiName: chatToolPayload.apiName,+ args: parsedArgs,+ callIndex,+ identifier: chatToolPayload.identifier,+ stepIndex,+ });+ })()+ : null;++ let execution: { result: ToolExecutionResultResponse; attempts: number };+ if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {+ // Per-call audit for device tools (local-system / remote-device).+ // Emitted before dispatch so the record exists even if dispatch+ // throws. We rely on the engine's enable gate to keep `canUseDevice`+ // true here; recording the policy reason inline lets an operator+ // distinguish first-party vs bot-owner runs without joining logs.+ const policy = state.metadata?.deviceAccessPolicy as+ | { canUseDevice: boolean; reason: DeviceAccessReason }+ | undefined;+ logDeviceToolAudit({+ apiName: chatToolPayload.apiName,+ botContext: state.metadata?.botContext,+ canUseDevice: policy?.canUseDevice ?? true,+ messageId: state.metadata?.sourceMessageId,+ operationId,+ reason: policy?.reason ?? 'first-party',+ toolIdentifier: chatToolPayload.identifier,+ topicId: ctx.topicId,+ userId: ctx.userId,+ });+ }- // Route to client via Agent Gateway WS when the tool is marked- // executor='client' and the current stream manager can reach a gateway.- // Falls through to the normal server path if either is unavailable.- const canDispatchToClient =- chatToolPayload.executor === 'client' &&- typeof streamManager.sendToolExecute === 'function';-- let toolCallMocked = false;- const hookResult = ctx.hookDispatcher- ? await (async () => {- // 1. dispatch for observation (webhook in production, local handler logging)- ctx- .hookDispatcher!.dispatch(+ if (hookResult?.isMocked) {+ log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);+ toolCallMocked = true;+ execution = {+ attempts: 0,+ result: { content: hookResult.content, executionTime: 0, success: true },+ };+ } else if (canDispatchToClient) {+ log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);+ const timeoutMs = resolveToolTimeoutMs({+ apiName: chatToolPayload.apiName,+ args: parsedArgs,+ manifest: effectiveManifestMap[chatToolPayload.identifier],+ });+ const dispatchResult = await dispatchClientTool(chatToolPayload, {+ operationId,+ streamManager,+ timeoutMs,+ });+ execution = { attempts: 1, result: dispatchResult };+ } else {+ // Inject source from sourceMap so BuiltinToolsExecutor can route+ // lobehubSkill / klavis tools correctly (LLM responses don't carry source)+ if (toolSource && !chatToolPayload.source) {+ chatToolPayload.source = toolSource;+ }++ // Execute tool using ToolExecutionService+ log(`[${operationLogId}] Executing tool ${toolName} ...`);+ execution = await executeToolWithRetry(+ () =>+ toolExecutionService.executeTool(chatToolPayload, {+ activeDeviceId: state.metadata?.activeDeviceId,+ agentId: state.metadata?.agentId,+ documentId: state.metadata?.documentId,+ groupId: state.metadata?.groupId,+ memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,+ messageId: state.metadata?.sourceMessageId,operationId,- 'beforeToolCall',- {- apiName: chatToolPayload.apiName,- args: parsedArgs,- callIndex,- identifier: chatToolPayload.identifier,- operationId,- stepIndex,- userId: ctx.userId,- },- state.metadata?._hooks,- )- .catch(() => {});- // 2. dispatchBeforeToolCall for mock support (local-only)- return ctx.hookDispatcher!.dispatchBeforeToolCall(operationId, {- apiName: chatToolPayload.apiName,- args: parsedArgs,- callIndex,- identifier: chatToolPayload.identifier,- stepIndex,- });- })()- : null;-- let execution: { result: ToolExecutionResultResponse; attempts: number };- if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {- // Per-call audit for device tools (local-system / remote-device).- // Emitted before dispatch so the record exists even if dispatch- // throws. We rely on the engine's enable gate to keep `canUseDevice`- // true here; recording the policy reason inline lets an operator- // distinguish first-party vs bot-owner runs without joining logs.- const policy = state.metadata?.deviceAccessPolicy as- | { canUseDevice: boolean; reason: DeviceAccessReason }- | undefined;- logDeviceToolAudit({- apiName: chatToolPayload.apiName,- botContext: state.metadata?.botContext,- canUseDevice: policy?.canUseDevice ?? true,- messageId: state.metadata?.sourceMessageId,- operationId,- reason: policy?.reason ?? 'first-party',- toolIdentifier: chatToolPayload.identifier,- topicId: ctx.topicId,+ projectSkills: (state.metadata?.operationSkillSet?.skills ?? [])+ .filter(+ (skill: { location?: string; source?: string }) =>+ skill.source === 'project' && !!skill.location,+ )+ .map((skill: { location: string; name: string }) => ({+ location: skill.location,+ name: skill.name,+ })),+ scope: state.metadata?.scope,+ serverDB: ctx.serverDB,+ skipResultTruncation: true,+ taskId: state.metadata?.taskId,+ threadId: state.metadata?.threadId,+ toolCallId: chatToolPayload.id,+ toolManifestMap: effectiveManifestMap,+ toolResultMaxLength,+ topicId: ctx.topicId,+ userId: ctx.userId,+ }),+ {+ isInterrupted: () => isOperationInterrupted(ctx),+ maxRetries: TOOL_MAX_RETRIES,+ operationLogId,+ toolName,+ },+ );+ }++ const executionResult = await archiveRuntimeToolResult(execution.result, {+ agentId: state.metadata?.agentId,+ identifier: chatToolPayload.identifier,+ limit: toolResultMaxLength,+ serverDB: ctx.serverDB,+ toolCallId: chatToolPayload.id,+ topicId: ctx.topicId ?? state.metadata?.topicId,userId: ctx.userId,});- }+ const executionTime = executionResult.executionTime;+ const isSuccess = executionResult.success;+ if (ctx.hookDispatcher) {+ ctx.hookDispatcher+ .dispatch(+ operationId,+ 'afterToolCall',+ {+ apiName: chatToolPayload.apiName,+ args: parsedArgs,+ callIndex,+ content: executionResult.content,+ executionTimeMs: executionTime,+ identifier: chatToolPayload.identifier,+ mocked: toolCallMocked,+ operationId,+ stepIndex,+ success: isSuccess,+ userId: ctx.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});+ }+ log(+ `[${operationLogId}] Executing ${toolName} in ${executionTime}ms, result: %O`,+ executionResult,+ );- if (hookResult?.isMocked) {- log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);- toolCallMocked = true;- execution = {- attempts: 0,- result: { content: hookResult.content, executionTime: 0, success: true },- };- } else if (canDispatchToClient) {- log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);- const timeoutMs = resolveToolTimeoutMs({- apiName: chatToolPayload.apiName,- args: parsedArgs,- manifest: effectiveManifestMap[chatToolPayload.identifier],- });- const dispatchResult = await dispatchClientTool(chatToolPayload, {- operationId,- streamManager,- timeoutMs,+ // Publish tool execution result event+ await streamManager.publishStreamEvent(operationId, {+ data: {+ executionTime,+ isSuccess,+ attempts: execution.attempts,+ maxAttempts: TOOL_MAX_RETRIES + 1,+ payload,+ phase: 'tool_execution',+ result: executionResult,+ },+ stepIndex,+ type: 'tool_end',});- execution = { attempts: 1, result: dispatchResult };- } else {- // Inject source from sourceMap so BuiltinToolsExecutor can route- // lobehubSkill / klavis tools correctly (LLM responses don't carry source)- if (toolSource && !chatToolPayload.source) {- chatToolPayload.source = toolSource;- }- // Execute tool using ToolExecutionService- log(`[${operationLogId}] Executing tool ${toolName} ...`);- execution = await executeToolWithRetry(- () =>- toolExecutionService.executeTool(chatToolPayload, {- activeDeviceId: state.metadata?.activeDeviceId,- agentId: state.metadata?.agentId,- documentId: state.metadata?.documentId,- groupId: state.metadata?.groupId,- memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,- messageId: state.metadata?.sourceMessageId,- operationId,- projectSkills: (state.metadata?.operationSkillSet?.skills ?? [])- .filter(- (skill: { location?: string; source?: string }) =>- skill.source === 'project' && !!skill.location,- )- .map((skill: { location: string; name: string }) => ({- location: skill.location,- name: skill.name,- })),- scope: state.metadata?.scope,- serverDB: ctx.serverDB,- skipResultTruncation: true,- taskId: state.metadata?.taskId,- threadId: state.metadata?.threadId,- toolCallId: chatToolPayload.id,- toolManifestMap: effectiveManifestMap,- toolResultMaxLength,- topicId: ctx.topicId,- userId: ctx.userId,- }),- {- isInterrupted: () => isOperationInterrupted(ctx),- maxRetries: TOOL_MAX_RETRIES,- operationLogId,- toolName,- },- );- }-- const executionResult = await archiveRuntimeToolResult(execution.result, {- agentId: state.metadata?.agentId,- identifier: chatToolPayload.identifier,- limit: toolResultMaxLength,- serverDB: ctx.serverDB,- toolCallId: chatToolPayload.id,- topicId: ctx.topicId ?? state.metadata?.topicId,- userId: ctx.userId,- });- const executionTime = executionResult.executionTime;- const isSuccess = executionResult.success;- if (ctx.hookDispatcher) {- ctx.hookDispatcher- .dispatch(- operationId,- 'afterToolCall',- {- apiName: chatToolPayload.apiName,- args: parsedArgs,- callIndex,- content: executionResult.content,- executionTimeMs: executionTime,- identifier: chatToolPayload.identifier,- mocked: toolCallMocked,+ // Finally persist to database. In resumption mode (skipCreateToolMessage),+ // the pending tool message already exists from request_human_approve, so+ // we update it in-place rather than inserting a new row — inserting would+ // either duplicate the tool_call_id or violate parent_id FK ().+ let toolMessageId: string | undefined;+ try {+ if (payload.skipCreateToolMessage) {+ toolMessageId = payload.parentMessageId;+ await ctx.messageModel.updateToolMessage(toolMessageId, {+ content: executionResult.content,+ metadata: { toolExecutionTimeMs: executionTime },+ pluginError: executionResult.error,+ pluginState: executionResult.state,+ });+ log(+ '[%s:%d] Updated existing tool message %s (skipCreateToolMessage)',operationId,stepIndex,- success: isSuccess,- userId: ctx.userId,- },- state.metadata?._hooks,- )- .catch(() => {});- }- log(- `[${operationLogId}] Executing ${toolName} in ${executionTime}ms, result: %O`,- executionResult,- );-- // Publish tool execution result event- await streamManager.publishStreamEvent(operationId, {- data: {- executionTime,- isSuccess,- attempts: execution.attempts,- maxAttempts: TOOL_MAX_RETRIES + 1,- payload,- phase: 'tool_execution',- result: executionResult,- },- stepIndex,- type: 'tool_end',- });-- // Finally persist to database. In resumption mode (skipCreateToolMessage),- // the pending tool message already exists from request_human_approve, so- // we update it in-place rather than inserting a new row — inserting would- // either duplicate the tool_call_id or violate parent_id FK ().- let toolMessageId: string | undefined;- try {- if (payload.skipCreateToolMessage) {- toolMessageId = payload.parentMessageId;- await ctx.messageModel.updateToolMessage(toolMessageId, {- content: executionResult.content,- metadata: { toolExecutionTimeMs: executionTime },- pluginError: executionResult.error,- pluginState: executionResult.state,- });- log(- '[%s:%d] Updated existing tool message %s (skipCreateToolMessage)',- operationId,+ toolMessageId,+ );+ } else {+ const toolMessage = await ctx.messageModel.create({+ agentId: state.metadata!.agentId!,+ content: executionResult.content,+ metadata: { toolExecutionTimeMs: executionTime },+ parentId: payload.parentMessageId,+ plugin: chatToolPayload as any,+ pluginError: executionResult.error,+ pluginState: executionResult.state,+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: chatToolPayload.id,+ topicId: state.metadata?.topicId,+ });+ toolMessageId = toolMessage.id;+ }+ } catch (error) {+ console.error('[StreamingToolExecutor] Failed to persist tool message: %O', error);+ // Normalize BEFORE publishing so clients (which treat `error` stream+ // events as terminal and surface `event.data.error` directly) see the+ // typed business error, not the raw SQL / driver text.+ const fatal = isParentMessageMissingError(error)+ ? createConversationParentMissingError(payload.parentMessageId, error)+ : error instanceof Error+ ? error+ : new Error(String(error));+ await streamManager.publishStreamEvent(operationId, {+ data: formatErrorEventData(fatal, 'tool_message_persist'),stepIndex,- toolMessageId,- );- } else {- const toolMessage = await ctx.messageModel.create({- agentId: state.metadata!.agentId!,- content: executionResult.content,- metadata: { toolExecutionTimeMs: executionTime },- parentId: payload.parentMessageId,- plugin: chatToolPayload as any,- pluginError: executionResult.error,- pluginState: executionResult.state,- role: 'tool',- threadId: state.metadata?.threadId,- tool_call_id: chatToolPayload.id,- topicId: state.metadata?.topicId,+ type: 'error',});- toolMessageId = toolMessage.id;+ // Mark so the outer catch (which normally converts tool-exec errors+ // into event records and returns the unchanged state) re-throws.+ throw markPersistFatal(fatal);}- } catch (error) {- console.error('[StreamingToolExecutor] Failed to persist tool message: %O', error);- // Normalize BEFORE publishing so clients (which treat `error` stream- // events as terminal and surface `event.data.error` directly) see the- // typed business error, not the raw SQL / driver text.- const fatal = isParentMessageMissingError(error)- ? createConversationParentMissingError(payload.parentMessageId, error)- : error instanceof Error- ? error- : new Error(String(error));- await streamManager.publishStreamEvent(operationId, {- data: formatErrorEventData(fatal, 'tool_message_persist'),- stepIndex,- type: 'error',- });- // Mark so the outer catch (which normally converts tool-exec errors- // into event records and returns the unchanged state) re-throws.- throw markPersistFatal(fatal);- }-- const newState = structuredClone(state);- newState.messages.push({- content: executionResult.content,- role: 'tool',- tool_call_id: chatToolPayload.id,- });-- events.push({ id: chatToolPayload.id, result: executionResult, type: 'tool_result' });+ const newState = structuredClone(state);- // Get tool unit price- const toolCost = TOOL_PRICING[toolName] || 0;+ newState.messages.push({+ content: executionResult.content,+ role: 'tool',+ tool_call_id: chatToolPayload.id,+ });- // Use UsageCounter to uniformly accumulate tool usage- const { usage, cost } = UsageCounter.accumulateTool({- cost: newState.cost,- executionTime,- success: isSuccess,- toolCost,- toolName,- usage: newState.usage,- });+ events.push({ id: chatToolPayload.id, result: executionResult, type: 'tool_result' });- newState.usage = usage;- if (cost) newState.cost = cost;+ // Get tool unit price+ const toolCost = TOOL_PRICING[toolName] || 0;- // Persist ToolsActivator discovery results to state.activatedStepTools- const discoveredTools = executionResult.state?.activatedTools as- | Array<{ identifier: string }>- | undefined;- if (discoveredTools?.length) {- const existingIds = new Set(- (newState.activatedStepTools ?? []).map((t: { id: string }) => t.id),- );- const newActivations = discoveredTools- .filter((t) => !existingIds.has(t.identifier))- .map((t) => ({- activatedAtStep: state.stepCount,- id: t.identifier,- manifest: effectiveManifestMap[t.identifier],- source: 'discovery' as const,- }));+ // Use UsageCounter to uniformly accumulate tool usage+ const { usage, cost } = UsageCounter.accumulateTool({+ cost: newState.cost,+ executionTime,+ success: isSuccess,+ toolCost,+ toolName,+ usage: newState.usage,+ });- if (newActivations.length > 0) {- newState.activatedStepTools = [...(newState.activatedStepTools ?? []), ...newActivations];+ newState.usage = usage;+ if (cost) newState.cost = cost;- log(- `[${operationLogId}] Persisted %d tool activations to state: %o`,- newActivations.length,- newActivations.map((a) => a.id),+ // Persist ToolsActivator discovery results to state.activatedStepTools+ const discoveredTools = executionResult.state?.activatedTools as+ | Array<{ identifier: string }>+ | undefined;+ if (discoveredTools?.length) {+ const existingIds = new Set(+ (newState.activatedStepTools ?? []).map((t: { id: string }) => t.id),);+ const newActivations = discoveredTools+ .filter((t) => !existingIds.has(t.identifier))+ .map((t) => ({+ activatedAtStep: state.stepCount,+ id: t.identifier,+ manifest: effectiveManifestMap[t.identifier],+ source: 'discovery' as const,+ }));++ if (newActivations.length > 0) {+ newState.activatedStepTools = [+ ...(newState.activatedStepTools ?? []),+ ...newActivations,+ ];++ log(+ `[${operationLogId}] Persisted %d tool activations to state: %o`,+ newActivations.length,+ newActivations.map((a) => a.id),+ );+ }}- }- // Find current tool statistics- const currentToolStats = usage.tools.byTool.find((t) => t.name === toolName);+ // Find current tool statistics+ const currentToolStats = usage.tools.byTool.find((t) => t.name === toolName);- // Log usage information- log(- `[${operationLogId}][tool usage] %s: calls=%d, time=%dms, success=%s, cost=$%s`,- toolName,- currentToolStats?.calls || 0,- executionTime,- isSuccess,- toolCost.toFixed(4),- );+ // Log usage information+ log(+ `[${operationLogId}][tool usage] %s: calls=%d, time=%dms, success=%s, cost=$%s`,+ toolName,+ currentToolStats?.calls || 0,+ executionTime,+ isSuccess,+ toolCost.toFixed(4),+ );- log('[%s:%d] Tool execution completed', operationId, stepIndex);+ log('[%s:%d] Tool execution completed', operationId, stepIndex);- // When the tool result carries an execSubAgent / execSubAgents state the- // GeneralChatAgent needs `stop: true` in the payload to detect it and- // emit the matching exec_sub_agent / exec_sub_agents instruction. Without- // this flag the agent falls through to the normal LLM-call path and the- // sub-agent is never spawned.- const execTaskStateType = executionResult.state?.type as string | undefined;- const isExecTaskState =- execTaskStateType === 'execSubAgent' || execTaskStateType === 'execSubAgents';+ // When the tool result carries an execSubAgent / execSubAgents state the+ // GeneralChatAgent needs `stop: true` in the payload to detect it and+ // emit the matching exec_sub_agent / exec_sub_agents instruction. Without+ // this flag the agent falls through to the normal LLM-call path and the+ // sub-agent is never spawned.+ const execTaskStateType = executionResult.state?.type as string | undefined;+ const isExecTaskState =+ execTaskStateType === 'execSubAgent' || execTaskStateType === 'execSubAgents';- return {- events,- newState,- nextContext: {- payload: {- data: executionResult,- executionTime,- isSuccess,- // Pass tool message ID as parentMessageId for the next LLM call- parentMessageId: toolMessageId,- ...(isExecTaskState && { stop: true }),- toolCall: chatToolPayload,- toolCallId: chatToolPayload.id,- },- phase: 'tool_result',- session: {- eventCount: events.length,- messageCount: newState.messages.length,- sessionId: operationId,- status: 'running',- stepCount: state.stepCount + 1,- },- stepUsage: {- cost: toolCost,- toolName,- unitPrice: toolCost,- usageCount: 1,+ executeToolSpan.setAttributes(+ buildExecuteToolResultAttributes({ attempts: execution.attempts, success: isSuccess }),+ );++ return {+ events,+ newState,+ nextContext: {+ payload: {+ data: executionResult,+ executionTime,+ isSuccess,+ // Pass tool message ID as parentMessageId for the next LLM call+ parentMessageId: toolMessageId,+ ...(isExecTaskState && { stop: true }),+ toolCall: chatToolPayload,+ toolCallId: chatToolPayload.id,+ },+ phase: 'tool_result',+ session: {+ eventCount: events.length,+ messageCount: newState.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ stepUsage: {+ cost: toolCost,+ toolName,+ unitPrice: toolCost,+ usageCount: 1,+ },},- },- };- } catch (error) {- // Persist-level failures (parent FK violation etc.) must propagate so- // the step fails — otherwise the swallow-and-continue path keeps- // running the agent on a broken conversation chain. See .- if (isPersistFatal(error)) throw error;+ };+ } catch (error) {+ executeToolSpan.recordException(error as Error);+ executeToolSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ executeToolSpan.setAttributes(buildExecuteToolResultAttributes({ success: false }));- if (ctx.hookDispatcher) {- ctx.hookDispatcher- .dispatch(- operationId,- 'onToolCallError',- {- apiName: chatToolPayload.apiName,- args: parsedArgs,- callIndex,- error: error instanceof Error ? error.message : String(error),- identifier: chatToolPayload.identifier,+ // Persist-level failures (parent FK violation etc.) must propagate so+ // the step fails — otherwise the swallow-and-continue path keeps+ // running the agent on a broken conversation chain. See .+ if (isPersistFatal(error)) throw error;++ if (ctx.hookDispatcher) {+ ctx.hookDispatcher+ .dispatch(operationId,- stepIndex,- userId: ctx.userId,- },- state.metadata?._hooks,- )- .catch(() => {});- }+ 'onToolCallError',+ {+ apiName: chatToolPayload.apiName,+ args: parsedArgs,+ callIndex,+ error: error instanceof Error ? error.message : String(error),+ identifier: chatToolPayload.identifier,+ operationId,+ stepIndex,+ userId: ctx.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});+ }- // Publish tool execution error event- await streamManager.publishStreamEvent(operationId, {- data: formatErrorEventData(error, 'tool_execution'),- stepIndex,- type: 'error',- });+ // Publish tool execution error event+ await streamManager.publishStreamEvent(operationId, {+ data: formatErrorEventData(error, 'tool_execution'),+ stepIndex,+ type: 'error',+ });- events.push({ error, type: 'error' });+ events.push({ error, type: 'error' });- console.error(- `[StreamingToolExecutor] Tool execution failed for operation ${operationId}:${stepIndex}:`,- error,- );+ console.error(+ `[StreamingToolExecutor] Tool execution failed for operation ${operationId}:${stepIndex}:`,+ error,+ );- return {- events,- newState: state, // State unchanged- };+ return {+ events,+ newState: state, // State unchanged+ };+ }+ } finally {+ executeToolSpan.end();}},@@ -2141,281 +2289,316 @@ export const createRuntimeExecutors = (// Keep malformed tool arguments as an empty preview payload; execution still uses raw args.}+ // OTel execute_tool span — one per tool inside the concurrent batch.+ const batchToolSourceForSpan =+ state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??+ state.toolSourceMap?.[chatToolPayload.identifier];+ const batchExecuteToolSpan = agentRuntimeTracer.startSpan(executeToolSpanName(toolName), {+ attributes: buildExecuteToolAttributes({+ operationId,+ stepIndex,+ toolCallId: chatToolPayload.id,+ toolName,+ toolSource: batchToolSourceForSpan,+ toolType: GEN_AI_FUNCTION_TOOL_TYPE,+ }),+ });+try {- log(`[${operationLogId}] Executing tool ${toolName} ...`);- // Build effective manifest map (operation + step-level activations)- const batchManifestMap = {- ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),- ...Object.fromEntries(- (state.activatedStepTools ?? [])- .filter((a) => a.manifest)- .map((a) => [a.id, a.manifest!]),- ),- };+ try {+ log(`[${operationLogId}] Executing tool ${toolName} ...`);+ // Build effective manifest map (operation + step-level activations)+ const batchManifestMap = {+ ...(state.operationToolSet?.manifestMap ?? state.toolManifestMap),+ ...Object.fromEntries(+ (state.activatedStepTools ?? [])+ .filter((a) => a.manifest)+ .map((a) => [a.id, a.manifest!]),+ ),+ };- const batchAgentConfig = state.metadata?.agentConfig;+ const batchAgentConfig = state.metadata?.agentConfig;- const canDispatchToClient =- chatToolPayload.executor === 'client' &&- typeof streamManager.sendToolExecute === 'function';+ const canDispatchToClient =+ chatToolPayload.executor === 'client' &&+ typeof streamManager.sendToolExecute === 'function';- let batchToolCallMocked = false;- const batchHookResult = ctx.hookDispatcher- ? await (async () => {- ctx- .hookDispatcher!.dispatch(- operationId,- 'beforeToolCall',- {- apiName: chatToolPayload.apiName,- args: batchParsedArgs,- callIndex: batchCallIndex,- identifier: chatToolPayload.identifier,+ let batchToolCallMocked = false;+ const batchHookResult = ctx.hookDispatcher+ ? await (async () => {+ ctx+ .hookDispatcher!.dispatch(operationId,- stepIndex,- userId: ctx.userId,- },- state.metadata?._hooks,- )- .catch(() => {});- return ctx.hookDispatcher!.dispatchBeforeToolCall(operationId, {- apiName: chatToolPayload.apiName,- args: batchParsedArgs,- callIndex: batchCallIndex,- identifier: chatToolPayload.identifier,- stepIndex,- });- })()- : null;-- if (isDeviceToolIdentifier(chatToolPayload.identifier) && !batchHookResult?.isMocked) {- const policy = state.metadata?.deviceAccessPolicy as- | { canUseDevice: boolean; reason: DeviceAccessReason }- | undefined;- logDeviceToolAudit({- apiName: chatToolPayload.apiName,- botContext: state.metadata?.botContext,- canUseDevice: policy?.canUseDevice ?? true,- messageId: state.metadata?.sourceMessageId,- operationId,- reason: policy?.reason ?? 'first-party',- toolIdentifier: chatToolPayload.identifier,- topicId: ctx.topicId,- userId: ctx.userId,- });- }-- let execution: { result: ToolExecutionResultResponse; attempts: number };- if (batchHookResult?.isMocked) {- log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);- batchToolCallMocked = true;- execution = {- attempts: 0,- result: { content: batchHookResult.content, executionTime: 0, success: true },- };- } else if (canDispatchToClient) {- log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);- const timeoutMs = resolveToolTimeoutMs({- apiName: chatToolPayload.apiName,- args: batchParsedArgs,- manifest: batchManifestMap[chatToolPayload.identifier],- });- const dispatchResult = await dispatchClientTool(chatToolPayload, {- operationId,- streamManager,- timeoutMs,- });- execution = { attempts: 1, result: dispatchResult };- } else {- // Inject source from sourceMap so BuiltinToolsExecutor can route- // lobehubSkill / klavis tools correctly (LLM responses don't carry source)- const batchToolSource =- state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??- state.toolSourceMap?.[chatToolPayload.identifier];- if (batchToolSource && !chatToolPayload.source) {- chatToolPayload.source = batchToolSource;+ 'beforeToolCall',+ {+ apiName: chatToolPayload.apiName,+ args: batchParsedArgs,+ callIndex: batchCallIndex,+ identifier: chatToolPayload.identifier,+ operationId,+ stepIndex,+ userId: ctx.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});+ return ctx.hookDispatcher!.dispatchBeforeToolCall(operationId, {+ apiName: chatToolPayload.apiName,+ args: batchParsedArgs,+ callIndex: batchCallIndex,+ identifier: chatToolPayload.identifier,+ stepIndex,+ });+ })()+ : null;++ if (isDeviceToolIdentifier(chatToolPayload.identifier) && !batchHookResult?.isMocked) {+ const policy = state.metadata?.deviceAccessPolicy as+ | { canUseDevice: boolean; reason: DeviceAccessReason }+ | undefined;+ logDeviceToolAudit({+ apiName: chatToolPayload.apiName,+ botContext: state.metadata?.botContext,+ canUseDevice: policy?.canUseDevice ?? true,+ messageId: state.metadata?.sourceMessageId,+ operationId,+ reason: policy?.reason ?? 'first-party',+ toolIdentifier: chatToolPayload.identifier,+ topicId: ctx.topicId,+ userId: ctx.userId,+ });}- execution = await executeToolWithRetry(- () =>- toolExecutionService.executeTool(chatToolPayload, {- activeDeviceId: state.metadata?.activeDeviceId,- agentId: state.metadata?.agentId,- documentId: state.metadata?.documentId,- groupId: state.metadata?.groupId,- memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,- messageId: state.metadata?.sourceMessageId,- operationId,- scope: state.metadata?.scope,- serverDB: ctx.serverDB,- skipResultTruncation: true,- taskId: state.metadata?.taskId,- threadId: state.metadata?.threadId,- toolCallId: chatToolPayload.id,- toolManifestMap: batchManifestMap,- toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,- topicId: ctx.topicId,- userId: ctx.userId,- }),- {- isInterrupted: () => isOperationInterrupted(ctx),- maxRetries: TOOL_MAX_RETRIES,- operationLogId,- toolName,- },- );- }-- const executionResult = await archiveRuntimeToolResult(execution.result, {- agentId: state.metadata?.agentId,- identifier: chatToolPayload.identifier,- limit: batchAgentConfig?.chatConfig?.toolResultMaxLength,- serverDB: ctx.serverDB,- toolCallId: chatToolPayload.id,- topicId: ctx.topicId ?? state.metadata?.topicId,- userId: ctx.userId,- });- const executionTime = executionResult.executionTime;- const isSuccess = executionResult.success;- if (ctx.hookDispatcher) {- ctx.hookDispatcher- .dispatch(+ let execution: { result: ToolExecutionResultResponse; attempts: number };+ if (batchHookResult?.isMocked) {+ log(`[${operationLogId}] Tool ${toolName} mocked by beforeToolCall hook`);+ batchToolCallMocked = true;+ execution = {+ attempts: 0,+ result: { content: batchHookResult.content, executionTime: 0, success: true },+ };+ } else if (canDispatchToClient) {+ log(`[${operationLogId}] Dispatching tool ${toolName} to client via Agent Gateway`);+ const timeoutMs = resolveToolTimeoutMs({+ apiName: chatToolPayload.apiName,+ args: batchParsedArgs,+ manifest: batchManifestMap[chatToolPayload.identifier],+ });+ const dispatchResult = await dispatchClientTool(chatToolPayload, {operationId,- 'afterToolCall',+ streamManager,+ timeoutMs,+ });+ execution = { attempts: 1, result: dispatchResult };+ } else {+ // Inject source from sourceMap so BuiltinToolsExecutor can route+ // lobehubSkill / klavis tools correctly (LLM responses don't carry source)+ const batchToolSource =+ state.operationToolSet?.sourceMap?.[chatToolPayload.identifier] ??+ state.toolSourceMap?.[chatToolPayload.identifier];+ if (batchToolSource && !chatToolPayload.source) {+ chatToolPayload.source = batchToolSource;+ }++ execution = await executeToolWithRetry(+ () =>+ toolExecutionService.executeTool(chatToolPayload, {+ activeDeviceId: state.metadata?.activeDeviceId,+ agentId: state.metadata?.agentId,+ documentId: state.metadata?.documentId,+ groupId: state.metadata?.groupId,+ memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,+ messageId: state.metadata?.sourceMessageId,+ operationId,+ scope: state.metadata?.scope,+ serverDB: ctx.serverDB,+ skipResultTruncation: true,+ taskId: state.metadata?.taskId,+ threadId: state.metadata?.threadId,+ toolCallId: chatToolPayload.id,+ toolManifestMap: batchManifestMap,+ toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,+ topicId: ctx.topicId,+ userId: ctx.userId,+ }),{- apiName: chatToolPayload.apiName,- args: batchParsedArgs,- callIndex: batchCallIndex,- content: executionResult.content,- executionTimeMs: executionTime,- identifier: chatToolPayload.identifier,- mocked: batchToolCallMocked,- operationId,- stepIndex,- success: isSuccess,- userId: ctx.userId,+ isInterrupted: () => isOperationInterrupted(ctx),+ maxRetries: TOOL_MAX_RETRIES,+ operationLogId,+ toolName,},- state.metadata?._hooks,- )- .catch(() => {});- }- log(- `[${operationLogId}] Executed ${toolName} in ${executionTime}ms, success: ${isSuccess}`,- );-- // Publish tool execution result event- await streamManager.publishStreamEvent(operationId, {- data: {- executionTime,- isSuccess,- attempts: execution.attempts,- maxAttempts: TOOL_MAX_RETRIES + 1,- payload: { parentMessageId, toolCalling: chatToolPayload },- phase: 'tool_execution',- result: executionResult,- },- stepIndex,- type: 'tool_end',- });+ );+ }- // Create tool message in database- try {- const toolMessage = await ctx.messageModel.create({- agentId: state.metadata!.agentId!,- content: executionResult.content,- metadata: { toolExecutionTimeMs: executionTime },- parentId: parentMessageId,- plugin: chatToolPayload as any,- pluginError: executionResult.error,- pluginState: executionResult.state,- role: 'tool',- threadId: state.metadata?.threadId,- tool_call_id: chatToolPayload.id,- topicId: state.metadata?.topicId,+ const executionResult = await archiveRuntimeToolResult(execution.result, {+ agentId: state.metadata?.agentId,+ identifier: chatToolPayload.identifier,+ limit: batchAgentConfig?.chatConfig?.toolResultMaxLength,+ serverDB: ctx.serverDB,+ toolCallId: chatToolPayload.id,+ topicId: ctx.topicId ?? state.metadata?.topicId,+ userId: ctx.userId,});- toolMessageIds.push(toolMessage.id);- log(`[${operationLogId}] Created tool message ${toolMessage.id} for ${toolName}`);- } catch (error) {- console.error(- `[${operationLogId}] Failed to create tool message for ${toolName}:`,- error,+ const executionTime = executionResult.executionTime;+ const isSuccess = executionResult.success;+ if (ctx.hookDispatcher) {+ ctx.hookDispatcher+ .dispatch(+ operationId,+ 'afterToolCall',+ {+ apiName: chatToolPayload.apiName,+ args: batchParsedArgs,+ callIndex: batchCallIndex,+ content: executionResult.content,+ executionTimeMs: executionTime,+ identifier: chatToolPayload.identifier,+ mocked: batchToolCallMocked,+ operationId,+ stepIndex,+ success: isSuccess,+ userId: ctx.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});+ }+ log(+ `[${operationLogId}] Executed ${toolName} in ${executionTime}ms, success: ${isSuccess}`,);- // Normalize BEFORE publishing — clients treat `error` stream- // events as terminal and surface `event.data.error` directly, so- // a raw SQL error here would leak driver text to the user before- // the ConversationParentMissing throw is consumed. See .- const fatal = isParentMessageMissingError(error)- ? createConversationParentMissingError(parentMessageId, error)- : error instanceof Error- ? error- : new Error(String(error));++ // Publish tool execution result eventawait streamManager.publishStreamEvent(operationId, {- data: formatErrorEventData(fatal, 'tool_message_persist'),+ data: {+ executionTime,+ isSuccess,+ attempts: execution.attempts,+ maxAttempts: TOOL_MAX_RETRIES + 1,+ payload: { parentMessageId, toolCalling: chatToolPayload },+ phase: 'tool_execution',+ result: executionResult,+ },stepIndex,- type: 'error',+ type: 'tool_end',});- // Marker so the outer catch (which normally just records- // per-tool exec errors) knows to propagate this one.- throw markPersistFatal(fatal);- }- // Collect tool result- toolResults.push({- data: executionResult,- executionTime,- isSuccess,- toolCall: chatToolPayload,- toolCallId: chatToolPayload.id,- });+ // Create tool message in database+ try {+ const toolMessage = await ctx.messageModel.create({+ agentId: state.metadata!.agentId!,+ content: executionResult.content,+ metadata: { toolExecutionTimeMs: executionTime },+ parentId: parentMessageId,+ plugin: chatToolPayload as any,+ pluginError: executionResult.error,+ pluginState: executionResult.state,+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: chatToolPayload.id,+ topicId: state.metadata?.topicId,+ });+ toolMessageIds.push(toolMessage.id);+ log(`[${operationLogId}] Created tool message ${toolMessage.id} for ${toolName}`);+ } catch (error) {+ console.error(+ `[${operationLogId}] Failed to create tool message for ${toolName}:`,+ error,+ );+ // Normalize BEFORE publishing — clients treat `error` stream+ // events as terminal and surface `event.data.error` directly, so+ // a raw SQL error here would leak driver text to the user before+ // the ConversationParentMissing throw is consumed. See .+ const fatal = isParentMessageMissingError(error)+ ? createConversationParentMissingError(parentMessageId, error)+ : error instanceof Error+ ? error+ : new Error(String(error));+ await streamManager.publishStreamEvent(operationId, {+ data: formatErrorEventData(fatal, 'tool_message_persist'),+ stepIndex,+ type: 'error',+ });+ // Marker so the outer catch (which normally just records+ // per-tool exec errors) knows to propagate this one.+ throw markPersistFatal(fatal);+ }- events.push({ id: chatToolPayload.id, result: executionResult, type: 'tool_result' });+ // Collect tool result+ toolResults.push({+ data: executionResult,+ executionTime,+ isSuccess,+ toolCall: chatToolPayload,+ toolCallId: chatToolPayload.id,+ });- // Collect per-tool usage for post-batch accumulation- const toolCost = TOOL_PRICING[toolName] || 0;- toolResults.at(-1).usageParams = {- executionTime,- success: isSuccess,- toolCost,- toolName,- };- } catch (error) {- // Persist-level failures (e.g. parent FK violations) must propagate- // so the whole batch short-circuits. Without this the fallback to- // the already-deleted parent triggers another FK on the next step.- if (isPersistFatal(error)) {- throw error;- }+ events.push({ id: chatToolPayload.id, result: executionResult, type: 'tool_result' });- if (ctx.hookDispatcher) {- ctx.hookDispatcher- .dispatch(- operationId,- 'onToolCallError',- {- apiName: chatToolPayload.apiName,- args: batchParsedArgs,- callIndex: batchCallIndex,- error: error instanceof Error ? error.message : String(error),- identifier: chatToolPayload.identifier,+ // Collect per-tool usage for post-batch accumulation+ const toolCost = TOOL_PRICING[toolName] || 0;+ toolResults.at(-1).usageParams = {+ executionTime,+ success: isSuccess,+ toolCost,+ toolName,+ };++ batchExecuteToolSpan.setAttributes(+ buildExecuteToolResultAttributes({+ attempts: execution.attempts,+ success: isSuccess,+ }),+ );+ } catch (error) {+ batchExecuteToolSpan.recordException(error as Error);+ batchExecuteToolSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ batchExecuteToolSpan.setAttributes(+ buildExecuteToolResultAttributes({ success: false }),+ );++ // Persist-level failures (e.g. parent FK violations) must propagate+ // so the whole batch short-circuits. Without this the fallback to+ // the already-deleted parent triggers another FK on the next step.+ if (isPersistFatal(error)) {+ throw error;+ }++ if (ctx.hookDispatcher) {+ ctx.hookDispatcher+ .dispatch(operationId,- stepIndex,- userId: ctx.userId,- },- state.metadata?._hooks,- )- .catch(() => {});- }+ 'onToolCallError',+ {+ apiName: chatToolPayload.apiName,+ args: batchParsedArgs,+ callIndex: batchCallIndex,+ error: error instanceof Error ? error.message : String(error),+ identifier: chatToolPayload.identifier,+ operationId,+ stepIndex,+ userId: ctx.userId,+ },+ state.metadata?._hooks,+ )+ .catch(() => {});+ }- console.error(`[${operationLogId}] Tool execution failed for ${toolName}:`, error);+ console.error(`[${operationLogId}] Tool execution failed for ${toolName}:`, error);- // Publish error event- await streamManager.publishStreamEvent(operationId, {- data: formatErrorEventData(error, 'tool_execution'),- stepIndex,- type: 'error',- });+ // Publish error event+ await streamManager.publishStreamEvent(operationId, {+ data: formatErrorEventData(error, 'tool_execution'),+ stepIndex,+ type: 'error',+ });- events.push({ error, type: 'error' });+ events.push({ error, type: 'error' });+ }+ } finally {+ batchExecuteToolSpan.end();}}),);diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsindex 8c1c67fc791..aeb3d401b5e 100644--- a/src/server/services/agentRuntime/AgentRuntimeService.ts+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -8,6 +8,17 @@ import { AgentRuntime, findInMessages, GeneralChatAgent } from '@lobechat/agent-import type { ISnapshotStore } from '@lobechat/agent-tracing';import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';import { getModelPropertyWithFallback } from '@lobechat/model-runtime';+import {+ context as otelContext,+ SpanStatusCode,+ trace as otelTrace,+} from '@lobechat/observability-otel/api';+import {+ buildInvokeAgentAttributes,+ buildInvokeAgentResultAttributes,+ invokeAgentSpanName,+ tracer as agentRuntimeTracer,+} from '@lobechat/observability-otel/modules/agent-runtime';import {AgentRuntimeErrorType,ChatErrorType,@@ -554,418 +565,476 @@ export class AgentRuntimeService {// success path.const stepStartAt = Date.now();- try {- 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}`);- }-- const stepStartUiMessages = await this.queryUiMessages(agentState);- await this.streamManager.publishStreamEvent(operationId, {- data: {- ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }),- },- stepIndex,- type: 'step_start',- });-- agentState.metadata = {- ...agentState.metadata,- externalRetryCount,- };+ // 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);- // 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,- };- }+ 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}`);+ }- // 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,+ const stepStartUiMessages = await this.queryUiMessages(agentState);+ await this.streamManager.publishStreamEvent(operationId, {+ data: {+ ...(stepStartUiMessages !== undefined && { uiMessages: stepStartUiMessages }),+ },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);+ type: 'step_start',+ });- return {- nextStepScheduled: false,- state: agentState,- stepResult: null,- success: true,+ agentState.metadata = {+ ...agentState.metadata,+ externalRetryCount,};- }-- let beforeStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];- // Dispatch beforeStep hooks- try {- const beforeStepMetadata = agentState?.metadata || {};- const beforeStepSignalEmission = await emitAgentSignalSourceEvent(- {- payload: {- agentId: beforeStepMetadata?.agentId,- operationId,- serializedContext: undefined,- stepIndex,- topicId: beforeStepMetadata?.topicId,- turnCount: agentState?.stepCount || 0,- },- sourceId: `${operationId}:before:${stepIndex}`,- sourceType: 'runtime.before_step',- },- {- agentId: beforeStepMetadata?.agentId,- db: this.serverDB,- userId: beforeStepMetadata?.userId || this.userId,- },- { ignoreError: true },- );- beforeStepSignalEvents = toAgentSignalSnapshotEvents(beforeStepSignalEmission);- await hookDispatcher.dispatch(- operationId,- 'beforeStep',- {- agentId: beforeStepMetadata?.agentId || '',- finalState: agentState,+ // Enrich invoke_agent span with agent identity now that state is loaded.+ const stateAgentConfig = agentState.metadata?.agentConfig as+ | { description?: string | null; title?: string | null }+ | undefined;+ const stateModel =+ agentState.modelRuntimeConfig?.model ?? agentState.metadata?.modelRuntimeConfig?.model;+ const stateProvider =+ agentState.modelRuntimeConfig?.provider ??+ agentState.metadata?.modelRuntimeConfig?.provider;+ invokeAgentSpan.updateName(invokeAgentSpanName(stateAgentConfig?.title ?? undefined));+ invokeAgentSpan.setAttributes(+ buildInvokeAgentAttributes({+ agentDescription: stateAgentConfig?.description ?? undefined,+ agentId: agentState.metadata?.agentId,+ agentName: stateAgentConfig?.title ?? undefined,+ conversationId: agentState.metadata?.topicId,operationId,+ provider: stateProvider,+ requestModel: stateModel,stepIndex,- steps: agentState?.stepCount || 0,- userId: beforeStepMetadata?.userId || this.userId,- },- beforeStepMetadata._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; 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)- const { runtime } = await this.createAgentRuntime({- metadata: agentState?.metadata,- operationId,- stepIndex,- tracingContextEngine: (input, output) => {- contextEnginePayload = { input, output };- },- });-- // Handle human intervention- let currentContext = context;- 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;- }- // Pre-step computation: extract device context from DB messages- // Follows front-end computeStepContext pattern — computed at step boundary, not inside executors- if (!currentState.metadata?.activeDeviceId) {- const deviceContext = await this.computeDeviceContext(currentState);- if (deviceContext && currentState.metadata) {- currentState.metadata.activeDeviceId = deviceContext.activeDeviceId;- currentState.metadata.devicePlatform = deviceContext.devicePlatform;- currentState.metadata.deviceSystemInfo = deviceContext.deviceSystemInfo;+ // Layer 2 defense: catch extremely delayed retries that arrive after lock TTL expired+ if (agentState.stepCount > stepIndex) {log(- '[%s][%d] Pre-step: device context computed from messages (deviceId: %s)',+ '[%s][%d] Step already completed (stepCount=%d), skipping',operationId,stepIndex,- deviceContext.activeDeviceId,+ agentState.stepCount,);+ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };}- }- // Execute step- const startAt = Date.now();- const stepResult = await runtime.step(currentState, currentContext);-- // Check if the operation was interrupted while the step was executing- // (e.g., user clicked abort during a long LLM call)- const latestState = await this.coordinator.loadAgentState(operationId);- if (latestState?.status === 'interrupted') {- stepResult.newState.status = 'interrupted';- stepResult.newState.lastModified = new Date().toISOString();- log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);- }-- // Save state, coordinator will handle event sending automatically- await this.coordinator.saveStepResult(operationId, {- ...stepResult,- executionTime: Date.now() - startAt,- stepIndex, // placeholder- });-- // Decide whether to schedule next step- const shouldContinue = this.shouldContinueExecution(- stepResult.newState,- stepResult.nextContext,- );- let nextStepScheduled = false;+ // 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,+ );- // Publish step complete event- await this.streamManager.publishStreamEvent(operationId, {- data: {- finalState: stepResult.newState,- nextStepScheduled,- stepIndex,- },- stepIndex,- type: 'step_complete',- });+ const reason = this.determineCompletionReason(agentState);- // Build enhanced step completion log & presentation data- const { presentation: stepPresentationData, summary: stepSummary } = buildStepPresentation(- stepResult,- Date.now() - startAt,- );+ await this.completionLifecycle.emitSignalEvents(operationId, agentState, reason);- 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,- );+ // Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize+ await this.completionLifecycle.dispatchHooks(operationId, agentState, reason);- const toolsCalling = stepPresentationData.toolsCalling;- const content = stepPresentationData.content;+ return {+ nextStepScheduled: false,+ state: agentState,+ stepResult: null,+ success: true,+ };+ }- let afterStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];+ let beforeStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];- // Dispatch afterStep hooks (enriched with step presentation + tracking data)- try {- const metadata = stepResult.newState?.metadata || {};- const tracking = metadata._stepTracking || {};- const elapsedMs = stepResult.newState?.createdAt- ? Date.now() - new Date(stepResult.newState.createdAt).getTime()- : undefined;- const stepLabel = metadata?._stepLabel;-- afterStepSignalEvents = toAgentSignalSnapshotEvents(- await emitAgentSignalSourceEvent(+ // Dispatch beforeStep hooks+ try {+ const beforeStepMetadata = agentState?.metadata || {};+ const beforeStepSignalEmission = await emitAgentSignalSourceEvent({payload: {- agentId: metadata?.agentId,+ agentId: beforeStepMetadata?.agentId,operationId,serializedContext: undefined,stepIndex,- topicId: metadata?.topicId,- turnCount: stepResult.newState?.stepCount || 0,+ topicId: beforeStepMetadata?.topicId,+ turnCount: agentState?.stepCount || 0,},- sourceId: `${operationId}:after:${stepIndex}`,- sourceType: 'runtime.after_step',+ sourceId: `${operationId}:before:${stepIndex}`,+ sourceType: 'runtime.before_step',},{- agentId: metadata?.agentId,+ agentId: beforeStepMetadata?.agentId,db: this.serverDB,- userId: metadata?.userId || this.userId,+ userId: beforeStepMetadata?.userId || this.userId,},{ ignoreError: true },- ),- );+ );+ beforeStepSignalEvents = toAgentSignalSnapshotEvents(beforeStepSignalEmission);+ await hookDispatcher.dispatch(+ operationId,+ 'beforeStep',+ {+ agentId: beforeStepMetadata?.agentId || '',+ finalState: agentState,+ operationId,+ stepIndex,+ steps: agentState?.stepCount || 0,+ userId: beforeStepMetadata?.userId || this.userId,+ },+ beforeStepMetadata._hooks,+ );+ } catch (hookError) {+ log('[%s] beforeStep hook dispatch error: %O', operationId, hookError);+ }- await hookDispatcher.dispatch(+ // 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; 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)+ const { runtime } = await this.createAgentRuntime({+ metadata: agentState?.metadata,operationId,- 'afterStep',- {- agentId: metadata?.agentId || '',- content,- elapsedMs,- executionTimeMs: stepPresentationData.executionTimeMs,+ stepIndex,+ tracingContextEngine: (input, output) => {+ contextEnginePayload = { input, output };+ },+ });++ // Handle human intervention+ let currentContext = context;+ 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;+ }++ // Pre-step computation: extract device context from DB messages+ // Follows front-end computeStepContext pattern — computed at step boundary, not inside executors+ if (!currentState.metadata?.activeDeviceId) {+ const deviceContext = await this.computeDeviceContext(currentState);+ if (deviceContext && currentState.metadata) {+ currentState.metadata.activeDeviceId = deviceContext.activeDeviceId;+ currentState.metadata.devicePlatform = deviceContext.devicePlatform;+ currentState.metadata.deviceSystemInfo = deviceContext.deviceSystemInfo;+ log(+ '[%s][%d] Pre-step: device context computed from messages (deviceId: %s)',+ operationId,+ stepIndex,+ deviceContext.activeDeviceId,+ );+ }+ }++ // Execute step+ const startAt = Date.now();+ const stepResult = await runtime.step(currentState, currentContext);++ // Check if the operation was interrupted while the step was executing+ // (e.g., user clicked abort during a long LLM call)+ const latestState = await this.coordinator.loadAgentState(operationId);+ if (latestState?.status === 'interrupted') {+ stepResult.newState.status = 'interrupted';+ stepResult.newState.lastModified = new Date().toISOString();+ log('[%s][%d] Operation was interrupted during step execution', operationId, stepIndex);+ }++ // Save state, coordinator will handle event sending automatically+ await this.coordinator.saveStepResult(operationId, {+ ...stepResult,+ executionTime: Date.now() - startAt,+ stepIndex, // placeholder+ });++ // Decide whether to schedule next step+ const shouldContinue = this.shouldContinueExecution(+ stepResult.newState,+ stepResult.nextContext,+ );+ let nextStepScheduled = false;++ // Publish step complete event+ await this.streamManager.publishStreamEvent(operationId, {+ data: {finalState: stepResult.newState,- ...(stepLabel && { stepLabel }),- lastLLMContent: tracking.lastLLMContent,- lastToolsCalling: tracking.lastToolsCalling,- operationId,- reasoning: stepPresentationData.reasoning,- shouldContinue,- status: stepResult.newState?.status,- stepCost: stepPresentationData.stepCost,+ nextStepScheduled,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: metadata?.topicId,- totalCost: stepPresentationData.totalCost,- totalInputTokens: stepPresentationData.totalInputTokens,- totalOutputTokens: stepPresentationData.totalOutputTokens,- totalSteps: stepPresentationData.totalSteps,- totalTokens: stepPresentationData.totalTokens,- totalToolCalls: (tracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0),- userId: metadata?.userId || this.userId,},- metadata._hooks,+ stepIndex,+ type: 'step_complete',+ });++ // Build enhanced step completion log & presentation data+ const { presentation: stepPresentationData, summary: stepSummary } = buildStepPresentation(+ stepResult,+ Date.now() - startAt,);- } 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,- });+ 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,+ );- // Update step tracking in state metadata for afterStep hooks (cross-step accumulator)- const hasAfterStepHooks = stepResult.newState.metadata?._hooks?.some(- (h: { type: string }) => h.type === 'afterStep',- );- 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,- };+ const toolsCalling = stepPresentationData.toolsCalling;+ const content = stepPresentationData.content;- // Persist tracking state for next step- stepResult.newState.metadata._stepTracking = updatedTracking;- await this.coordinator.saveAgentState(operationId, stepResult.newState);- }+ let afterStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];- if (shouldContinue && stepResult.nextContext && this.queueService) {- const nextStepIndex = stepIndex + 1;- const delay = this.calculateStepDelay(stepResult);- const priority = this.calculatePriority(stepResult);+ // Dispatch afterStep hooks (enriched with step presentation + tracking data)+ try {+ const metadata = stepResult.newState?.metadata || {};+ const tracking = metadata._stepTracking || {};+ const elapsedMs = stepResult.newState?.createdAt+ ? Date.now() - new Date(stepResult.newState.createdAt).getTime()+ : undefined;+ const stepLabel = metadata?._stepLabel;++ afterStepSignalEvents = toAgentSignalSnapshotEvents(+ await emitAgentSignalSourceEvent(+ {+ payload: {+ agentId: metadata?.agentId,+ operationId,+ serializedContext: undefined,+ stepIndex,+ topicId: metadata?.topicId,+ turnCount: stepResult.newState?.stepCount || 0,+ },+ sourceId: `${operationId}:after:${stepIndex}`,+ sourceType: 'runtime.after_step',+ },+ {+ agentId: metadata?.agentId,+ db: this.serverDB,+ userId: metadata?.userId || this.userId,+ },+ { ignoreError: true },+ ),+ );- await this.queueService.scheduleMessage({- context: stepResult.nextContext,- delay,- endpoint: `${this.baseURL}/run`,- operationId,- priority,- retryDelay:- typeof stepResult.newState.metadata?.queueRetryDelay === 'string'- ? stepResult.newState.metadata.queueRetryDelay- : undefined,- retries:- typeof stepResult.newState.metadata?.queueRetries === 'number'- ? stepResult.newState.metadata.queueRetries- : undefined,- stepIndex: nextStepIndex,+ await hookDispatcher.dispatch(+ operationId,+ 'afterStep',+ {+ agentId: metadata?.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: metadata?.topicId,+ totalCost: stepPresentationData.totalCost,+ totalInputTokens: stepPresentationData.totalInputTokens,+ totalOutputTokens: stepPresentationData.totalOutputTokens,+ totalSteps: stepPresentationData.totalSteps,+ totalTokens: stepPresentationData.totalTokens,+ totalToolCalls: (tracking.totalToolCalls ?? 0) + (toolsCalling?.length ?? 0),+ userId: metadata?.userId || this.userId,+ },+ metadata._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,});- nextStepScheduled = true;- log('[%s][%d] Scheduled next step %d', operationId, stepIndex, nextStepIndex);- }+ // Update step tracking in state metadata for afterStep hooks (cross-step accumulator)+ const hasAfterStepHooks = stepResult.newState.metadata?._hooks?.some(+ (h: { type: string }) => h.type === 'afterStep',+ );+ 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);+ }- // Check if operation is complete- if (!shouldContinue) {- const reason = this.determineCompletionReason(stepResult.newState);+ if (shouldContinue && stepResult.nextContext && this.queueService) {+ const nextStepIndex = stepIndex + 1;+ const delay = this.calculateStepDelay(stepResult);+ const priority = this.calculatePriority(stepResult);- const completionSignalEvents = await this.completionLifecycle.emitSignalEvents(- operationId,- stepResult.newState,- reason,+ await this.queueService.scheduleMessage({+ context: stepResult.nextContext,+ delay,+ endpoint: `${this.baseURL}/run`,+ operationId,+ priority,+ retryDelay:+ typeof stepResult.newState.metadata?.queueRetryDelay === 'string'+ ? stepResult.newState.metadata.queueRetryDelay+ : undefined,+ retries:+ typeof stepResult.newState.metadata?.queueRetries === 'number'+ ? stepResult.newState.metadata.queueRetries+ : undefined,+ stepIndex: nextStepIndex,+ });+ nextStepScheduled = true;++ 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,+ }),);- // Dispatch completion hooks- await this.completionLifecycle.dispatchHooks(operationId, stepResult.newState, reason);-- // 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 ().- await this.traceRecorder.finalize(operationId, {- appendEventsToLastStep: completionSignalEvents,- completionReason: reason,- error: stepResult.newState.error- ? {- message:- this.completionLifecycle.extractErrorMessage(stepResult.newState.error) ??- JSON.stringify(stepResult.newState.error),- type: String(- stepResult.newState.error.type ??- stepResult.newState.error.errorType ??- 'unknown',- ),- }- : undefined,- state: stepResult.newState,- });- }+ // Check if operation is complete+ if (!shouldContinue) {+ const reason = this.determineCompletionReason(stepResult.newState);+ invokeAgentSpan.setAttributes(+ buildInvokeAgentResultAttributes({ completionReason: reason }),+ );- return {- nextStepScheduled,- state: stepResult.newState,- stepResult,- success: true,- };+ const completionSignalEvents = await this.completionLifecycle.emitSignalEvents(+ operationId,+ stepResult.newState,+ reason,+ );++ // Dispatch completion hooks+ await this.completionLifecycle.dispatchHooks(operationId, stepResult.newState, reason);++ // 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 ().+ await this.traceRecorder.finalize(operationId, {+ appendEventsToLastStep: completionSignalEvents,+ completionReason: reason,+ error: stepResult.newState.error+ ? {+ message:+ this.completionLifecycle.extractErrorMessage(stepResult.newState.error) ??+ JSON.stringify(stepResult.newState.error),+ type: String(+ stepResult.newState.error.type ??+ stepResult.newState.error.errorType ??+ 'unknown',+ ),+ }+ : undefined,+ state: stepResult.newState,+ });+ }++ return {+ nextStepScheduled,+ state: stepResult.newState,+ stepResult,+ success: true,+ };+ });} catch (error) {+ invokeAgentSpan.recordException(error as Error);+ invokeAgentSpan.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ invokeAgentSpan.setAttributes(+ buildInvokeAgentResultAttributes({ completionReason: 'error' }),+ );+log('Step %d failed for operation %s: %O', stepIndex, operationId, error);const formattedError = formatErrorForState(error);@@ -1051,6 +1120,7 @@ export class AgentRuntimeService {throw error;} finally {+ invokeAgentSpan.end();// Release lock so legitimate retries or next operations can proceed.// If Vercel force-kills the process, this won't execute — the lock// auto-expires after TTL (35s), allowing QStash retries to self-heal.diff --git a/src/server/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/src/server/services/agentRuntime/__tests__/agentSignalHooks.integration.test.tsindex 3b36e1ab1fe..92e373eb98f 100644--- a/src/server/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts+++ b/src/server/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';interface AgentSignalRedisTestGlobal {__agentSignalRedisClient?: typeof mockRedis | null;@@ -13,13 +13,25 @@ const mockRedis = {set: vi.fn(),};+const stubUiMessagesSnapshot = (service: unknown) => {+ (+ service as { messageServiceInstance?: { queryMessages: ReturnType<typeof vi.fn> } }+ ).messageServiceInstance = {+ queryMessages: vi.fn().mockResolvedValue([]),+ };+};+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(() => ({create: vi.fn(),+ query: vi.fn().mockResolvedValue([]),update: vi.fn(),})),}));+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));vi.mock('@/server/modules/AgentRuntime', () => ({AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({createAgentOperation: vi.fn(),@@ -51,7 +63,12 @@ vi.mock('@/server/services/queue/impls', () => ({LocalQueueServiceImpl: class {},isQueueAgentRuntimeEnabled: vi.fn().mockReturnValue(false),}));-vi.mock('@/server/services/agentSignal/featureGate', () => ({+vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: vi+ .fn()+ .mockResolvedValue({ enableAgentSelfIteration: true }),+}));+vi.mock('../../agentSignal/featureGate', () => ({isAgentSignalEnabledForUser: vi.fn().mockResolvedValue(true),}));vi.mock('@/server/services/toolExecution', () => ({@@ -65,6 +82,11 @@ vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({}));describe('AgentRuntimeService Agent Signal hook integration', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = undefined;+ });+it('emits source events for beforeStep and afterStep boundaries',{ timeout: 20_000 },@@ -78,6 +100,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {const { AgentRuntimeService } = await import('../AgentRuntimeService');const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });+ stubUiMessagesSnapshot(service);const coordinator = (service as any).coordinator;vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({@@ -180,6 +203,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {queueService: null,snapshotStore: snapshotStore as any,});+ stubUiMessagesSnapshot(service);const coordinator = (service as any).coordinator;vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({@@ -278,6 +302,7 @@ describe('AgentRuntimeService Agent Signal hook integration', () => {queueService: null,snapshotStore: snapshotStore as any,});+ stubUiMessagesSnapshot(service);const coordinator = (service as any).coordinator;vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({