agent-runtime-hooks
- Repo stars 77,599
- Author updated Live
- Author repo lobehub
- Domain
- AI
- Compatible agents
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- Trust score
- 88 / 100 · community maintained
- Author / version / license
- @lobehub · no license declared
- Token usage
- Lean
- Setup complexity
- Guided setup
- External API key
- Not required
- Operating systems
- Unspecified (assume cross-platform)
- Runtime requirements
- No special requirements
- Permissions
-
- Read-only
- Shell exec
- Write / modify
- Network behavior
- External requests
- Install commands
- 26 variants
Profile is derived at build time from SKILL.md and install vectors. Subject to drift from author intent.
Heads up: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: agent-runtime-hooks
description: Agent runtime lifecycle hooks for observing and intercepting agent execution. Use when adding ho…
category: ai
runtime: no special runtime
---
# agent-runtime-hooks output preview
## PART A: Task fit
- Use case: Agent runtime lifecycle hooks for observing and intercepting agent execution. Use when adding hooks to agent operations, mocking tool calls, logging step events, handling human intervention, sub-agent calls, context compression, or building eval/tracing integrations. Triggers on 'hooks', 'beforeToolCall', 'afterToolCall', 'beforeStep', 'afterStep', 'onComplete', 'onError', 'tool mock', 'agent lifecycle', 'human intervention', 'callAgent', 'compact'..
- Inputs: target material, constraints, expected output, and acceptance criteria.
- Evidence boundary: follow “Hook Types / Key Files / Registration Flow” and do not present inference as author intent.
## PART B: Execution result
- **01** The card summarizes the use case; runtime output centers on “Agent runtime lifecycle hooks for observing and intercepting agent execution. Use when adding hooks to agent operations, mocking tool calls, logging step events, handling human intervention, sub-agent calls, context compression, or building eval/tracing integrations. Triggers on 'hooks', 'beforeToolCall', 'afterToolCall', 'beforeStep', 'afterStep', 'onComplete', 'onError', 'tool mock', 'agent lifecycle', 'human intervention', 'callAgent', 'compact'.”.
- **02** When the source has headings, the agent prioritizes “Hook Types / Key Files / Registration Flow” so the result follows the author’s structure.
- **03** Typical output includes task judgment, concrete steps, required commands or file edits, validation, and follow-up options.
- **04** Risk context follows the fingerprint: read files, run shell commands, write/modify files; may access external network resources; usually needs no extra API key.
## Running Rules
- read files, run shell commands, write/modify files; may access external network resources; usually needs no extra API key.
- Validate with a small sample before expanding scope.
- Return the result, validation criteria, and next iteration options. The source does not require a stable slash command. After installation, invoke the skill by name and describe the task.
Name target files or source material, expected output, forbidden changes, and whether network or shell access is allowed. Permission fingerprint: read files, run shell commands, write/modify files.
Start with a small task and check whether the result follows “Hook Types / Key Files / Registration Flow”. Inspect diffs, logs, previews, or tests before expanding scope.
Confirm the final output includes a concrete result, evidence, and next action. If it stays generic, tighten inputs, boundaries, and acceptance criteria.
---
name: agent-runtime-hooks
description: Agent runtime lifecycle hooks for observing and intercepting agent execution. Use when adding ho…
category: ai
source: lobehub/lobehub
---
# agent-runtime-hooks
## When to use
- Agent runtime lifecycle hooks for observing and intercepting agent execution. Use when adding hooks to agent operation…
- Use it when the task has clear inputs, repeatable steps, and validation criteria.
## What to provide
- Target material, scope, expected result, and forbidden changes.
- Whether network, commands, file writes, or external services are allowed.
## Execution rules
- Organize steps around “Hook Types / Key Files / Registration Flow” and keep inference separate from source facts.
- read files, run shell commands, write/modify files; may access external network resources; usually needs no extra API key.
- Validate with a small sample before expanding the task.
## Output requirements
- Return the deliverable, key evidence, validation method, and next action.
- Mark missing information as unknown; do not invent commands, platforms, or dependencies. The author source anchors workflow facts; repository files anchor sources and commands; Fluxly only adds fit, limitations, and quality judgment.
skill "agent-runtime-hooks" {
input -> user goal + target files + boundaries + acceptance criteria
context -> Hook Types / Key Files / Registration Flow
rules -> SKILL.md triggers / order / output contract
runtime -> no special runtime | read files, run shell commands, write/modify files | may access external network resources
guardrails -> usually needs no extra API key + small-sample validation + diff/log review
output -> copyable result + checklist + next iteration
} 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) |
src/server/services/agentRuntime/hooks/types.ts |
Server-side types (AgentHook, re-exports) |
src/server/services/agentRuntime/hooks/HookDispatcher.ts |
Registration, dispatch, dispatchBeforeToolCall |
src/server/modules/AgentRuntime/RuntimeExecutors.ts |
Tool/Compact/HumanIntervention hook dispatch |
src/server/services/agentRuntime/AgentRuntimeService.ts |
Step hooks + HumanIntervention resume/reject |
src/server/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:
beforeToolCallsupports mock viaevent.mock()— usesdispatchBeforeToolCall()which returns the mock result. - Sequential: Same-type hooks run in registration order.
- Local only:
beforeToolCallmock 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, sobeforeToolCall/afterToolCallcover them. Useevent.identifierto filter.
Real-World Example: agent-evals
See devtools/agent-evals/helpers/runner.ts — createEvalHooks() uses afterStep, onComplete, afterToolCall, and beforeToolCall (for mock).
Decide Fit First
Design Intent
How To Use It
Boundaries And Review