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.

♻️ refactor(agent-runtime): improve AgentInstruction types and extract hook event types

Arvin Xu4f2f0055e185
diff --git a/packages/agent-runtime/src/types/hooks.ts b/packages/agent-runtime/src/types/hooks.ts
new file mode 100644
index 00000000000..73c2152a83e
--- /dev/null
+++ b/packages/agent-runtime/src/types/hooks.ts
@@ -0,0 +1,92 @@
+/**
+ * Agent Runtime Hook Types
+ *
+ * Pure data types for hook lifecycle events.
+ * The hook registration/dispatch mechanism (AgentHook, webhook delivery,
+ * serialization) lives in the server layer.
+ */
+
+/**
+ * Lifecycle hook points in agent execution
+ */
+export type AgentHookType =
+ | 'afterStep' // After each step completes
+ | 'beforeStep' // Before each step executes
+ | 'onComplete' // Operation reaches terminal state (done/error/interrupted)
+ | 'onError'; // Error during execution
+
+/**
+ * Unified event payload passed to hook handlers and webhook payloads
+ */
+export interface AgentHookEvent {
+ // Identification
+ agentId: string;
+ /** LLM text output (afterStep only) */
+ content?: string;
+ // Statistics
+ cost?: number;
+ duration?: number;
+ /** Elapsed time since operation started in ms (afterStep only) */
+ elapsedMs?: number;
+ // Content
+ 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;
+ // Execution result
+ reason?: string; // 'done' | 'error' | 'interrupted' | 'max_steps' | 'cost_limit'
+ /** LLM reasoning / thinking content (afterStep only) */
+ reasoning?: string;
+ // Step-specific (for beforeStep/afterStep)
+ shouldContinue?: boolean;
+ 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) */
+ thinking?: boolean;
+
+ toolCalls?: number;
+ /** Tools the LLM decided to call (afterStep only) */
+ toolsCalling?: any;
+ /** Results from tool execution (afterStep only) */
+ toolsResult?: any;
+ topicId?: string;
+ /** Cumulative total cost (afterStep only) */
+ totalCost?: number;
+ /** Cumulative input tokens (afterStep only) */
+ totalInputTokens?: number;
+ /** Cumulative output tokens (afterStep only) */
+ totalOutputTokens?: number;
+ /** Total steps executed so far (afterStep only) */
+ totalSteps?: number;
+ totalTokens?: number;
+ /** Running total of tool calls across all steps (afterStep only) */
+ totalToolCalls?: number;
+
+ userId: string;
+}
diff --git a/packages/agent-runtime/src/types/index.ts b/packages/agent-runtime/src/types/index.ts
index e370fd942c1..c7c5e55008c 100644
--- a/packages/agent-runtime/src/types/index.ts
+++ b/packages/agent-runtime/src/types/index.ts
@@ -1,6 +1,7 @@
export * from './event';
export * from './generalAgent';
export * from './graph';
+export * from './hooks';
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 04804ffc73a..d65961f4b35 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -112,6 +112,8 @@ export interface Agent {
tools?: ToolRegistry;
}
+// ── Payloads ──────────────────────────────────────────────
+
export interface CallLLMPayload {
isFirstMessage?: boolean;
messages: any[];
@@ -145,84 +147,6 @@ export interface HumanAbortPayload {
toolsCalling?: ChatToolPayload[];
}
-export interface AgentInstructionCallLlm {
- payload: any;
- type: 'call_llm';
-}
-
-export interface AgentInstructionCallTool {
- payload: {
- parentMessageId: string;
- toolCalling: ChatToolPayload;
- };
- type: 'call_tool';
-}
-
-export interface AgentInstructionCallToolsBatch {
- payload: {
- parentMessageId: string;
- toolsCalling: ChatToolPayload[];
- } & any;
- type: 'call_tools_batch';
-}
-
-export interface AgentInstructionRequestHumanPrompt {
- metadata?: Record<string, unknown>;
- prompt: string;
- reason?: string;
- type: 'request_human_prompt';
-}
-
-export interface AgentInstructionRequestHumanSelect {
- metadata?: Record<string, unknown>;
- multi?: boolean;
- options: Array<{ label: string; value: string }>;
- prompt?: string;
- reason?: string;
- type: 'request_human_select';
-}
-
-export interface AgentInstructionRequestHumanApprove {
- pendingToolsCalling: ChatToolPayload[];
- reason?: string;
- skipCreateToolMessage?: boolean;
- type: 'request_human_approve';
-}
-
-export interface AgentInstructionFinish {
- reason: FinishReason;
- reasonDetail?: string;
- type: 'finish';
-}
-
-export interface AgentInstructionResolveAbortedTools {
- payload: {
- /** Parent message ID (assistant message) */
- parentMessageId: string;
- /** Reason for the abort */
- reason?: string;
- /** Tool calls that need to be resolved/cancelled */
- toolsCalling: ChatToolPayload[];
- };
- type: 'resolve_aborted_tools';
-}
-
-/**
- * Instruction to execute context compression
- * When triggered, compresses ALL messages into a single MessageGroup summary
- */
-export interface AgentInstructionCompressContext {
- payload: {
- /** Current token count before compression */
- currentTokenCount: number;
- /** Existing summary to incorporate (for incremental compression) */
- existingSummary?: string;
- /** Messages to compress */
- messages: any[];
- };
- type: 'compress_context';
-}
-
/**
* Task definition for exec_tasks instruction
*/
@@ -251,60 +175,6 @@ export interface ExecTaskItem {
timeout?: number;
}
-/**
- * Instruction to execute a single async task (server-side)
- */
-export interface AgentInstructionExecTask {
- payload: {
- /** Parent message ID (tool message that triggered the task) */
- parentMessageId: string;
- /** Task to execute */
- task: ExecTaskItem;
- };
- type: 'exec_task';
-}
-
-/**
- * Instruction to execute multiple async tasks in parallel (server-side)
- */
-export interface AgentInstructionExecTasks {
- payload: {
- /** Parent message ID (tool message that triggered the tasks) */
- parentMessageId: string;
- /** Array of tasks to execute */
- tasks: ExecTaskItem[];
- };
- type: 'exec_tasks';
-}
-
-/**
- * Instruction to execute a single async task on the client (desktop only)
- * Used when task requires local tools like file system or shell commands
- */
-export interface AgentInstructionExecClientTask {
- payload: {
- /** Parent message ID (tool message that triggered the task) */
- parentMessageId: string;
- /** Task to execute */
- task: ExecTaskItem;
- };
- type: 'exec_client_task';
-}
-
-/**
- * Instruction to execute multiple async tasks on the client in parallel (desktop only)
- * Used when tasks require local tools like file system or shell commands
- */
-export interface AgentInstructionExecClientTasks {
- payload: {
- /** Parent message ID (tool message that triggered the tasks) */
- parentMessageId: string;
- /** Array of tasks to execute */
- tasks: ExecTaskItem[];
- };
- type: 'exec_client_tasks';
-}
-
/**
* Payload for task_result phase (single task)
*/
@@ -347,30 +217,163 @@ export interface TasksBatchResultPayload {
}>;
}
+// ── Instructions ──────────────────────────────────────────
+
/**
* 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 {
+export interface AgentInstructionBase {
/** Human-readable label for this step (e.g. graph node name). Propagated to stream events and hooks. */
stepLabel?: string;
}
+// ─ LLM ───────────────────────────────────────────────────
+
+export interface AgentInstructionCallLlm extends AgentInstructionBase {
+ payload: any;
+ type: 'call_llm';
+}
+
+// ─ Tool ──────────────────────────────────────────────────
+
+export interface AgentInstructionCallTool extends AgentInstructionBase {
+ payload: {
+ parentMessageId: string;
+ toolCalling: ChatToolPayload;
+ };
+ type: 'call_tool';
+}
+
+export interface AgentInstructionCallToolsBatch extends AgentInstructionBase {
+ payload: {
+ parentMessageId: string;
+ toolsCalling: ChatToolPayload[];
+ } & any;
+ type: 'call_tools_batch';
+}
+
+export interface AgentInstructionResolveAbortedTools extends AgentInstructionBase {
+ payload: {
+ /** Parent message ID (assistant message) */
+ parentMessageId: string;
+ /** Reason for the abort */
+ reason?: string;
+ /** Tool calls that need to be resolved/cancelled */
+ toolsCalling: ChatToolPayload[];
+ };
+ type: 'resolve_aborted_tools';
+}
+
+// ─ Task ──────────────────────────────────────────────────
+
+export interface AgentInstructionExecTask extends AgentInstructionBase {
+ payload: {
+ /** Parent message ID (tool message that triggered the task) */
+ parentMessageId: string;
+ /** Task to execute */
+ task: ExecTaskItem;
+ };
+ type: 'exec_task';
+}
+
+export interface AgentInstructionExecTasks extends AgentInstructionBase {
+ payload: {
+ /** Parent message ID (tool message that triggered the tasks) */
+ parentMessageId: string;
+ /** Array of tasks to execute */
+ tasks: ExecTaskItem[];
+ };
+ type: 'exec_tasks';
+}
+
+export interface AgentInstructionExecClientTask extends AgentInstructionBase {
+ payload: {
+ /** Parent message ID (tool message that triggered the task) */
+ parentMessageId: string;
+ /** Task to execute */
+ task: ExecTaskItem;
+ };
+ type: 'exec_client_task';
+}
+
+export interface AgentInstructionExecClientTasks extends AgentInstructionBase {
+ payload: {
+ /** Parent message ID (tool message that triggered the tasks) */
+ parentMessageId: string;
+ /** Array of tasks to execute */
+ tasks: ExecTaskItem[];
+ };
+ type: 'exec_client_tasks';
+}
+
+// ─ Human Interaction ─────────────────────────────────────
+
+export interface AgentInstructionRequestHumanPrompt extends AgentInstructionBase {
+ metadata?: Record<string, unknown>;
+ prompt: string;
+ reason?: string;
+ type: 'request_human_prompt';
+}
+
+export interface AgentInstructionRequestHumanSelect extends AgentInstructionBase {
+ metadata?: Record<string, unknown>;
+ multi?: boolean;
+ options: Array<{ label: string; value: string }>;
+ prompt?: string;
+ reason?: string;
+ type: 'request_human_select';
+}
+
+export interface AgentInstructionRequestHumanApprove extends AgentInstructionBase {
+ pendingToolsCalling: ChatToolPayload[];
+ reason?: string;
+ skipCreateToolMessage?: boolean;
+ type: 'request_human_approve';
+}
+
+// ─ Control ───────────────────────────────────────────────
+
+export interface AgentInstructionCompressContext extends AgentInstructionBase {
+ payload: {
+ /** Current token count before compression */
+ currentTokenCount: number;
+ /** Existing summary to incorporate (for incremental compression) */
+ existingSummary?: string;
+ /** Messages to compress */
+ messages: any[];
+ };
+ type: 'compress_context';
+}
+
+export interface AgentInstructionFinish extends AgentInstructionBase {
+ reason: FinishReason;
+ reasonDetail?: string;
+ type: 'finish';
+}
+
+// ── Union Type ────────────────────────────────────────────
+
/**
* A serializable instruction object that the "Agent" (Brain) returns
* to the "AgentRuntime" (Engine) to execute.
*/
export type AgentInstruction =
- | (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);
+ // LLM
+ | AgentInstructionCallLlm
+ // Tool
+ | AgentInstructionCallTool
+ | AgentInstructionCallToolsBatch
+ | AgentInstructionResolveAbortedTools
+ // Task
+ | AgentInstructionExecTask
+ | AgentInstructionExecTasks
+ | AgentInstructionExecClientTask
+ | AgentInstructionExecClientTasks
+ // Human Interaction
+ | AgentInstructionRequestHumanPrompt
+ | AgentInstructionRequestHumanSelect
+ | AgentInstructionRequestHumanApprove
+ // Control
+ | AgentInstructionCompressContext
+ | AgentInstructionFinish;
diff --git a/src/server/services/agentRuntime/hooks/types.ts b/src/server/services/agentRuntime/hooks/types.ts
index a1f0310e716..1ac93abca8b 100644
--- a/src/server/services/agentRuntime/hooks/types.ts
+++ b/src/server/services/agentRuntime/hooks/types.ts
@@ -1,38 +1,13 @@
/**
* Agent Runtime Hooks β€” external lifecycle hook system
*
- * Hooks are registered once and automatically adapt to the runtime mode:
- * - Local mode: handler function is called directly (in-process)
- * - Production (QStash) mode: webhook is delivered via HTTP POST
+ * Hook event types are defined in @lobechat/agent-runtime (shared).
+ * Hook registration, webhook delivery, and serialization types are server-specific.
*/
-// ── Hook Types ──────────────────────────────────────────
+export type { AgentHookEvent, AgentHookType } from '@lobechat/agent-runtime';
-/**
- * Lifecycle hook points in agent execution
- */
-export type AgentHookType =
- | 'afterStep' // After each step completes
- | 'beforeStep' // Before each step executes
- | 'onComplete' // Operation reaches terminal state (done/error/interrupted)
- | 'onError'; // Error during execution
-
-/**
- * Hook definition β€” consumers register these with execAgent
- */
-export interface AgentHook {
- /** Handler function for local mode (called in-process) */
- handler: (event: AgentHookEvent) => Promise<void>;
-
- /** Unique hook identifier (for logging, debugging, idempotency) */
- id: string;
-
- /** Hook lifecycle point */
- type: AgentHookType;
-
- /** Webhook config for production mode (if omitted, hook only works in local mode) */
- webhook?: AgentHookWebhook;
-}
+// ── Server-side Hook Types ───────────────────────────────
/**
* Webhook delivery configuration for production mode
@@ -48,82 +23,21 @@ export interface AgentHookWebhook {
url: string;
}
-// ── Hook Events ──────────────────────────────────────────
-
/**
- * Unified event payload passed to hook handlers and webhook payloads
+ * Hook definition β€” consumers register these with execAgent
*/
-export interface AgentHookEvent {
- // Identification
- agentId: string;
- /** LLM text output (afterStep only) */
- content?: string;
- // Statistics
- cost?: number;
- duration?: number;
- /** Elapsed time since operation started in ms (afterStep only) */
- elapsedMs?: number;
- // Content
- 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;
- // Execution result
- reason?: string; // 'done' | 'error' | 'interrupted' | 'max_steps' | 'cost_limit'
- /** LLM reasoning / thinking content (afterStep only) */
- reasoning?: string;
- // Step-specific (for beforeStep/afterStep)
- shouldContinue?: boolean;
- status?: string; // 'done' | 'error' | 'interrupted' | 'waiting_for_human'
- /** Step cost (afterStep only, LLM steps) */
- stepCost?: number;
- stepIndex?: number;
+export interface AgentHook {
+ /** Handler function for local mode (called in-process) */
+ handler: (event: AgentHookEvent) => Promise<void>;
- /** 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) */
- thinking?: boolean;
+ /** Unique hook identifier (for logging, debugging, idempotency) */
+ id: string;
- toolCalls?: number;
- /** Tools the LLM decided to call (afterStep only) */
- toolsCalling?: any;
- /** Results from tool execution (afterStep only) */
- toolsResult?: any;
- topicId?: string;
- /** Cumulative total cost (afterStep only) */
- totalCost?: number;
- /** Cumulative input tokens (afterStep only) */
- totalInputTokens?: number;
- /** Cumulative output tokens (afterStep only) */
- totalOutputTokens?: number;
- /** Total steps executed so far (afterStep only) */
- totalSteps?: number;
- totalTokens?: number;
- /** Running total of tool calls across all steps (afterStep only) */
- totalToolCalls?: number;
+ /** Hook lifecycle point */
+ type: AgentHookType;
- userId: string;
+ /** Webhook config for production mode (if omitted, hook only works in local mode) */
+ webhook?: AgentHookWebhook;
}
// ── Serialized Hook (for Redis persistence) ──────────────