{"data":{"slug":"github-lobehub-lobehub-agents-skills-agent-runtime-hooks-11eb94cb0ee5","title":"Agent Runtime Hook Management","summary":"Register and manage hooks for agent lifecycle events, tool calls, and context compression, with support for logging, mocking, and external notifications.","url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-runtime-hooks-11eb94cb0ee5","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-lobehub-lobehub-agents-skills-agent-runtime-hooks-11eb94cb0ee5","markdown_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-runtime-hooks-11eb94cb0ee5.md","download_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-runtime-hooks-11eb94cb0ee5\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Hooks require an `operationId` for registration and unregistration. Webhook hooks use environment variables for headers and must be configured with `allowedEnvVars`. The first deliverable is a registered hook handler, typically in the form of a function or webhook configuration.","instructions":"---\nname: agent-runtime-hooks\ndescription: 'Use for agent lifecycle hooks, tool mocks, intervention, sub-agent calls and context compression.'\nuser-invocable: false\n---\n\n# Agent Runtime Hooks\n\nRegister lifecycle hooks through `execAgent({ hooks })`. `HookDispatcher` stores them per operation and dispatches them in registration order.\n\n## Hook Types\n\n16 hook types across 5 categories:\n\n```\nexecAgent({ hooks })\n  \u2502\n  \u251c\u2500 beforeStep \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Before each step executes\n  \u2502     \u2502\n  \u2502     \u251c\u2500 [call_llm]        LLM inference\n  \u2502     \u2502\n  \u2502     \u251c\u2500 [call_tool]\n  \u2502     \u2502     \u251c\u2500 beforeToolCall \u2500\u2500 Before tool executes (supports mocking)\n  \u2502     \u2502     \u251c\u2500 (tool execution)\n  \u2502     \u2502     \u251c\u2500 afterToolCall \u2500\u2500\u2500 After tool completes (optional result control)\n  \u2502     \u2502     \u2514\u2500 onToolCallError \u2500 Tool threw an exception\n  \u2502     \u2502\n  \u2502     \u251c\u2500 [request_human_approve]\n  \u2502     \u2502     \u251c\u2500 beforeHumanIntervention \u2500\u2500 Before agent pauses\n  \u2502     \u2502     \u251c\u2500 afterHumanIntervention \u2500\u2500\u2500 After approve\/reject + resume\n  \u2502     \u2502     \u2514\u2500 onStopByHumanIntervention \u2500\u2500 User rejected, agent halted\n  \u2502     \u2502\n  \u2502     \u251c\u2500 [compress_context]\n  \u2502     \u2502     \u251c\u2500 beforeCompact \u2500\u2500\u2500\u2500 Before compression starts\n  \u2502     \u2502     \u251c\u2500 afterCompact \u2500\u2500\u2500\u2500\u2500 After compression completes\n  \u2502     \u2502     \u2514\u2500 onCompactError \u2500\u2500\u2500 Compression failed\n  \u2502     \u2502\n  \u2502     \u251c\u2500 [callAgent] (via execSubAgentTask)\n  \u2502     \u2502     \u251c\u2500 beforeCallAgent \u2500\u2500 Before sub-agent starts\n  \u2502     \u2502     \u251c\u2500 afterCallAgent \u2500\u2500\u2500 After creation\/start returns\n  \u2502     \u2502     \u2514\u2500 onCallAgentError \u2500\u2500 Sub-agent failed\n  \u2502     \u2502\n  \u2502     \u2514\u2500 afterStep \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 After step completes\n  \u2502\n  \u251c\u2500 (next step...)\n  \u2502\n  \u251c\u2500 onComplete \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Operation reaches terminal state\n  \u2514\u2500 onError \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 Error during execution\n```\n\n## Key Files\n\n| File                                                                                             | Role                                                      |\n| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------- |\n| `packages\/agent-runtime\/src\/types\/hooks.ts`                                                      | Event types and required\/optional fields                  |\n| `apps\/server\/src\/services\/agentRuntime\/hooks\/types.ts`                                           | Registration and webhook types                            |\n| `apps\/server\/src\/services\/agentRuntime\/hooks\/HookDispatcher.ts`                                  | Registration, dispatch, local mocks, HTTP\/QStash delivery |\n| `apps\/server\/src\/services\/agentRuntime\/hooks\/webhookPayload.ts`                                  | Event projection and email enrichment                     |\n| `apps\/server\/src\/modules\/AgentRuntime\/adapters\/toolCallHookContext.ts`                           | Shared tool-event context builder                         |\n| `apps\/server\/src\/modules\/AgentRuntime\/adapters\/ServerToolTransport.ts`                           | Tool notifications and execution results                  |\n| `apps\/server\/src\/modules\/AgentRuntime\/RuntimeExecutors.ts`                                       | Tool, compression and human-intervention execution        |\n| `apps\/server\/src\/services\/agentRuntime\/AgentRuntimeService\/` (`executeStep\/`, `intervention.ts`) | Step events and human-intervention continuation           |\n| `apps\/server\/src\/services\/agentRuntime\/CompletionLifecycle\/index.ts`                             | Terminal events                                           |\n| `apps\/server\/src\/services\/aiAgent\/subAgentRuns.ts`                                               | Sub-agent events                                          |\n\n## Registration\n\n```ts\nconst hooks: AgentHook[] = [\n  {\n    id: 'observe-step',\n    type: 'afterStep',\n    handler: async (event) => {\n      console.log(event.operationId, event.stepIndex);\n    },\n  },\n];\nawait aiAgentService.execAgent({ agentId, prompt, hooks });\n```\n\nCompletion cleans up registrations through `hookDispatcher.unregister(operationId)`.\n\n### Webhook Hooks\n\nWebhook-only hooks deliver in both local and queue modes. For hooks with both `handler` and `webhook`, local dispatch calls the handler; queue dispatch uses the serialized webhook. Only webhook configuration is persisted, so functions are unavailable after a process restart.\n\n```ts\nconst hook: AgentHook = {\n  id: 'tool-notification',\n  type: 'afterToolCall',\n  matcher: '^fs\/readFile$',\n  webhook: {\n    url: 'https:\/\/example.com\/hooks',\n    delivery: 'fetch',\n    timeout: 5, \/\/ seconds; default 30\n    headers: { Authorization: 'Bearer ${HOOK_TOKEN}' },\n    allowedEnvVars: ['HOOK_TOKEN'],\n  },\n};\n```\n\n- `matcher` is a regex against `${identifier}\/${apiName}`, supported only on tool events. Omitted, empty, or `*` matches all tools.\n- Header environment templates resolve only at send time from `allowedEnvVars`; persist templates, never resolved secrets.\n- Notifications ignore response content and may return HTTP 204.\n- `beforeToolCall` with `responseHandling: 'toolCall'` awaits an optional HTTP decision before tool execution. Return HTTP 2xx JSON with `{ \"decision\": \"allow\" }` or `{ \"decision\": \"deny\", \"reason\": \"\u7981\u6b62\u6267\u884c\u8be5\u64cd\u4f5c\" }` to intervene. The type is `{ decision: 'allow' } | { decision: 'deny'; reason?: string }`; a deny with an omitted or empty reason uses `Blocked by beforeToolCall hook.`. Denials preserve the reason in the tool result\/card with classification `hook_denied`.\n- `afterToolCall` also accepts `responseHandling: 'toolCall'`. It synchronously checks the full request\/result before archival and model consumption; deny replaces the original result with the receiver's optional reason in both content and blocked state. A deny with an omitted or empty reason uses `Blocked by afterToolCall hook.`, following the same `Blocked by ${type} hook.` rule as `beforeToolCall`. The reason enters model context and the tool card, as with `beforeToolCall`. It does not undo tool side effects, retries, or charges. See [the result-control contract](..\/..\/..\/docs\/development\/agent-tool-result-hooks.md) for deferred completions and runtime boundaries.\n- Environment response modes are `ignore` (default notifications) and `toolCall` (optional decisions for both before and after). Only subscribed events are enabled. Replace removed `toolResult`\/`toolCallAndResult` values with `toolCall`; use the events list to select after-only checking. Existing after responses with a valid decision now control results.\n- HTTP 204, empty successful bodies, invalid JSON, and JSON without a top-level decision (including arrays, scalars, null, or only the old nested `hookSpecificOutput`) are notification responses, even with `onError: 'block'`. Continue checking subsequent hooks; do not treat a notification as permission to skip later policies. Explicit invalid decisions, non-2xx status, oversized bodies, invalid UTF-8, network failures, and timeouts follow `onError: 'continue' | 'block'` (default `continue`); blocking uses `hook_control_error` as the tool-result content and reason for both before and after hooks. Cancellation never grants permission.\n- Extra response fields are allowed and discarded. Only `decision` and a deny's optional string `reason` are consumed; `updatedInput`\/`additionalContext` do not change tool arguments or conversation context.\n- Configuration: `packages\/types\/src\/agentHook.ts`; response parsing: `packages\/types\/src\/agentHookResponse.ts`; HTTP delivery: `apps\/server\/src\/services\/agentRuntime\/hooks\/httpWebhook.ts`.\n\n### Hook configuration lifetime\n\n- Environment hooks (`AGENT_HOOK_WEBHOOK_*`) always come from the executing worker's **current environment**, including after human approval and deferred completion. Never persist their configuration or restore a previous environment's hooks.\n- Code-supplied webhook hooks (`execAgent({ hooks })`) retain the existing per-operation serialization and persistence. Recover these caller hooks from the runtime snapshot or durable operation record; preserve environment-variable templates without expanding secrets into storage.\n- Evaluate each operation's recovered caller hooks in order, then evaluate current environment hooks once in the final round. Do not deduplicate caller hook IDs across operations. Environment-only hooks do not require durable operation storage. Removing an environment hook stops it from controlling subsequent results; when no matching result control remains, allow the result. Do not freeze a previous environment policy across an approval or restart.\n- Deferred completion publishes into its empty placeholder once; duplicate callbacks retain that first final result, including a denial. Propagate caller-policy storage errors rather than treating failed reads as an empty hook list. Do not extend default allow to configured-hook delivery failures: those follow `onError`.\n- Cover environment removal\/addition across approval and snapshot expiry, publication without review markers, and continued enforcement of persisted caller hooks in regression tests.\n\n### Publish after the result hook\n\n- Await result control before archival, message content\/state writes, streaming, and model consumption. Persist the allowed result or the sanitized denial directly; do not add `toolResultControl` pending\/allowed\/blocked metadata or hide raw output through history projections.\n- Human approval sources claim the decision and retain the answer in their private resolution\/outbox. `MessageModel.resolveHumanApproval` defaults to claim-only; only the runtime calls it with `publishResult: true` after result control. Stop\/rejection receipts can publish directly because they contain no executed tool output.\n- Recover original caller hooks through the existing intervention operation identity or deferred callback's parent operation. Keep the in-memory hook verdict separate from tool-owned state; a tool returning `type: 'blocked'` is not a hook verdict.\n- Every deferred backfill, including a member that fails to start, follows the same hook-before-write order. Use the existing empty placeholder to arbitrate duplicate final writes; do not introduce a replacement review state machine.\n- When a thread has a sub-agent or group-member completion bridge, that bridge exclusively publishes its tool result. Thread lifecycle hooks update thread metadata only; never prefill the tool message with an ungated summary, including after approval recovery.\n- Cover an answer held while a hook runs, atomic publication and rollback, duplicate callbacks after policy removal, and partial member startup failure. History readers should need no result-review logic.\n\n## Events\n\n| Event                       | Timing and payload                                                                         |\n| --------------------------- | ------------------------------------------------------------------------------------------ |\n| `beforeStep`                | Before a step; `AgentHookEvent`                                                            |\n| `afterStep`                 | After a step; content, tool calls\/results and usage totals                                 |\n| `onComplete`                | Terminal state; reason such as `done`, `error`, `interrupted`, `max_steps` or `cost_limit` |\n| `onError`                   | Operation error; `errorMessage`, `errorDetail` and available error metadata                |\n| `beforeToolCall`            | Before tool execution; shared tool context and local `mock()` callback                     |\n| `afterToolCall`             | After tool execution; structured `result` and `mocked`                                     |\n| `onToolCallError`           | Tool execution throws; shared tool context and `error`                                     |\n| `beforeHumanIntervention`   | Before approval; `pendingTools`, `operationId`, `stepIndex`                                |\n| `afterHumanIntervention`    | Approval decision and continuation; `action`, optional `toolCallId` and `rejectionReason`  |\n| `onStopByHumanIntervention` | Human rejection stops the run; optional `toolCallId` and `rejectionReason`                 |\n| `beforeCompact`             | Before compression; `messageCount`, `tokenCount`, `stepIndex`                              |\n| `afterCompact`              | After compression; `groupId`, `messagesBefore`, `messagesAfter`, `summary`                 |\n| `onCompactError`            | Compression error; `error`, `tokenCount`, `stepIndex`                                      |\n| `beforeCallAgent`           | Before sub-agent creation; `agentId`, `instruction`                                        |\n| `afterCallAgent`            | Creation\/start returns; `agentId`, `subOperationId`, `success`, optional `threadId`        |\n| `onCallAgentError`          | Sub-agent call fails; `agentId`, `error`                                                   |\n\nCallAgent events dispatch on the parent operation identified by `parentOperationId`. An isolated child supplies `threadId`; shared group members use the shared conversation. Child completion is reported by the child's `onComplete` event.\n\n## Tool Context\n\nUse `buildToolCallHookContext()` for the three tool events.\n\n- Required fields: native `toolCallId`, `assistantMessageId`, `identifier`, `apiName`, effective `args`, `callIndex`, `stepIndex`, `operationId` and `executor`.\n- Optional associations come from the run context: agent, topic, session, thread, group, task, workspace, document, source\/tool message and parent operation IDs.\n- `userId` uses `runtime.userId ?? origin.userId`.\n- `toolSource` identifies the tool's origin; `executor` identifies the server\/client dispatch route. `executionTarget` and `activeDeviceId` describe the run's execution plan and device selection.\n- `afterToolCall.result` carries `content`, `success`, optional `executionTime` and error\/state data such as `state.type: 'blocked'`. `mocked` marks results supplied by a local hook.\n\nSandbox and MCP tools use the same event path. Filter with `identifier`, `apiName` or `toolSource`.\n\n### Local Mocking\n\n`dispatchBeforeToolCall()` exposes `event.mock(result)`. The first accepted mock wins and short-circuits the remaining mock handlers. The method returns `{ isMocked: true, result }` for a mock, or `null` to continue execution.\n\n```ts\nevent.mock({ content: '{\"items\":[]}', success: true });\n```\n\nTool observation payloads use `BeforeToolCallObservationEvent`; the callback belongs to the in-memory handler event. `dispatchBeforeToolCall()` does not deliver webhooks.\n\n## Webhook Payloads\n\n`createWebhookPayloadBuilder()` selects `eventFields`, adds `hookId`\/`hookType`, then merges `webhook.body`. The body determines the final value of overlapping fields. Tool-result notification payloads use `redactResultForEvents()` to trim raw skill Work data; controls receive the full result. Work registration retains the full in-process result. `finalState` is available to local handlers; serialized payloads carry the event's data fields.\n\nWhen email is selected, the builder resolves `userEmail` from the final effective `userId`, replacing supplied email values. Email-only projections use the event ID. An explicit invalid ID, missing email or lookup error leaves email omitted.\n\nEmail queries share a per-dispatcher cache of up to 1,000 users for five minutes. Query timeouts belong to the database layer. The builder's optional fourth `{ signal }` argument lets a waiter cancel independently; cancellation returns `undefined` so the caller can stop delivery. Fetch and QStash use the enriched payload.\n\n## Delivery Errors\n\nDispatch awaits each handler or webhook. Ordinary errors are logged and dispatch continues. Webhooks with `fallback: 'none'` accumulate a `CriticalHookDeliveryError`, which is thrown after sibling hooks have run. QStash delivery defaults to a fetch fallback; use `fallback: 'none'` for QStash-signed endpoints.\n","use_cases":["Track agent step execution with logging","Mock tool calls for testing","Notify external systems after tool execution","Handle human intervention in agent workflows"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/lobehub\/lobehub\/blob\/54382b5c8e81544da454fa6d7b50f461a562c1ee\/.agents\/skills\/agent-runtime-hooks\/SKILL.md","source_commit":"54382b5c8e81544da454fa6d7b50f461a562c1ee","license":null,"version":null,"listing_approved_at":"2026-11-22","created_at":"2026-11-21T10:52:55.000000Z","updated_at":"2026-11-22T11:17:05.000000Z","seo_title":"Agent Runtime Hook Management","seo_description":"Register and manage hooks for agent lifecycle events, tool calls, and context compression with precise control over execution flow.","seo_keywords":["agent hook registration","tool call mocking","lifecycle event handling","webhook integration","context compression"]}}