실제 제품을 적절한 조작 환경에서 실행해 변경 사항을 검증하고, 사용자가 확인할 수 있는 증거를 모아 인수 보고서로 게시합니다. 기존 검증 계획을 확인하거나 점검 항목을 만들고, `lh` CLI로 결과를 게시할 수 있습니다.
- 변경된 제품 동작을 실제로 확인하기
- 스크린샷 등 검증 증거 수집하기
- 검증 계획과 보고서 작성하기
에이전트 실행 단계, 도구 호출, 사람의 승인, 컨텍스트 압축, 하위 에이전트 호출에 훅을 등록하는 방법을 안내합니다. 이벤트를 관찰하고 로컬 도구 결과를 모의하거나 설정에 따라 웹훅으로 도구 호출을 허용 또는 거부할 수 있습니다.
Use for agent lifecycle hooks, tool mocks, intervention, sub-agent calls and context compression.
실행 점수 미검증
설치 방법 보기이 가이드는 에이전트 실행 수명 주기의 여러 단계에 훅을 등록하고 이벤트를 처리하는 방법을 설명합니다. 단계의 시작과 완료, 도구 호출과 오류, 사람의 승인, 컨텍스트 압축, 하위 에이전트 호출, 최종 실행 상태를 관찰할 수 있습니다. 로컬 핸들러로 도구 결과를 모의할 수 있으며, 웹훅으로 이벤트를 알리거나 결정 기능을 설정해 도구 호출을 허용하거나 거부할 수 있습니다. 이벤트에 포함되는 실행 ID, 도구 정보, 결과와 웹훅 페이로드 및 전송 오류 동작도 다룹니다.
에이전트 실행을 관찰하거나 운영 중 개입하는 기능을 구현할 때 활용할 수 있습니다. 테스트를 위해 도구 결과를 바꾸거나 승인과 하위 에이전트가 포함된 흐름을 추적할 때도 도움이 됩니다.
웹훅을 설정하고 동작시키려면 대상 URL이 필요합니다. 헤더에 환경 변수를 사용할 경우 허용 목록을 지정해야 하며, 비밀 값은 설정 저장 시가 아니라 전송 시점에 해석됩니다. 웹훅만으로 등록한 훅은 프로세스를 다시 시작한 뒤 함수 핸들러를 복원할 수 없습니다.
이 소개문은 공개된 SKILL.md를 바탕으로 AI(OpenAI Codex)가 작성했습니다. 정확한 사양은 아래 원문을 확인하세요.
AI가 SKILL.md의 내용에서 주의가 필요한 작업과 도입 전제를 확인했습니다. 점수는 실제로 실행한 결과(실행 검증)만으로 매깁니다.
점수에는 넣지 않았습니다. 2026년 10월 26일 기준으로 AI(OpenAI Codex)가 판정했습니다. 참고용이므로 설치 전에 원문도 확인해 주세요.
설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.
Register lifecycle hooks through execAgent({ hooks }). HookDispatcher stores them per operation and dispatches them in registration order.
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 (optional result control)
│ │ └─ 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 creation/start returns
│ │ └─ onCallAgentError ── Sub-agent failed
│ │
│ └─ afterStep ──────────── After step completes
│
├─ (next step...)
│
├─ onComplete ───────────── Operation reaches terminal state
└─ onError ──────────────── Error during execution
| File | Role |
|---|---|
packages/agent-runtime/src/types/hooks.ts | Event types and required/optional fields |
apps/server/src/services/agentRuntime/hooks/types.ts | Registration and webhook types |
apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts | Registration, dispatch, local mocks, HTTP/QStash delivery |
apps/server/src/services/agentRuntime/hooks/webhookPayload.ts | Event projection and email enrichment |
apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.ts | Shared tool-event context builder |
apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts | Tool notifications and execution results |
apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts | Tool, compression and human-intervention execution |
apps/server/src/services/agentRuntime/AgentRuntimeService/ (executeStep/, intervention.ts) | Step events and human-intervention continuation |
apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts | Terminal events |
apps/server/src/services/aiAgent/subAgentRuns.ts | Sub-agent events |
const hooks: AgentHook[] = [
{
id: 'observe-step',
type: 'afterStep',
handler: async (event) => {
console.log(event.operationId, event.stepIndex);
},
},
];
await aiAgentService.execAgent({ agentId, prompt, hooks });
Completion cleans up registrations through hookDispatcher.unregister(operationId).
Webhook-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.
const hook: AgentHook = {
id: 'tool-notification',
type: 'afterToolCall',
matcher: '^fs/readFile$',
webhook: {
url: 'https://example.com/hooks',
delivery: 'fetch',
timeout: 5, // seconds; default 30
headers: { Authorization: 'Bearer ${HOOK_TOKEN}' },
allowedEnvVars: ['HOOK_TOKEN'],
},
};
matcher is a regex against ${identifier}/${apiName}, supported only on tool events. Omitted, empty, or * matches all tools.allowedEnvVars; persist templates, never resolved secrets.beforeToolCall with responseHandling: 'toolCall' awaits an optional HTTP decision before tool execution. Return HTTP 2xx JSON with { "decision": "allow" } or { "decision": "deny", "reason": "禁止执行该操作" } 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.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 for deferred completions and runtime boundaries.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.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.decision and a deny's optional string reason are consumed; updatedInput/additionalContext do not change tool arguments or conversation context.packages/types/src/agentHook.ts; response parsing: packages/types/src/agentHookResponse.ts; HTTP delivery: apps/server/src/services/agentRuntime/hooks/httpWebhook.ts.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.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.onError.toolResultControl pending/allowed/blocked metadata or hide raw output through history projections.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.type: 'blocked' is not a hook verdict.| Event | Timing and payload |
|---|---|
beforeStep | Before a step; AgentHookEvent |
afterStep | After a step; content, tool calls/results and usage totals |
onComplete | Terminal state; reason such as done, error, interrupted, max_steps or cost_limit |
onError | Operation error; errorMessage, errorDetail and available error metadata |
beforeToolCall | Before tool execution; shared tool context and local mock() callback |
afterToolCall | After tool execution; structured result and mocked |
onToolCallError | Tool execution throws; shared tool context and error |
beforeHumanIntervention | Before approval; pendingTools, operationId, stepIndex |
afterHumanIntervention | Approval decision and continuation; action, optional toolCallId and rejectionReason |
onStopByHumanIntervention | Human rejection stops the run; optional toolCallId and rejectionReason |
beforeCompact | Before compression; messageCount, tokenCount, stepIndex |
afterCompact | After compression; groupId, messagesBefore, messagesAfter, summary |
onCompactError | Compression error; error, tokenCount, stepIndex |
beforeCallAgent | Before sub-agent creation; agentId, instruction |
afterCallAgent | Creation/start returns; agentId, subOperationId, success, optional threadId |
onCallAgentError | Sub-agent call fails; agentId, error |
CallAgent 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.
Use buildToolCallHookContext() for the three tool events.
toolCallId, assistantMessageId, identifier, apiName, effective args, callIndex, stepIndex, operationId and executor.userId uses runtime.userId ?? origin.userId.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.afterToolCall.result carries content, success, optional executionTime and error/state data such as state.type: 'blocked'. mocked marks results supplied by a local hook.Sandbox and MCP tools use the same event path. Filter with identifier, apiName or toolSource.
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.
event.mock({ content: '{"items":[]}', success: true });
Tool observation payloads use BeforeToolCallObservationEvent; the callback belongs to the in-memory handler event. dispatchBeforeToolCall() does not deliver webhooks.
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.
When 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.
Email 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.
Dispatch 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.
아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.
로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.
아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.
실제 제품을 적절한 조작 환경에서 실행해 변경 사항을 검증하고, 사용자가 확인할 수 있는 증거를 모아 인수 보고서로 게시합니다. 기존 검증 계획을 확인하거나 점검 항목을 만들고, `lh` CLI로 결과를 게시할 수 있습니다.
LobeHub에 AI 모델 제공자를 추가하는 과정을 안내합니다. 런타임 연동, 모델 정보와 설정, 브랜드 표시, 문서화 및 인수 확인을 다루며, 기존 제공자에 모델만 추가하는 경우와 새 연동이 필요한 경우를 구분합니다.
서버 환경 변수로 사용자 설정의 기본값을 지정하도록 구현하는 절차를 안내합니다. 변수 검증, 서버 설정 구성, 사용자 저장소 반영부터 예시 환경 파일과 셀프 호스팅 문서 갱신까지 다룹니다.
에이전트의 이벤트 기반 백그라운드 작업을 설계하고 구현하도록 돕습니다. 소스, 시그널, 액션, 정책의 역할을 나누고 비동기 처리, 중복 실행 방지, 완료 기록과 관측 기능을 다룹니다.
실제 데스크톱 채팅 앱에서 봇 채널의 인수 테스트를 진행합니다. Discord, Slack, Telegram, WeChat, Lark, QQ에서 메시지를 보내고 응답을 기다린 뒤 결과 화면을 캡처합니다. iMessage는 BlueBubbles 브리지를 사용합니다.
작업 ID로 에이전트 실행 기록을 살펴 실패한 도구 호출과 인수·결과, 사용 가능한 도구, 실행 문맥과 대규모 언어 모델 입력을 확인합니다. 문맥 지도와 다른 모델로 기록을 재생해 비교하는 기능도 제공합니다.