Skip to content

Compile semantic Agent event routes into native host hooks #97

Closed

Description

@ScriptedAlchemy

Summary

Extend Agent Bundle's existing host-neutral hook names and adapter-owned native
translation into filesystem event routes with a broader capability-aware
vocabulary. The compiler maps each semantic event onto the selected host's native event,
matcher, input decoder, synchronous deadline, output envelope, and delivery
capabilities.

Authors write application behavior once. Host adapters own translation.

Problem

Agent Bundle currently normalizes four hook events: sessionStart,
beforeTool, afterTool, and stop. TraceDecay-class applications also need
session completion, prompt submission, subagent start, file saved, workspace
open, compaction, shell completion, test lifecycle, idle, and host-specific
receipts.

Copying JSON hook documents or branching on host names inside handlers does
not scale. Hosts differ in event names, fields, matchers, synchronous response
formats, deadlines, trust prompts, and whether directed feedback is possible.

Filesystem convention

src/events/
  session/start.tsx
  session/end.tsx
  prompt/submit.tsx
  agent/start.tsx
  tool/before.tsx
  tool/after.tsx
  file/saved.tsx
  workspace/open.tsx
  compact/before.tsx
  stop.tsx

Each route may export static configuration and an RSC result component:

export const config = {
  tools: ['file.write'],
  delivery: ['immediate', 'deferred'],
} satisfies AgentEventRouteConfig;

export default async function AfterTool() {
  const { event, services } = await agent();
  const hint = await services.hints.forEvent(event);
  return hint ? <Agent.Context>{hint}</Agent.Context> : null;
}

Canonical event contract

Every event carries bounded metadata, explicit identity provenance, ordering,
an idempotency key, host contract revision, and an AbortSignal. Sensitive or
unbounded native payload fields are excluded unless an application explicitly
declares and validates them.

Host support is a state, not a Boolean:

type HostEventSupport =
  | { state: 'supported'; source: 'native' | 'receipt' }
  | { state: 'degraded'; reason: string }
  | { state: 'unavailable'; reason: string }
  | { state: 'prohibited'; reason: string };

The compiler refuses routes that require an unavailable capability unless the
route is explicitly restricted to supported targets.

Projection

The adapter registry owns:

  • native event names and matchers;
  • input decoding and canonical identity extraction;
  • synchronous deadline and payload budgets;
  • immediate output encoding (additionalContext, hook-specific output,
    denial, toast, or no response);
  • trust/activation requirements;
  • event fixtures and provenance.

Application routes never emit host-native JSON directly.

Failure and timing

  • Hook processes acknowledge within the host deadline.
  • An unavailable provider or backend produces a truthful empty/no-guidance
    result, not a fabricated success.
  • Slow work is handed to an explicit state/task backend and later delivery
    route; a short-lived hook does not silently continue unowned work.
  • Duplicate events are idempotent when a state provider is configured.
  • Native payloads are size bounded before user code runs.

Non-goals

  • Claiming event support from another host's similar payload.
  • Built-in hint or collision algorithms.
  • A mandatory event database.
  • Arbitrary raw native-hook documents as the primary authoring model.

Acceptance criteria

  • Unsupported and degraded mappings are visible in inspect output and fail
    required routes before packaging.
  • Checked-in host-native fixtures prove schema and adapter conformance for every
    supported mapping; they are not evidence that a commercial host dispatched
    the event.
  • The handler receives canonical context and never branches on host JSON.
  • Immediate output is rendered through the Agent Document projector.
  • The event process never holds open for deferred output. Before the delivery
    feature exists, a deferred-delivery request fails with a typed unsupported
    outcome rather than pretending work will continue.
  • One tool/after route compiles into two genuinely supported native formats;
    a separate file/saved fixture is reported unavailable on targets that do
    not expose that event.

Design references

Stack position

Full meta-framework stack

Flight-backed event-route execution

The intended default architecture is a thin native hook client calling the
shared Agent Bundle render runtime, not a generated shell process that loads the
whole application and renderer for every event.

native hook stdin/event
  -> host decoder
  -> AgentEventProps { canonical, native, provenance, signal }
  -> shared runtime render request
  -> event route Server Component
  -> Flight stream
  -> Agent Document decoder/projector
  -> native hook stdout/result

canonical contains the cross-host event identity used by application code.
native retains every field the host actually supplied after schema and size
validation, so an application can use host-specific evidence without receiving
fabricated fields. Both are immutable typed props and are also available through
the request context established around the Flight render.

The generated client selects a real transport per host:

  • use a native mcp_tool hook only where the host contract proves it can call
    the generated server with the required input, output, cancellation, and
    deadline semantics;
  • otherwise use compiler-owned local IPC to the host-managed MCP/runtime
    process;
  • use a standalone in-process wrapper only as an explicit degraded mode when
    shared runtime/state is not required.

The MCP/runtime process can amortize application startup and expose
process-lifetime providers or state across hook invocations. This is optional:
event routes that need only their props still work without durable storage, and
routes requiring shared/durable state declare that capability explicitly.

Additional acceptance criteria:

  • One real generated hook sends the complete validated native envelope as
    typed props through Flight and receives a valid native response before the
    host deadline.
  • Claude, Codex, and Cursor adapters prove their selected runtime transport or
    report it degraded/unavailable; similarly named events are not evidence.
  • Two consecutive events can observe the same process-lifetime provider when
    the shared runtime is active without reloading the application per hook.
  • Runtime absence, restart, timeout, cancellation, and artifact-epoch mismatch
    have fail-closed or explicitly configured fallback behavior.
  • The public hook protocol never receives raw Flight bytes or non-native output.

Activity

  1. added
    enhancement
    meta-framework
    runtime
    host-integration
    on Aug 31, 2026
  2. ScriptedAlchemy commented on Sep 1, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Documentation-coverage audit update (2026-09-01)

    Current Claude Code hook reference: https://code.claude.com/docs/en/hooks
    Current Codex hook reference: https://learn.chatgpt.com/docs/hooks
    Current Cursor hook reference: https://cursor.com/docs/agent/hooks

    The seven canonical families remain a sound v1, and the running Claude+Codex SubagentStart/SubagentStop correction lane should be credited. The documentation sweep adds this explicit route-family decision so newer events are not silently untracked.

    Promote to canonical route-family backlog

    These have clear application-level semantics and evidence on at least two pinned hosts, or are coordination primitives already in #97's domain:

    • session/end — Claude, Codex, Cursor
    • prompt/submit — Claude UserPromptSubmit, Codex UserPromptSubmit, Cursor beforeSubmitPrompt
    • tool/failure — Claude PostToolUseFailure, Cursor postToolUseFailure; Codex unavailable at the release-documented surface
    • compact/before — Claude/Codex PreCompact, Cursor preCompact
    • compact/after — Claude/Codex PostCompact; Cursor unavailable
    • permission/request — Claude/Codex PermissionRequest; Cursor must not be inferred from pre-tool permission
    • permission/denied — Claude PermissionDenied; other hosts unavailable until evidenced
    • file/change (the proposed file/saved) — Claude FileChanged, Cursor afterFileEdit; payload/matcher differences must stay visible
    • config/change — Claude ConfigChange; other hosts unavailable
    • task/create, task/complete, agent/idle — Claude TaskCreated, TaskCompleted, TeammateIdle; host-specific today but directly relevant to coordination applications
    • stop/failure — Claude StopFailure; other hosts unavailable

    Keep as selectors/native variants, not new route families

    • Cursor beforeShellExecution/afterShellExecution, beforeMCPExecution/afterMCPExecution, beforeReadFile, and afterFileEdit overlap canonical tool-before/tool-after plus a tool selector where payload/decision semantics can be preserved. Add dedicated families only if fixture evidence proves the generic tool route loses required information or control.

    Explicitly defer/unavailable in capability tables

    • Claude-only host/UI/protocol callbacks: Setup, UserPromptExpansion, PostToolBatch, MessageDisplay, InstructionsLoaded, CwdChanged, DirectoryAdded, PreModelSwitch, PostModelSwitch, Elicitation, ElicitationResult, WorktreeCreate, WorktreeRemove.
    • Claude Notification belongs to Add recipient-aware notices and capability-gated delivery #99 delivery-channel evidence rather than pretending it is an application event route.
    • Cursor afterAgentResponse, afterAgentThought, beforeTabFileRead, and afterTabFileEdit stay native/deferred until a canonical consumer is accepted.
    • Codex generated schemas currently include Interrupt, but the release behavior page warns that main schemas may be ahead of a release; mark it deferred until release docs and a pinned CLI revision agree.
    • Cloud/desktop availability differences are capability dimensions, not reasons to claim universal support.

    For every deferred item, add a dated unavailable/prohibited row with the native name and reason. This preserves G10's bounded v1 without leaving the expanded event lists untracked.

  3. ScriptedAlchemy commented on Sep 1, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Correction to the event-family support matrix: the landed v1 evidence incorrectly marked agent/start and agent/stop unavailable for both Codex 0.147.0 and Claude Code 2.1.250.

    Event family Cursor Claude Code 2.1.250 Codex 0.147.0
    agent/start subagentStart SubagentStart SubagentStart
    agent/stop subagentStop SubagentStop SubagentStop
    workspace/open workspaceOpen unavailable unavailable

    The correction, pinned wire-schema evidence, replay fixtures, output projection, and plugin packaging proof are in #194.

    Sources:

  4. ScriptedAlchemy commented on Sep 1, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Correction to the corrected matrix above: the workspace/open row listed Cursor as workspaceOpen (supported). That claim was removed by #221 (merged as 49281f1): Cursor's native workspaceOpen fires outside an agent session with no session/conversation fields and its response must return pluginPaths — an envelope the generated session-scoped wrapper vocabulary cannot express, and #189 forbids a supported claim without a native-envelope fixture.

    Event family Cursor Claude Code 2.1.250 Codex 0.147.0
    workspace/open unavailable (sessionless, returns pluginPaths) unavailable unavailable

    The workspace/open route family remains defined; it is unavailable on every pinned host until a real sessionless fixture replay admits it.

  5. ScriptedAlchemy commented on Sep 2, 2026

    @ScriptedAlchemy
    OwnerAuthor

    v1 complete — v2 families tracked separately

    Verified v1 delivery against #107 revision 3 and merged event-route PRs.

    v1 acceptance → landings

    Requirement Status Evidence
    Event descriptor + support-state schema ✅ #170
    Host family capability states ✅ #173
    Four-event parity through filesystem routes + context binding ✅ #182 example adoption
    Thin hook clients over warm runtime (local IPC, epoch-bound) ✅ #180
    agent/start + agent/stop with pinned Claude/Codex/Cursor evidence ✅ #194 matrix correction
    workspace/open honestly unavailable everywhere ✅ #221 — sessionless Cursor native hook cannot carry canonical identity
    One tool/after in two genuinely supported native formats + one family unavailable ✅ v1 matrix + #221
    Immediate output through Agent Document projector ✅ warm-runtime render path #180/#194
    Deferred delivery fails typed unsupported (pre-#99) ✅ compile/runtime contract

    v2 backlog moved to new tracker

    The documentation audit in this comment listed promoted route families (session/end, prompt/submit, tool/failure, compaction, permission, file change, config change, task coordination, stop/failure) plus defer/unavailable rows. That expansion is out of v1 scope per G10 and now tracked in:

    → #258 — Compile semantic event route v2 families into native host hooks

    Closing #97 as v1 semantic event routes complete; all further family increments follow #258's evidence bar.

  6. ScriptedAlchemy commented on Sep 2, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Closing: v1 event routes complete (#170/#173/#180/#182/#194/#221). v2 family backlog → #258.

  7. added a commit that references this issue on Sep 3, 2026
  8. ScriptedAlchemy commented on Sep 3, 2026

    @ScriptedAlchemy
    OwnerAuthor

    Closed-issue re-audit (G3) — VERIFIED, one docs gap fixed in #372 (squash ccb9cd18a).

    Re-checked on origin/main (af1c18551): every cited PR (#170/#173/#180/#182/#194/#221, and the post-closure #292 that put standalone/fallback hook execution on the Flight path) is on main; the admitted family vocabulary lives in packages/agent-bundle/src/routes/public.ts:11-32; per-host eventRoutes capability states plus the deferredNativeEvents rows are in src/adapters/capabilities/*.json; native decode (events/projection.ts:86), thin-client IPC (events/ipc.ts:869), and native encode (events/projection.ts:375) are single-sourced; AB4817/AB4823–AB4825 are documented. The v2 tracker #258 is closed with all five stages merged (#351/#357/#358/#359/#360). Tests run green here: lifecycle-replay-dev-server, generated-route-server (10), worktree-proximity-journeys (real generated hook wrappers over the artifact IPC), lifecycles.e2e, pnpm test:route-unit 35/35.

    Gap: docs/entry-conventions.md had no row for src/events/** — the event-route authoring convention was documented only indirectly through diagnostics. #372 adds the row (family path → canonical event, AgentEventRouteConfig, AgentEventRouteProps, capability-state gating, _ opt-out).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementhost-integrationmeta-frameworkruntime

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions