{"slug": "aspect-oriented-programming-for-ai-agents-hookflows-as-an-event-bus", "title": "Aspect-Oriented Programming for AI Agents: Hookflows as an Event Bus", "summary": "Aspect-oriented programming (AOP) principles for AI agents by using \"hookflows\" as an event bus to handle cross-cutting concerns like notifications. Instead of having each agent explicitly call a Telegram notification function, the author created a governance hookflow that intercepts every agent dispatch, validates required metadata, and sends notifications as a deterministic side effect without consuming additional tokens. This approach solves common problems in multi-agent systems, including token cost compounding, unreliable agent discretion, and degraded composability.", "body_md": "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\ncall. The agents were already being validated by a governance hookflow. Why not piggyback the notification onto the validation step?\nOne tool call. Validation and notification. Zero additional tokens consumed by the agent.\nThen it hit me: I'd accidentally reinvented aspect-oriented programming — but for AI agents instead of Java classes.\nAspect-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.\nThe 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.\nNow apply that mental model to AI agents:\nThe 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.\nHere'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:\nname: Require task or write_agent originator notify\ndescription: >\nBlocks task/write_agent calls unless they contain a valid\noriginator_notify tag. On success, sends the parsed message\nto the originator via Telegram Bot API.\non:\nhooks:\ntypes: [preToolUse]\ntools: [task, write_agent]\nblocking: true\nenv:\nTOOL_NAME: ${{ event.tool.name }}\nTASK_PROMPT_JSON: ${{ toJSON(event.tool.args.prompt) }}\nWRITE_AGENT_MESSAGE_JSON: ${{ toJSON(event.tool.args.message) }}\nsteps:\n- name: Validate and send originator notification\nrun: |\n# Determine which tool arg contains the text\n$text = if ($env:TOOL_NAME -eq 'write_agent') {\n$env:WRITE_AGENT_MESSAGE_JSON | ConvertFrom-Json\n} else {\n$env:TASK_PROMPT_JSON | ConvertFrom-Json\n}\n# Parse the XML tag from tool arguments\n$pattern = '<originator_notify\\b(?<attrs>[^>]*)>(?<message>[\\s\\S]*?)</originator_notify>'\n$matches = [regex]::Matches($text, $pattern)\nif ($matches.Count -eq 0) {\nWrite-Error \"Missing <originator_notify> block\"\nexit 1 # BLOCKS the tool call\n}\n# Extract telegram_id via nested regex on attributes\n$attrs = $matches[0].Groups['attrs'].Value\n$idMatch = [regex]::Match($attrs, 'telegram_id=[\"\\x27](?<id>\\d+)[\"\\x27]')\n$telegramId = $idMatch.Groups['id'].Value\n$notifyMessage = $matches[0].Groups['message'].Value.Trim()\n# Side effect: send Telegram notification\n$botToken = $env:TELEGRAM_BOT_TOKEN\n$body = @{ chat_id = $telegramId; text = $notifyMessage } | ConvertTo-Json\nInvoke-RestMethod -Uri \"https://api.telegram.org/bot$botToken/sendMessage\" `\n-Method Post -ContentType 'application/json' -Body $body\nThe 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.\nThe naive approach is straightforward: after dispatching a sub-agent, call telegram_send_message\nexplicitly. But that approach has serious problems in production multi-agent systems:\nToken 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.\nAgent 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.\nComposability 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.\nThis pattern isn't limited to notifications. Here are enforcement-triggered side effects I'm now implementing across the platform:\nTask creation with auto-notification:\nA hookflow on add_task\nvalidates the task structure, then parses a notify\nblock to Telegram the assignee. The agent creating the task doesn't need to know who gets notified or how.\nFile edits with watch triggers:\nA hookflow on edit\nfor certain file paths validates the change, then queues a test run. The editing agent doesn't know it just triggered CI.\nContent creation with publish intent:\nA hookflow on create\nfor content files validates frontmatter, then notifies the content scheduler to slot the piece. The writing agent doesn't manage scheduling.\nEach hookflow is independent. Stack them. Compose them. The agent sees one tool call; the platform executes an entire workflow.\nThe broader software world has been exploring this territory:\nSpring 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.\nMicrosoft's own Agent Governance Toolkit provides application-level policy enforcement for autonomous agents via Python middleware.\nWhat'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.\nThe engine powering this is gh-hookflow — a Go-based workflow engine that intercepts GitHub Copilot CLI tool calls using preToolUse\nand postToolUse\ntriggers. Hookflows are defined in YAML (GitHub Actions syntax) and live in .github/hookflows/\n. 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.\nThe execution model:\ntask\n)preToolUse\nThis 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.\nIn a system running 53 agents with scheduled cron jobs, every unnecessary tool call matters. Here's the math:\ntelegram_send_message\ncall: ~200 tokens (call + response + reasoning)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.\nIf you're building with GitHub Copilot CLI extensions or any hook-based agent framework, here's the pattern:\nThe 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.\nAspect-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.\nThe 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.\nOne tool call. Governance satisfied. Side effects fired. Zero extra tokens. That's AOP for AI agents.", "url": "https://wpnews.pro/news/aspect-oriented-programming-for-ai-agents-hookflows-as-an-event-bus", "canonical_source": "https://dev.to/htekdev/aspect-oriented-programming-for-ai-agents-hookflows-as-an-event-bus-1if7", "published_at": "2026-05-20 13:55:26+00:00", "updated_at": "2026-05-20 14:05:13.487099+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "large-language-models", "developer-tools", "enterprise-software"], "entities": ["Telegram", "Aspect-Oriented Programming", "AI agents", "hookflow", "governance"], "alternates": {"html": "https://wpnews.pro/news/aspect-oriented-programming-for-ai-agents-hookflows-as-an-event-bus", "markdown": "https://wpnews.pro/news/aspect-oriented-programming-for-ai-agents-hookflows-as-an-event-bus.md", "text": "https://wpnews.pro/news/aspect-oriented-programming-for-ai-agents-hookflows-as-an-event-bus.txt", "jsonld": "https://wpnews.pro/news/aspect-oriented-programming-for-ai-agents-hookflows-as-an-event-bus.jsonld"}}