Skip to content
← Back to Articles

Aspect-Oriented Programming for AI Agents: Hookflows as an Event Bus

· 6 min read
GitHub Copilot Copilot CLI Agentic Development Multi-Agent Systems Deep Dive
Aspect-Oriented Programming for AI Agents: Hookflows as an Event Bus

The Pattern That Made Me Say “That’s Exactly What AOP Is”

I was debugging a notification problem in my 53-agent home assistant when I stumbled onto something unexpectedly powerful. I needed every agent dispatch to notify me via Telegram — but I didn’t want to burn tokens on a separate telegram_send_message call. The agents were already being validated by a governance hookflow. Why not piggyback the notification onto the validation step?

One tool call. Validation and notification. Zero additional tokens consumed by the agent.

Then it hit me: I’d accidentally reinvented aspect-oriented programming — but for AI agents instead of Java classes.

What Is AOP, and Why Does It Matter Here?

Aspect-oriented programming emerged in the late 1990s to solve a specific problem: cross-cutting concerns. Logging, security checks, transaction management — these behaviors cut across every module in your application, but they don’t belong in any single module’s core logic.

The AOP solution: define these concerns once, then weave them into your code at specific join points (method calls, property access) using advice (before, after, around). The original code never knows it’s being augmented.

Now apply that mental model to AI agents:

AOP ConceptAgent Equivalent
Join pointTool call (e.g., task, edit, create)
PointcutHook trigger rule (which tools, which args)
AdviceHook step logic (validate, notify, log)
AspectA hookflow YAML definition
WeavingThe hook engine intercepting tool calls at runtime

The agent doesn’t know. It just calls a tool. The governance layer intercepts, validates, and fires side effects. This is textbook AOP — applied to a fundamentally new domain.

The Real Implementation: Enforcement-Triggered Side Effects

Here’s the actual hookflow running in my platform. It requires every agent dispatch to include a notification tag, validates it, and then sends the notification as a side effect:

name: Require task or write_agent originator notify
description: >
  Blocks task/write_agent calls unless they contain a valid
  originator_notify tag. On success, sends the parsed message
  to the originator via Telegram Bot API.
on:
  hooks:
    types: [preToolUse]
    tools: [task, write_agent]
blocking: true
env:
  TOOL_NAME: ${{ event.tool.name }}
  TASK_PROMPT_JSON: ${{ toJSON(event.tool.args.prompt) }}
  WRITE_AGENT_MESSAGE_JSON: ${{ toJSON(event.tool.args.message) }}
steps:
  - name: Validate and send originator notification
    run: |
      # Determine which tool arg contains the text
      $text = if ($env:TOOL_NAME -eq 'write_agent') {
        $env:WRITE_AGENT_MESSAGE_JSON | ConvertFrom-Json
      } else {
        $env:TASK_PROMPT_JSON | ConvertFrom-Json
      }

      # Parse the XML tag from tool arguments
      $pattern = '<originator_notify\b(?<attrs>[^>]*)>(?<message>[\s\S]*?)</originator_notify>'
      $matches = [regex]::Matches($text, $pattern)

      if ($matches.Count -eq 0) {
        Write-Error "Missing <originator_notify> block"
        exit 1  # BLOCKS the tool call
      }

      # Extract telegram_id via nested regex on attributes
      $attrs = $matches[0].Groups['attrs'].Value
      $idMatch = [regex]::Match($attrs, 'telegram_id=["\x27](?<id>\d+)["\x27]')
      $telegramId = $idMatch.Groups['id'].Value

      $notifyMessage = $matches[0].Groups['message'].Value.Trim()

      # Side effect: send Telegram notification
      $botToken = $env:TELEGRAM_BOT_TOKEN
      $body = @{ chat_id = $telegramId; text = $notifyMessage } | ConvertTo-Json
      Invoke-RestMethod -Uri "https://api.telegram.org/bot$botToken/sendMessage" `
        -Method Post -ContentType 'application/json' -Body $body

The agent’s perspective? It’s just including metadata in its prompt — a governance requirement. It has no idea that including that tag triggers a Telegram message. The hookflow handles both enforcement (blocking if the tag is missing) and a side effect (sending the notification) in a single interception.

Why This Is Better Than Explicit Tool Calls

The naive approach is straightforward: after dispatching a sub-agent, call telegram_send_message explicitly. But that approach has serious problems in production multi-agent systems:

Token cost compounds. Every tool call consumes tokens — the call itself, the response, the reasoning about the response. In a system dispatching dozens of agents per hour, those extra calls add up fast.

Agent discretion is unreliable. Agents skip steps. They forget. They decide a notification “isn’t necessary this time.” When notifications are a side effect of governance, they happen deterministically. Every single time. No exceptions.

Composability degrades. When you want to add a second cross-cutting concern — say, audit logging — you’d need to update every agent’s instructions. With hookflows, you stack another aspect. The agents remain untouched.

The Composability Advantage

This pattern isn’t limited to notifications. Here are enforcement-triggered side effects I’m now implementing across the platform:

Task creation with auto-notification: A hookflow on add_task validates the task structure, then parses a notify block to Telegram the assignee. The agent creating the task doesn’t need to know who gets notified or how.

File edits with watch triggers: A hookflow on edit for certain file paths validates the change, then queues a test run. The editing agent doesn’t know it just triggered CI.

Content creation with publish intent: A hookflow on create for content files validates frontmatter, then notifies the content scheduler to slot the piece. The writing agent doesn’t manage scheduling.

Each hookflow is independent. Stack them. Compose them. The agent sees one tool call; the platform executes an entire workflow.

Prior Art: I’m Not the First, But the Domain Is New

The broader software world has been exploring this territory:

Spring AI’s Advisor system draws an explicit parallel to Spring AOP — intercepting and enhancing AI calls with logging, memory injection, and retrieval augmentation. CrewAI’s LLM Call Hooks expose before/after interception points for inspection, approval gates, and response transformation. Victor Dibia’s analysis of agent middleware frames middleware as a control and observability mechanism for agent execution loops.

Microsoft’s own Agent Governance Toolkit provides application-level policy enforcement for autonomous agents via Python middleware.

What’s different about the hookflow approach is the enforcement-plus-side-effect fusion. Most prior art treats governance (blocking/allowing) and side effects (notifications/logging) as separate middleware layers. The hookflow pattern combines them: the same rule that enforces compliance also triggers downstream actions. One interception, multiple outcomes.

The Technical Architecture

The engine powering this is gh-hookflow — a Go-based workflow engine that intercepts GitHub Copilot CLI tool calls using preToolUse and postToolUse triggers. Hookflows are defined in YAML (GitHub Actions syntax) and live in .github/hookflows/. I’ve written about the governance layer before in Stop Trusting AI Agents with Git and the broader three-layer architecture that makes autonomous agents production-ready.

The execution model:

  1. Agent calls a tool (e.g., task)
  2. Hook engine intercepts via preToolUse
  3. Hookflow steps execute: parse args, validate, fire side effects
  4. If validation fails → tool call is blocked (agent sees denial message)
  5. If validation passes → tool call proceeds, side effects already fired

This is deterministic. It runs on every tool call matching the trigger. The agent cannot bypass it — unlike instructions, which are suggestions the model can ignore.

Why Token Efficiency Matters at Scale

In a system running 53 agents with scheduled cron jobs, every unnecessary tool call matters. Here’s the math:

But the bigger win isn’t cost. It’s reliability. Those 80-120 notifications now happen with 100% certainty. Not “usually” or “when the agent remembers.” Every time.

Building Your Own Enforcement-Triggered Side Effects

If you’re building with GitHub Copilot CLI extensions or any hook-based agent framework, here’s the pattern:

  1. Identify a cross-cutting concern — something that should happen on every tool call of a certain type
  2. Require metadata — make the agent include structured data (XML, JSON, YAML) in its tool arguments
  3. Validate the metadata — block the call if it’s missing or malformed
  4. Fire the side effect — parse the metadata and trigger your downstream action
  5. The agent never needs to know — it thinks it’s satisfying a governance requirement

The key insight: by framing side effects as governance requirements, you get both compliance enforcement AND automated workflows from a single hook. The agent is incentivized to include the metadata (because the call fails without it), and the platform gets free automation.

The Bottom Line

Aspect-oriented programming solved cross-cutting concerns in enterprise Java twenty years ago. The same pattern — interception at defined join points, transparent augmentation, composition of independent aspects — solves cross-cutting concerns in autonomous AI agent systems today.

The difference is that agents can’t be refactored to call the right methods. They’re non-deterministic. They forget. They improvise. That’s exactly why enforcement-triggered side effects are more powerful than explicit tool calls: you remove agent discretion from the equation entirely.

One tool call. Governance satisfied. Side effects fired. Zero extra tokens. That’s AOP for AI agents.


← All Articles