Agent Skillslobehub/lobehub › agent-runtime-hooks

agent-runtime-hooks

GitHub

提供Agent执行生命周期钩子机制,支持在步骤前后、工具调用、人工干预、上下文压缩及子代理调用等关键节点进行拦截、观测、Mock或注入逻辑。

.agents/skills/agent-runtime-hooks/SKILL.md lobehub/lobehub

Trigger Scenarios

需要监控Agent内部执行流程 实现工具调用Mock或测试 集成人工审批流 自定义上下文压缩逻辑

Install

npx skills add lobehub/lobehub --skill agent-runtime-hooks -g -y
More Options

Non-standard path

npx skills add https://github.com/lobehub/lobehub/tree/canary/.agents/skills/agent-runtime-hooks -g -y

Use without installing

npx skills use lobehub/lobehub@agent-runtime-hooks

指定 Agent (Claude Code)

npx skills add lobehub/lobehub --skill agent-runtime-hooks -a claude-code -g -y

安装 repo 全部 skill

npx skills add lobehub/lobehub --all -g -y

预览 repo 内 skill

npx skills add lobehub/lobehub --list

SKILL.md

Frontmatter
{
    "name": "agent-runtime-hooks",
    "description": "Agent runtime lifecycle hooks. Use for before\/after tool or step hooks, tool mocks, human intervention, sub-agent calls, context compression, evals, callAgent, or lifecycle events.",
    "user-invocable": false
}

Agent Runtime Hooks

Lifecycle hooks for observing and intercepting agent execution. Hooks are registered per-operation via execAgent({ hooks }) and dispatched by HookDispatcher.

Hook Types

16 hook types across 5 categories:

execAgent({ hooks })
  │
  ├─ beforeStep ──────────── Before each step executes
  │     │
  │     ├─ [call_llm]        LLM inference
  │     │
  │     ├─ [call_tool]
  │     │     ├─ beforeToolCall ── Before tool executes (supports mocking)
  │     │     ├─ (tool execution)
  │     │     ├─ afterToolCall ─── After tool completes (observation only)
  │     │     └─ onToolCallError ─ Tool threw an exception
  │     │
  │     ├─ [request_human_approve]
  │     │     ├─ beforeHumanIntervention ── Before agent pauses
  │     │     ├─ afterHumanIntervention ─── After approve/reject + resume
  │     │     └─ onStopByHumanIntervention ── User rejected, agent halted
  │     │
  │     ├─ [compress_context]
  │     │     ├─ beforeCompact ──── Before compression starts
  │     │     ├─ afterCompact ───── After compression completes
  │     │     └─ onCompactError ─── Compression failed
  │     │
  │     ├─ [callAgent] (via execSubAgentTask)
  │     │     ├─ beforeCallAgent ── Before sub-agent starts
  │     │     ├─ afterCallAgent ─── After sub-agent completes
  │     │     └─ onCallAgentError ── Sub-agent failed
  │     │
  │     └─ afterStep ──────────── After step completes
  │
  ├─ (next step...)
  │
  ├─ onComplete ───────────── Operation reaches terminal state
  └─ onError ──────────────── Error during execution

Key Files

File Role
packages/agent-runtime/src/types/hooks.ts Type definitions (AgentHookType, all event interfaces)
apps/server/src/services/agentRuntime/hooks/types.ts Server-side types (AgentHook, re-exports)
apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts Registration, dispatch, dispatchBeforeToolCall
apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts Tool/Compact/HumanIntervention hook dispatch
apps/server/src/services/agentRuntime/AgentRuntimeService.ts Step hooks + HumanIntervention resume/reject
apps/server/src/services/aiAgent/index.ts CallAgent hook dispatch

Registration Flow

const hooks: AgentHook[] = [
  { id: 'my-hook', type: 'afterStep', handler: async (event) => { ... } },
];
await aiAgentService.execAgent({ agentId, prompt, hooks });
// Internally: hookDispatcher.register(operationId, hooks)
// Cleanup:    hookDispatcher.unregister(operationId)

Hook Reference

Step Level

beforeStep — Before each step. event: AgentHookEvent afterStep — After each step. event: AgentHookEvent (content, toolsCalling, totalCost, etc.) onComplete — Terminal state. event: AgentHookEvent (reason: done/error/interrupted/max_steps/cost_limit) onError — Error occurred. event: AgentHookEvent (errorMessage, errorDetail)

Tool Call Level

beforeToolCall — Before tool executes. Supports mocking via event.mock().

// event: ToolCallHookEvent
{
  (identifier, apiName, args, callIndex, stepIndex, operationId, mock);
}
// Mock example:
event.mock({ content: '{"error":"rate limited"}' });

Dispatch method: hookDispatcher.dispatchBeforeToolCall() (returns mock result or null).

afterToolCall — After tool completes. Observation only.

// event: AfterToolCallHookEvent
{
  (identifier, apiName, args, callIndex, content, success, mocked, executionTimeMs, stepIndex);
}

onToolCallError — Tool threw an exception (catch block, not just success=false).

// event: ToolCallErrorHookEvent
{
  (identifier, apiName, args, callIndex, error, stepIndex);
}

Human Intervention

beforeHumanIntervention — Before agent pauses for approval.

// event: BeforeHumanInterventionHookEvent
{ operationId, stepIndex, pendingTools: [{ identifier, apiName }] }

afterHumanIntervention — After approve/reject, agent resumes.

// event: AfterHumanInterventionHookEvent
{ operationId, action: 'approve' | 'reject' | 'rejectAndContinue', toolCallId?, rejectionReason? }

onStopByHumanIntervention — User rejected, agent halted.

// event: StopByHumanInterventionHookEvent
{ operationId, toolCallId?, rejectionReason? }

Context Compression

beforeCompact — Before compression starts.

// event: BeforeCompactHookEvent
{
  (operationId, stepIndex, messageCount, tokenCount);
}

afterCompact — After compression completes.

// event: AfterCompactHookEvent
{
  (operationId, stepIndex, groupId, messagesBefore, messagesAfter, summary);
}

onCompactError — Compression failed.

// event: CompactErrorHookEvent
{
  (operationId, stepIndex, tokenCount, error);
}

Sub-Agent (CallAgent)

beforeCallAgent — Before calling sub-agent. Dispatched on parent operation.

// event: BeforeCallAgentHookEvent
{
  (operationId, agentId, instruction);
}

afterCallAgent — Sub-agent completed. Dispatched on parent operation.

// event: AfterCallAgentHookEvent
{
  (operationId, agentId, subOperationId, threadId, success);
}

onCallAgentError — Sub-agent failed. Dispatched on parent operation.

// event: CallAgentErrorHookEvent
{
  (operationId, agentId, error);
}

Note: CallAgent hooks require parentOperationId in ExecSubAgentTaskParams.

Design Notes

  • Fire-and-forget: All handlers return Promise<void>. Errors are non-fatal.
  • Exception: beforeToolCall supports mock via event.mock() — uses dispatchBeforeToolCall() which returns the mock result.
  • Sequential: Same-type hooks run in registration order.
  • Local only: beforeToolCall mock only works in local mode (in-memory hooks). Webhook mode does not support mocking.
  • Scoped per operation: Auto-cleaned via hookDispatcher.unregister() on completion.
  • Sandbox/MCP: No separate hooks — they go through executeTool, so beforeToolCall/afterToolCall cover them. Use event.identifier to filter.

Real-World Example: agent-evals

See devtools/agent-evals/helpers/runner.tscreateEvalHooks() uses afterStep, onComplete, afterToolCall, and beforeToolCall (for mock).

Version History

  • 29fe043 Current 2026-08-20 18:32

Same Skill Collection

.agents/skills/add-provider-doc/SKILL.md
.agents/skills/add-setting-env/SKILL.md
.agents/skills/agent-signal/SKILL.md
.agents/skills/agent-testing-bot/SKILL.md
.agents/skills/agent-tracing/SKILL.md
.agents/skills/agent-work/SKILL.md
.agents/skills/builtin-tool/SKILL.md
.agents/skills/chat-sdk/SKILL.md
.agents/skills/cleanup-git-worktrees/SKILL.md
.agents/skills/cli/SKILL.md
.agents/skills/data-fetching-architecture/SKILL.md
.agents/skills/db-migrations/SKILL.md
.agents/skills/debug-package/SKILL.md
.agents/skills/deep-review/SKILL.md
.agents/skills/design-prototype/SKILL.md
.agents/skills/desktop/SKILL.md
.agents/skills/docs-changelog/SKILL.md
.agents/skills/drizzle/SKILL.md
.agents/skills/heterogeneous-agent/SKILL.md
.agents/skills/hotkey/SKILL.md
.agents/skills/i18n/SKILL.md
.agents/skills/linear/SKILL.md
.agents/skills/llm-generation/SKILL.md
.agents/skills/modal/SKILL.md
.agents/skills/model-bank-metadata/SKILL.md
.agents/skills/product-design/SKILL.md
.agents/skills/project-overview/SKILL.md
.agents/skills/react/SKILL.md
.agents/skills/response-compliance/SKILL.md
.agents/skills/skills-audit/SKILL.md
.agents/skills/spa-routes/SKILL.md
.agents/skills/split-micro-app/SKILL.md
.agents/skills/store-data-structures/SKILL.md
.agents/skills/testing/SKILL.md
.agents/skills/trpc-router/SKILL.md
.agents/skills/typescript/SKILL.md
.agents/skills/upstash-workflow/SKILL.md
.agents/skills/ux-audit/SKILL.md
.agents/skills/ux/SKILL.md
.agents/skills/version-release/SKILL.md
.agents/skills/zustand/SKILL.md
.agents/skills/agent-testing/SKILL.md
.agents/skills/compose-atoms/SKILL.md
.agents/skills/debug-frontend-with-browser/SKILL.md
.agents/skills/pr/SKILL.md
packages/builtin-skills/src/acceptance/SKILL.md

Metadata

Files
0
Version
a06b4e2
Hash
f5497796
Indexed
2026-08-20 18:32

ホーム - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-30 02:16
浙ICP备14020137号-1 $お客様$