Skip to content

[RFC] Agent Lifecycle Hooks #17707

Description

@hannsxpeter

RFC 001: Agent Lifecycle Hooks

Summary

Add lifecycle hooks that fire at key moments in an agent session, enabling memory systems, logging, and other extensions to react to session events.

Motivation

Currently, there's no way for an addon (like openclaw-persona) to:

  • Save context before compaction truncates it
  • Extract memories after each turn
  • Initialize state when a session starts
  • Clean up when a session ends

Memory systems need these hooks to implement automatic formation, consolidation, and persistence.

Proposed Hooks

onSessionStart

Fires when a new session begins.

interface SessionStartEvent {
  sessionKey: string;
  sessionKind: 'main' | 'cron' | 'spawn';
  parentSession?: string;
  timestamp: Date;
}

onPreCompaction

Fires before context compaction, allowing handlers to flush important context.

interface PreCompactionEvent {
  sessionKey: string;
  contextUsagePercent: number;
  messageCount: number;
  timestamp: Date;
}

onPostTurn

Fires after each assistant turn completes.

interface PostTurnEvent {
  sessionKey: string;
  userMessage: string;
  assistantMessage: string;
  toolCalls: ToolCall[];
  timestamp: Date;
}

onSessionEnd

Fires when a session terminates.

interface SessionEndEvent {
  sessionKey: string;
  reason: 'timeout' | 'explicit' | 'error';
  durationMs: number;
  timestamp: Date;
}

Configuration

hooks:
  onSessionStart:
    - exec: "persona hook session-start"
  onPreCompaction:
    - exec: "persona hook pre-compaction"
  onPostTurn:
    - exec: "persona hook post-turn"
    - webhook: "https://example.com/turn"

Implementation Notes

  • Hooks run async, don't block the main flow
  • Timeout per hook (default 5s)
  • Failures logged but don't crash session
  • Event data passed as JSON to stdin or POST body

Alternatives Considered

  • Polling-based: Would miss events, higher latency
  • In-process plugins: More complex, security concerns
  • File watchers: Race conditions, platform-dependent

Open Questions

  1. Should hooks be sync or async by default?
  2. Should onPostTurn include full message history or just the turn?
  3. Priority/ordering for multiple handlers?

Metadata

Metadata

Assignees

No one assigned

    Labels

    staleMarked as stale due to inactivity

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions