Skip to content

[Improvement]: hooks: lifecycle hooks for subagent spawning (beforeSpawn / afterSpawn / onSpawnError) #8

@Arry8

Description

@Arry8

Summary

Add beforeSpawn, afterSpawn, and onSpawnError lifecycle hooks to the subagent spawning path, allowing user scripts to control, audit, or react to subagent creation.

Problem

Subagents are spawned dynamically by agent tool calls with no external visibility or control. There is no config-driven way to: enforce spawning policies (max depth, allowed agents), audit which agents spawn which subagents, abort a spawn based on context, or alert when spawning fails repeatedly.

Acceptance criteria

  • beforeSpawn hook fires before a subagent is created; returning { abort: true } prevents the spawn
  • afterSpawn hook fires after a subagent completes (or is detached) with parent/child agent context and outcome
  • onSpawnError hook fires when spawn fails with error and parent context
  • Hooks are configurable via openclaw.json with filter.agentId (parent agent) support
  • Hook failures are logged but never crash the spawning agent
  • Unit tests cover: abort spawn, pass-through, error isolation

Implementation plan

  1. Locate subagent spawn entry in src/agents/subagent-spawn.ts
  2. Add beforeSpawn check before subagent process creation
  3. Add afterSpawn / onSpawnError calls in src/agents/subagent-registry-completion.ts (completion path)
  4. Re-use runCronHooks / loadHookEntries with workflow: 'subagent'
  5. Add SubagentHooksConfig type and Zod schema
  6. Add unit tests

Files affected

  • src/cron/hooks.ts (reuse — no changes expected)
  • src/config/types.hooks.ts (add SubagentHooksConfig)
  • src/config/zod-schema.ts (Zod schema)
  • src/agents/subagent-spawn.ts (wire beforeSpawn)
  • src/agents/subagent-registry-completion.ts (wire afterSpawn / onSpawnError)
  • src/agents/subagent-spawn.hooks.test.ts (new — tests)

Additional notes

  • ctx should include: parentAgentId, childAgentId, sessionKey, spawnDepth, meta bag
  • Works alongside existing depth-limit guardrails in src/agents/subagent-depth.ts — hooks are a user-space complement, not a replacement
  • Implement after agent-session turn hooks (issue #N) since spawn completion feeds into the same turn context

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