Skip to content

[Improvement]: hooks: lifecycle hooks for agent session turns (beforeTurn / afterTurn / onTurnError) #7

@Arry8

Description

@Arry8

Summary

Add beforeTurn, afterTurn, and onTurnError lifecycle hooks to the agent session execution loop, allowing user scripts to guard, audit, or react to individual agent turns.

Problem

Agent turns (interactive message responses, local agent runs) execute with no external interception point. There is no config-driven way to: rate-limit turns per session, log turn duration and token usage to an external system, abort a turn based on content or context, or alert on repeated turn errors.

Acceptance criteria

  • beforeTurn hook fires before agent execution begins; returning { abort: true } skips the turn
  • afterTurn hook fires after successful turn completion with duration, token usage, and session context
  • onTurnError hook fires when a turn fails with the error string and session context
  • Hooks are configurable via openclaw.json under a shared hooks section with filter.agentId support
  • Hook failures are logged but never crash the agent turn
  • Unit tests cover: abort, pass-through, error isolation, agentId filter

Implementation plan

  1. Locate the agent turn entry point in src/agents/pi-embedded-runner.ts
  2. Add hook call sites before and after runEmbeddedPiAgent (or equivalent turn executor)
  3. Re-use runCronHooks / loadHookEntries from src/cron/hooks.ts with workflow: 'agent'
  4. Add AgentHooksConfig type to src/config/types.hooks.ts or extend shared hook types
  5. Wire config loading through agent deps
  6. Add unit tests

Files affected

  • src/cron/hooks.ts (reuse — no changes expected)
  • src/config/types.hooks.ts (add AgentHooksConfig)
  • src/config/zod-schema.ts (Zod schema)
  • src/agents/pi-embedded-runner.ts (wire hook call sites)
  • src/agents/pi-embedded-runner.hooks.test.ts (new — tests)

Additional notes

  • Natural extension of cron lifecycle hooks — same hook runner, same script contract, new ctx.workflow = 'agent'
  • ctx should include: sessionKey, agentId, model, turnIndex, meta bag
  • Token usage available post-turn from existing usage tracking (src/agents/usage.ts)

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions