# on()

Register a handler for a supported hosted lifecycle event.

```js
pi.on("before_agent_start", async (event, ctx) => {
  // Observe or return the event-specific result.
});
```

## Signature

```js
pi.on(eventName, handler);
```

`eventName` must be one of the supported [hook events](/docs/reference/extensions/hooks). `handler` receives:

* `event`: a JSON-safe, event-specific projection;
* `ctx`: the bounded hosted context, currently `{ external }`.

Handlers may be synchronous or asynchronous. Every invocation is bounded by the 10-second hosted hook timeout.

## Composition

Handlers are loaded in extension declaration order and registered in module order. They execute sequentially. Composition depends on the event:

| Event family                  | Composition                                                              |
| ----------------------------- | ------------------------------------------------------------------------ |
| Prompt and context transforms | Each handler receives the result accumulated so far                      |
| Tool call                     | The first blocking result stops execution; input mutations are preserved |
| Tool result                   | Returned fields update the result seen by later handlers                 |
| Provider transforms           | Patches or payload replacements are applied sequentially                 |
| Observation events            | Every registered handler is awaited                                      |
| Before compaction             | The last non-empty override wins                                         |
| Before tree change            | The first non-empty override wins                                        |

For predictable behavior, keep one owner for each mutating event. Use multiple handlers primarily for independent observation until your application has explicit ordering tests.

## Invalid handlers

Manifest discovery fails when a registered handler is not a function. An unknown event produces a discovery warning and is not part of the supported hosted contract.
