Skip to content

🀯 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.

πŸ”¨ chore: add GraphAgent and agentFactory for graph-driven agent execution (#13643)

Arvin Xu22909292557f
diff --git a/packages/agent-runtime/src/agents/GraphAgent.ts b/packages/agent-runtime/src/agents/GraphAgent.ts
new file mode 100644
index 00000000000..e191e0f4133
--- /dev/null
+++ b/packages/agent-runtime/src/agents/GraphAgent.ts
@@ -0,0 +1,363 @@
+import type {
+ Agent,
+ AgentInstruction,
+ AgentRuntimeContext,
+ AgentState,
+ GeneralAgentCallLLMInstructionPayload,
+ GeneralAgentConfig,
+ GraphContext,
+ ReasoningGraph,
+} from '../types';
+import { GeneralChatAgent } from './GeneralChatAgent';
+
+const GRAPH_CONTEXT_KEY = '__graphContext';
+
+/**
+ * GraphAgent β€” A graph-driven Agent that decorates GeneralChatAgent.
+ *
+ * Instead of the default phase-driven loop (LLM decides flow),
+ * GraphAgent uses a declarative ReasoningGraph to drive execution:
+ *
+ * 1. Each graph node maps to one or more AgentRuntime steps
+ * 2. 'agent' nodes delegate to GeneralChatAgent for full tool-calling loops
+ * 3. 'llm' nodes do a single LLM call with structured output
+ * 4. Transitions are evaluated programmatically (not by LLM)
+ * 5. Backtracking is supported with configurable limits
+ *
+ * Key mechanism: intercept GeneralChatAgent's 'finish' instruction.
+ * When the inner agent finishes, GraphAgent checks if the graph has more
+ * nodes to execute. Only when the terminal node completes does GraphAgent
+ * return a real 'finish'.
+ *
+ * Agent vs LLM nodes:
+ * - 'agent' nodes: prompt sent WITHOUT JSON schema β†’ agent loop with tools β†’
+ * on finish, extra LLM call to extract structured output
+ * - 'llm' nodes: prompt sent WITH JSON schema β†’ single structured LLM call
+ */
+export class GraphAgent implements Agent {
+ private innerAgent: GeneralChatAgent;
+ private graph: ReasoningGraph;
+
+ constructor(config: GeneralAgentConfig & { graph: ReasoningGraph }) {
+ const { graph, ...generalConfig } = config;
+ this.graph = graph;
+ this.innerAgent = new GeneralChatAgent(generalConfig);
+ }
+
+ async runner(
+ context: AgentRuntimeContext,
+ state: AgentState,
+ ): Promise<AgentInstruction | AgentInstruction[]> {
+ const gc = this.getGraphContext(state);
+
+ // First call β€” initialize graph and start entry node
+ if (!gc) {
+ return this.initGraph(context, state);
+ }
+
+ const node = this.graph.states[gc.currentNode];
+ if (!node) {
+ return {
+ reason: 'error_recovery',
+ reasonDetail: `Graph node "${gc.currentNode}" not found`,
+ type: 'finish',
+ };
+ }
+
+ // Agent node: delegate to GeneralChatAgent for the tool-calling loop
+ if (gc.nodeActive && node.type === 'agent') {
+ // If we're in the extraction phase, handle the extraction result
+ if (gc.extracting) {
+ if (context.phase === 'llm_result') {
+ gc.extracting = false;
+ return this.onNodeComplete(state, gc);
+ }
+ return this.innerAgent.runner(context, state);
+ }
+
+ const instruction = await this.innerAgent.runner(context, state);
+
+ // Intercept finish β€” agent loop done, now extract structured output
+ if (!Array.isArray(instruction) && instruction.type === 'finish') {
+ return this.startExtraction(state, gc);
+ }
+
+ if (Array.isArray(instruction)) {
+ const hasFinish = instruction.some((i) => i.type === 'finish');
+ if (hasFinish) {
+ return this.startExtraction(state, gc);
+ }
+ }
+
+ // Otherwise pass through (call_llm, call_tool, etc.)
+ return instruction;
+ }
+
+ // LLM node: after the LLM result comes back, extract output and advance
+ if (gc.nodeActive && node.type === 'llm') {
+ if (context.phase === 'llm_result') {
+ return this.onNodeComplete(state, gc);
+ }
+ // Delegate other phases (like compression_result) to inner agent
+ return this.innerAgent.runner(context, state);
+ }
+
+ // nodeActive is false β€” we're at a graph transition point, start the next node
+ return this.startNode(gc, state);
+ }
+
+ /**
+ * Initialize the graph: set up context, start entry node
+ */
+ private initGraph(_context: AgentRuntimeContext, state: AgentState): AgentInstruction {
+ const lastUserMessage = [...state.messages].reverse().find((m: any) => m.role === 'user');
+ const input =
+ typeof lastUserMessage?.content === 'string'
+ ? lastUserMessage.content
+ : JSON.stringify(lastUserMessage?.content ?? '');
+
+ const gc: GraphContext = {
+ currentNode: this.graph.entry,
+ nodeActive: false,
+ store: {},
+ backtrackCount: 0,
+ visitCount: {},
+ input,
+ };
+
+ this.saveGraphContext(state, gc);
+ return this.startNode(gc, state);
+ }
+
+ /**
+ * Start executing a graph node.
+ *
+ * - agent nodes: send task prompt WITH tools, WITHOUT JSON schema
+ * (let the agent use tools freely, extract structured output later)
+ * - llm nodes: send prompt WITH JSON schema, WITHOUT tools
+ * (single structured generation call)
+ */
+ private startNode(gc: GraphContext, state: AgentState): AgentInstruction {
+ const node = this.graph.states[gc.currentNode];
+ if (!node) {
+ return {
+ reason: 'error_recovery',
+ reasonDetail: `Graph node "${gc.currentNode}" not found in states`,
+ type: 'finish',
+ };
+ }
+
+ const visits = (gc.visitCount[gc.currentNode] ?? 0) + 1;
+ gc.visitCount[gc.currentNode] = visits;
+
+ if (visits > 1) {
+ gc.backtrackCount++;
+ }
+
+ const renderedPrompt = this.renderPrompt(node.prompt, gc);
+
+ let fullPrompt: string;
+ let tools: any[];
+
+ if (node.type === 'agent') {
+ // Agent node: task prompt with tools, no JSON schema constraint
+ // The agent will use tools freely; structured output is extracted after the loop
+ fullPrompt =
+ renderedPrompt +
+ '\n\nIMPORTANT: You MUST use your available tools (web search, etc.) to research this. ' +
+ 'Do NOT answer from memory. Search for real evidence and data first, ' +
+ 'then provide your findings based on the tool results.';
+ tools = state.tools ?? [];
+ } else {
+ // LLM node: structured output, no tools
+ fullPrompt =
+ renderedPrompt +
+ `\n\nYou MUST respond with a JSON object that conforms to this schema:\n` +
+ `\`\`\`json\n${JSON.stringify(node.outputSchema, null, 2)}\n\`\`\`\n` +
+ `Only output valid JSON, no other text.`;
+ tools = [];
+ }
+
+ gc.nodeActive = true;
+ gc.extracting = false;
+ this.saveGraphContext(state, gc);
+
+ const messages = [...state.messages, { content: fullPrompt, role: 'user' as const }];
+
+ const payload: GeneralAgentCallLLMInstructionPayload = {
+ messages,
+ model: state.modelRuntimeConfig?.model ?? '',
+ provider: state.modelRuntimeConfig?.provider ?? '',
+ tools,
+ };
+
+ return { payload, stepLabel: gc.currentNode, type: 'call_llm' };
+ }
+
+ /**
+ * After an agent node's tool loop finishes, do an extra LLM call
+ * to extract structured output from the conversation.
+ */
+ private startExtraction(state: AgentState, gc: GraphContext): AgentInstruction {
+ const node = this.graph.states[gc.currentNode];
+
+ const extractionPrompt =
+ `Based on the research and information gathered above, ` +
+ `extract and summarize your findings into a JSON object that conforms to this schema:\n` +
+ `\`\`\`json\n${JSON.stringify(node.outputSchema, null, 2)}\n\`\`\`\n` +
+ `Only output valid JSON, no other text.`;
+
+ gc.extracting = true;
+ this.saveGraphContext(state, gc);
+
+ const messages = [...state.messages, { content: extractionPrompt, role: 'user' as const }];
+
+ const payload: GeneralAgentCallLLMInstructionPayload = {
+ messages,
+ model: state.modelRuntimeConfig?.model ?? '',
+ provider: state.modelRuntimeConfig?.provider ?? '',
+ tools: [], // No tools for extraction
+ };
+
+ return { payload, stepLabel: `${gc.currentNode}:extract`, type: 'call_llm' };
+ }
+
+ /**
+ * Called when a node completes. Extract output, eval transitions, advance graph.
+ */
+ private onNodeComplete(state: AgentState, gc: GraphContext): AgentInstruction {
+ const currentNodeId = gc.currentNode;
+
+ const output = this.extractStructuredOutput(state);
+ gc.store[currentNodeId] = output;
+ gc.nodeActive = false;
+
+ // Terminal node β†’ done
+ if (currentNodeId === this.graph.terminal) {
+ this.saveGraphContext(state, gc);
+ return {
+ reason: 'completed',
+ reasonDetail: `Graph "${this.graph.name}" completed at terminal node "${currentNodeId}"`,
+ type: 'finish',
+ };
+ }
+
+ // Evaluate transitions
+ const nextNodeId = this.evaluateTransitions(gc, currentNodeId, output);
+
+ if (!nextNodeId) {
+ this.saveGraphContext(state, gc);
+ return {
+ reason: 'error_recovery',
+ reasonDetail: `No valid transition from node "${currentNodeId}"`,
+ type: 'finish',
+ };
+ }
+
+ // Move to next node
+ gc.currentNode = nextNodeId;
+
+ // If backtracking, clear intermediate store entries
+ const nodeKeys = Object.keys(this.graph.states);
+ const fromIdx = nodeKeys.indexOf(currentNodeId);
+ const toIdx = nodeKeys.indexOf(nextNodeId);
+ if (toIdx < fromIdx) {
+ for (let i = toIdx; i <= fromIdx; i++) {
+ delete gc.store[nodeKeys[i]];
+ }
+ }
+
+ this.saveGraphContext(state, gc);
+ return this.startNode(gc, state);
+ }
+
+ private evaluateTransitions(
+ gc: GraphContext,
+ currentNodeId: string,
+ output: Record<string, any>,
+ ): string | null {
+ const backtrackLimitReached = gc.backtrackCount >= this.graph.maxBacktracks;
+
+ for (const t of this.graph.transitions) {
+ if (t.from !== currentNodeId) continue;
+ try {
+ const result = new Function('output', `return (${t.condition})`)(output);
+ if (result) {
+ // If the transition target is a backtrack (already visited), only allow it
+ // when within the backtrack limit. Otherwise fall through to linear advance.
+ const isBacktrack = (gc.visitCount[t.to] ?? 0) > 0;
+ if (isBacktrack && backtrackLimitReached) continue;
+ return t.to;
+ }
+ } catch {
+ // condition eval failed, skip
+ }
+ }
+
+ return this.getNextState(currentNodeId);
+ }
+
+ private getNextState(currentNodeId: string): string | null {
+ const keys = Object.keys(this.graph.states);
+ const idx = keys.indexOf(currentNodeId);
+ return idx >= 0 && idx + 1 < keys.length ? keys[idx + 1] : null;
+ }
+
+ private renderPrompt(template: string, gc: GraphContext): string {
+ return template.replaceAll(/\{\{(\w+)\.(\w+)\}\}/g, (_, stateId, field) => {
+ if (stateId === 'input' && field === 'question') {
+ return gc.input;
+ }
+
+ const data = gc.store[stateId];
+ if (!data) return `(${stateId} has no data yet)`;
+ const val = data[field];
+ if (val === undefined) return `(${stateId}.${field} has no data)`;
+ return typeof val === 'string' ? val : JSON.stringify(val, null, 2);
+ });
+ }
+
+ private extractStructuredOutput(state: AgentState): Record<string, any> {
+ const lastAssistantMessage = [...state.messages]
+ .reverse()
+ .find((m: any) => m.role === 'assistant');
+
+ if (!lastAssistantMessage) return {};
+
+ const content =
+ typeof lastAssistantMessage.content === 'string' ? lastAssistantMessage.content : '';
+
+ // Extract JSON from markdown code blocks or raw content
+ const fenceStart = content.indexOf('```');
+ let jsonStr: string;
+ if (fenceStart !== -1) {
+ const contentAfterFence = content.slice(fenceStart + 3);
+ // Skip optional language tag (e.g. "json\n")
+ const newlineIdx = contentAfterFence.indexOf('\n');
+ const bodyStart = newlineIdx !== -1 ? newlineIdx + 1 : 0;
+ const fenceEnd = contentAfterFence.indexOf('```', bodyStart);
+ jsonStr = (
+ fenceEnd !== -1
+ ? contentAfterFence.slice(bodyStart, fenceEnd)
+ : contentAfterFence.slice(bodyStart)
+ ).trim();
+ } else {
+ jsonStr = content.trim();
+ }
+
+ try {
+ return JSON.parse(jsonStr);
+ } catch {
+ return { _raw: content };
+ }
+ }
+
+ private getGraphContext(state: AgentState): GraphContext | null {
+ return (state.metadata?.[GRAPH_CONTEXT_KEY] as GraphContext) ?? null;
+ }
+
+ private saveGraphContext(state: AgentState, gc: GraphContext): void {
+ if (!state.metadata) state.metadata = {};
+ state.metadata[GRAPH_CONTEXT_KEY] = gc;
+ }
+}
diff --git a/packages/agent-runtime/src/agents/index.ts b/packages/agent-runtime/src/agents/index.ts
index 6a774928223..f938f09c070 100644
--- a/packages/agent-runtime/src/agents/index.ts
+++ b/packages/agent-runtime/src/agents/index.ts
@@ -1 +1,2 @@
export * from './GeneralChatAgent';
+export * from './GraphAgent';
diff --git a/packages/agent-runtime/src/types/graph.ts b/packages/agent-runtime/src/types/graph.ts
new file mode 100644
index 00000000000..b6e998373b0
--- /dev/null
+++ b/packages/agent-runtime/src/types/graph.ts
@@ -0,0 +1,85 @@
+// ── Reasoning Graph Definition (declarative JSON) ──
+
+/**
+ * A single state node in the reasoning graph
+ */
+export interface StateNode {
+ /**
+ * JSON Schema for structured output. Forces LLM to produce conforming JSON.
+ */
+ outputSchema: Record<string, any>;
+ /**
+ * Prompt template. Use {{stateId.field}} to reference output fields from previous nodes.
+ * Special variable: {{input.question}} references the original user input.
+ */
+ prompt: string;
+ /**
+ * Node type:
+ * - 'agent': Has tool capabilities, delegates to GeneralChatAgent for multi-turn tool loop
+ * - 'llm': Pure generation, single LLM call with structured output
+ */
+ type: 'agent' | 'llm';
+}
+
+/**
+ * A transition rule between states
+ */
+export interface Transition {
+ /**
+ * JS expression evaluated programmatically (NOT by LLM).
+ * The `output` variable is injected with the current node's structured output.
+ * Example: 'output.confidence < 0.4 && output.falsified.length > 0'
+ */
+ condition: string;
+ from: string;
+ to: string;
+}
+
+/**
+ * Declarative reasoning graph definition.
+ * Drives multi-stage agent execution with programmatic flow control.
+ */
+export interface ReasoningGraph {
+ description?: string;
+ /** Entry node ID */
+ entry: string;
+ /** Maximum backtrack count before forcing forward progress */
+ maxBacktracks: number;
+ name: string;
+ /** State node definitions */
+ states: Record<string, StateNode>;
+ /** Terminal node ID β€” when this node finishes, the entire graph is done */
+ terminal: string;
+ /** Transition rules, evaluated in order β€” first match wins */
+ transitions: Transition[];
+}
+
+// ── Graph Runtime Context ──
+
+/**
+ * Runtime context maintained by GraphAgent across steps.
+ * Stored in AgentState.metadata to survive across runner() calls.
+ */
+export interface GraphContext {
+ /** Total backtrack count across the graph execution */
+ backtrackCount: number;
+ /** Current node ID being executed */
+ currentNode: string;
+ /**
+ * Whether an agent node is in the extraction phase.
+ * After the agent loop finishes, an extra LLM call extracts structured output.
+ */
+ extracting?: boolean;
+ /** The original user input/question */
+ input: string;
+ /**
+ * Whether the current node's inner agent loop is active.
+ * When true, phases like llm_result/tool_result are delegated to GeneralChatAgent.
+ * When false, we're at a graph-level transition point.
+ */
+ nodeActive: boolean;
+ /** Accumulated structured outputs from completed nodes: stateId β†’ output */
+ store: Record<string, Record<string, any>>;
+ /** Visit count per node (for detecting backtracks) */
+ visitCount: Record<string, number>;
+}
diff --git a/packages/agent-runtime/src/types/index.ts b/packages/agent-runtime/src/types/index.ts
index c3287aa641d..e370fd942c1 100644
--- a/packages/agent-runtime/src/types/index.ts
+++ b/packages/agent-runtime/src/types/index.ts
@@ -1,5 +1,6 @@
export * from './event';
export * from './generalAgent';
+export * from './graph';
export * from './instruction';
export * from './runtime';
export * from './state';
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index b9ba427c761..04804ffc73a 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -347,21 +347,30 @@ export interface TasksBatchResultPayload {
}>;
}
+/**
+ * Common fields shared across all instruction types.
+ * Agents can set `stepLabel` to label the current step for display in streaming events and hooks.
+ */
+interface AgentInstructionBase {
+ /** Human-readable label for this step (e.g. graph node name). Propagated to stream events and hooks. */
+ stepLabel?: string;
+}
+
/**
* A serializable instruction object that the "Agent" (Brain) returns
* to the "AgentRuntime" (Engine) to execute.
*/
export type AgentInstruction =
- | AgentInstructionCallLlm
- | AgentInstructionCallTool
- | AgentInstructionCallToolsBatch
- | AgentInstructionExecTask
- | AgentInstructionExecTasks
- | AgentInstructionExecClientTask
- | AgentInstructionExecClientTasks
- | AgentInstructionRequestHumanPrompt
- | AgentInstructionRequestHumanSelect
- | AgentInstructionRequestHumanApprove
- | AgentInstructionResolveAbortedTools
- | AgentInstructionCompressContext
- | AgentInstructionFinish;
+ | (AgentInstructionCallLlm & AgentInstructionBase)
+ | (AgentInstructionCallTool & AgentInstructionBase)
+ | (AgentInstructionCallToolsBatch & AgentInstructionBase)
+ | (AgentInstructionExecTask & AgentInstructionBase)
+ | (AgentInstructionExecTasks & AgentInstructionBase)
+ | (AgentInstructionExecClientTask & AgentInstructionBase)
+ | (AgentInstructionExecClientTasks & AgentInstructionBase)
+ | (AgentInstructionRequestHumanPrompt & AgentInstructionBase)
+ | (AgentInstructionRequestHumanSelect & AgentInstructionBase)
+ | (AgentInstructionRequestHumanApprove & AgentInstructionBase)
+ | (AgentInstructionResolveAbortedTools & AgentInstructionBase)
+ | (AgentInstructionCompressContext & AgentInstructionBase)
+ | (AgentInstructionFinish & AgentInstructionBase);
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 85d3249a628..f91e6bc2398 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -1266,6 +1266,8 @@ export class MessageModel {
.insert(messages)
.values({
...normalizedMessage,
+ // Sanitize content to strip null bytes that PostgreSQL rejects
+ content: sanitizeNullBytes(normalizedMessage.content),
// TODO: remove this when the client is updated
createdAt: createdAt ? new Date(createdAt) : undefined,
id,
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index c4a5306aab4..d0749a814c0 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -331,8 +331,14 @@ export const createRuntimeExecutors = (
}
// Publish stream start event
+ const stepLabel = (instruction as any).stepLabel;
await streamManager.publishStreamEvent(operationId, {
- data: { assistantMessage: assistantMessageItem, model, provider },
+ data: {
+ assistantMessage: assistantMessageItem,
+ model,
+ provider,
+ ...(stepLabel && { stepLabel }),
+ },
stepIndex,
type: 'stream_start',
});
@@ -810,6 +816,7 @@ export const createRuntimeExecutors = (
data: {
finalContent: content,
grounding,
+ ...(stepLabel && { stepLabel }),
imageList: imageList.length > 0 ? imageList : undefined,
reasoning: thinkingContent || undefined,
toolsCalling,
@@ -885,6 +892,12 @@ export const createRuntimeExecutors = (
if (cost) newState.cost = cost;
}
+ // Propagate stepLabel from instruction to state metadata for hook consumers
+ if (stepLabel) {
+ if (!newState.metadata) newState.metadata = {};
+ newState.metadata._stepLabel = stepLabel;
+ }
+
return {
events,
newState,
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 55332fff2c6..51425f0d7bc 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -1,4 +1,9 @@
-import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
+import type {
+ Agent,
+ AgentRuntimeContext,
+ AgentState,
+ GeneralAgentConfig,
+} from '@lobechat/agent-runtime';
import { AgentRuntime, findInMessages, GeneralChatAgent } from '@lobechat/agent-runtime';
import type { ISnapshotStore } from '@lobechat/agent-tracing';
import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
@@ -80,6 +85,13 @@ function formatErrorForState(error: unknown): ChatMessageError {
}
export interface AgentRuntimeServiceOptions {
+ /**
+ * Custom agent factory. When provided, this function is called instead of
+ * the default `new GeneralChatAgent(config)` to create the Agent instance.
+ * This allows injecting alternative Agent implementations (e.g. GraphAgent)
+ * without the service needing to know about them.
+ */
+ agentFactory?: (config: GeneralAgentConfig) => Agent;
/**
* Coordinator configuration options
* Allows injection of custom stateManager and streamEventManager
@@ -121,6 +133,7 @@ export interface AgentRuntimeServiceOptions {
* ```
*/
export class AgentRuntimeService {
+ private agentFactory?: (config: GeneralAgentConfig) => Agent;
private coordinator: AgentRuntimeCoordinator;
private streamManager: IStreamEventManager;
private queueService: QueueService | null;
@@ -148,6 +161,7 @@ export class AgentRuntimeService {
this.queueService =
options?.queueService === null ? null : (options?.queueService ?? new QueueService());
this.snapshotStore = options?.snapshotStore ?? this.createDefaultSnapshotStore();
+ this.agentFactory = options?.agentFactory;
this.serverDB = db;
this.userId = userId;
this.messageModel = new MessageModel(db, this.userId);
@@ -750,6 +764,7 @@ export class AgentRuntimeService {
const elapsedMs = stepResult.newState?.createdAt
? Date.now() - new Date(stepResult.newState.createdAt).getTime()
: undefined;
+ const stepLabel = metadata?._stepLabel;
await hookDispatcher.dispatch(
operationId,
'afterStep',
@@ -759,6 +774,7 @@ export class AgentRuntimeService {
elapsedMs,
executionTimeMs: stepPresentationData.executionTimeMs,
finalState: stepResult.newState,
+ ...(stepLabel && { stepLabel }),
lastLLMContent: tracking.lastLLMContent,
lastToolsCalling: tracking.lastToolsCalling,
operationId,
@@ -1406,8 +1422,8 @@ export class AgentRuntimeService {
operationId: string;
stepIndex: number;
}) {
- // Create Durable Agent instance
- const agent = new GeneralChatAgent({
+ // Create Agent instance β€” use custom factory if provided, otherwise default to GeneralChatAgent
+ const generalConfig = {
agentConfig: metadata?.agentConfig,
compressionConfig: {
enabled: metadata?.agentConfig?.chatConfig?.enableContextCompression ?? true,
@@ -1416,7 +1432,11 @@ export class AgentRuntimeService {
modelRuntimeConfig: metadata?.modelRuntimeConfig,
operationId,
userId: metadata?.userId,
- });
+ };
+
+ const agent = this.agentFactory
+ ? this.agentFactory(generalConfig)
+ : new GeneralChatAgent(generalConfig);
// Create streaming executor context
const executorContext: RuntimeExecutorContext = {
diff --git a/src/server/services/agentRuntime/hooks/types.ts b/src/server/services/agentRuntime/hooks/types.ts
index 5aa61c08149..a1f0310e716 100644
--- a/src/server/services/agentRuntime/hooks/types.ts
+++ b/src/server/services/agentRuntime/hooks/types.ts
@@ -67,22 +67,23 @@ export interface AgentHookEvent {
errorDetail?: string;
errorMessage?: string;
+
/** Step execution time in ms (afterStep only) */
executionTimeMs?: number;
-
/**
* Full AgentState β€” only available in local mode.
* Not serialized to webhook payloads.
* Use for consumers that need deep state access (e.g., SubAgent Thread updates).
*/
finalState?: any;
+
lastAssistantContent?: string;
/** Last LLM content from previous steps β€” for showing context during tool execution (afterStep only) */
lastLLMContent?: string;
/** Last tools calling from previous steps (afterStep only) */
lastToolsCalling?: any;
-
llmCalls?: number;
+
// Caller-provided metadata (from webhook.body)
metadata?: Record<string, unknown>;
operationId: string;
@@ -95,8 +96,10 @@ export interface AgentHookEvent {
status?: string; // 'done' | 'error' | 'interrupted' | 'waiting_for_human'
/** Step cost (afterStep only, LLM steps) */
stepCost?: number;
-
stepIndex?: number;
+
+ /** Step label for display (e.g. graph node name when using GraphAgent) */
+ stepLabel?: string;
steps?: number;
stepType?: string; // 'call_llm' | 'call_tool'
/** Whether next step is LLM thinking (afterStep only) */