# On Agent Message

Starts a workflow when an agent session receives a message, answers, calls a tool, or finishes a run.

- Tag: `on_agent_message`
- Input: none
- Output: `output`

One workflow run per accepted event, for every session in the workspace. A workflow that follows one
conversation reads `output.session_id` and stops early on anything else.

This is the egress half of the pair `agent_action` opens. Together they invert the old shape: the
agent runs in the backend and keeps running when no workflow is executing, and the workflow is only
what carries a message in and an answer out.

```
Telegram Message ──▶ agent_action(send_message)     the ingress
on_agent_message ──▶ format ──▶ Telegram Send       the egress
```

## Config

`event_kinds` chooses which events start a workflow. It accepts `user_message`, `assistant_message`,
`tool_call`, `tool_result`, `response_finished`, `compaction_started`, `compaction_finished`,
`run_finished`, and `run_failed`. An empty array accepts all nine.

The default is `["user_message", "assistant_message", "run_finished", "run_failed"]` — incoming
messages, answers, and both ways a run can end. Explicitly saved filters keep their selected kinds.
A run emits exactly one of `run_finished` and `run_failed`, so listening for both covers either end.

Tool traffic and the compaction lifecycle are available and off. A session doing real work emits a
lot of the first, and the second is maintenance an agent performs on itself rather than a moment to
act on; each event is a workflow run of its own.

Text and reasoning deltas are not offered at all. They describe a run in progress rather than
something it produced, and no configuration starts a workflow from one.

## Output

The event is `{session_id, agent_id, event}`.

`session_id` addresses the conversation, and is what `agent_action` takes to read the transcript or
send a reply into it. `agent_id` names the agent role that session instantiates; the session is the
addressable instance, and several sessions of one role each carry their own `session_id`.

`event` uses the loop's event shape. This trigger also admits incoming messages; that does not
change which intermediate events shared AI nodes publish. Branch on `event.kind`:

- `user_message` — `entry_id`, `text`, `author`, optional `sent_at`, optional `media`. An incoming
  message, not necessarily from a person. `author` is `{kind: "user"}`,
  `{kind: "system", origin?, hidden?}`, `{kind: "agent_session", session: "...", name: "..."}`, or
  `{kind: "delegation_response", session, name, outcome}`. A system message comes from something
  the user set up, such as a routine, a timer, a workflow or a coding agent; `origin` is the free
  text naming it (`"Routine · Morning review"`, `"Timer"`, `"Coding agent"`), and `hidden: true`
  means the chat does not draw it. A `delegation_response` is a helper session reporting that its
  work ended, with `outcome` `{status: "finished"}`, `{status: "stopped", by}` when someone stopped
  it (`by.kind` is `user`, `agent_session` with `session` and `name`, or `workflow`),
  `{status: "failed", reason}`, or `{status: "withdrawn", reason}` when it was archived or its
  agent retired before it answered (`reason` is `archived`, `archived_idle` or `retired`). Agents supplies
  the RFC 3339 send time when accepting the message; it survives queueing unchanged. `text`
  contains no generated timestamp or origin prefix. Other loop callers may omit `sent_at`. `media`
  is present only when the message carried attachments: an array whose items are
  `{"Object": <object descriptor>}` for something this workspace stores, or
  `{"External": {url, kind, content_type, filename}}` for a
  link. An attachment-only message has an empty `text`, so branch on `media` rather than assuming
  words.
- `assistant_message` — `entry_id`, `text`. A complete assistant segment, appended to the
  transcript. This is the one to forward.
- `tool_call` — `id`, `name`, `arguments`, optional `provider_item_id`. `id` pairs the call with
  its `tool_result`. `provider_item_id` is present only for OpenAI Responses calls and records that
  provider's item id; nothing pairs on it.
- `tool_result` — `id`, `entry_id`, `name`, `arguments`, `result`, `success`, optional
  `provider_item_id`.
- `response_finished` — `outcome`, `usage`. One model turn stopped generating; tool execution may
  follow.
- `compaction_started` — `entry_id`, `timestamp`, `trigger`. History is being summarised.
  `trigger` is `manual`, `automatic`, or `context_overflow_recovery`.
- `compaction_finished` — `entry_id`, `timestamp`, `outcome`. `outcome.status` is `completed` or
  `failed`. Completed carries `compaction.message`, `compaction.trigger`, `context_usage`
  (`previous_context_size`, `current_context_size`, `total_context_size`) and `tokens_spent`.
  Original history stays stored; history above the latest compaction marker is not replayed,
  entries below it are. Failed carries `error`, an object `{code, message}`: `code` names the error that
  stopped the summary as a dotted path and is the value to branch on; `message` is that error's own
  sentence, including the provider's own words when a provider refused; display it as given.
  Manual completion is published only after the summary and context commit;
  it emits no generation `run_finished`. Messages queued during maintenance start a normal run
  after maintenance releases its claim.
- `run_finished` — `outcome`, `usage`. The run reached an outcome and no further events follow for
  it.
- `run_failed` — `error`, an object `{code, message}`. The run failed and no further events follow
  for it. Every failure ends here: the model call or a tool failed, preparation failed, or the run
  was cancelled, timed out, crashed, or was lost to a server restart. `code` names the error that
  ended the run as a dotted path — for example `model_execution.quota_exhausted`,
  `not_configured`, `storage.not_found`, `tool_selection.invalid_config`, `cancelled`, `timed_out`,
  `panicked`, or `restarted` — and is the value to branch on. `message` is that error's own
  sentence; display it as given. Terminal exactly like `run_finished`, and a run carries one or the
  other, never both.

`outcome` is one of `answered`, `used_tools`, `truncated`, `awaiting_human`, `yielded`, `stopped`,
`budget_exhausted`. A failure is never an outcome. `usage` carries `used_tokens`,
`current_context_size`, and `total_context_size`.

## Delivery behavior

- The trigger carries events emitted while it is installed. It does not replay a session's history.
- A session that is running when the workflow is installed is picked up from its next event.
- Each matching event starts one run, in the order the session emitted them, including events
  emitted while earlier runs are still going.
- Running the workflow without a staged session event skips this trigger's outgoing branch.
  Other roots, such as manual message ingress in the same workflow, still run normally.
- Messages sent by the same workflow are eligible like any other message. The workflow's event
  filters and graph determine what it does when started.
- Incoming events arrive when a message reaches a turn boundary. A live event does not promise
  an in-flight pass is already durable. Successful terminal events follow transcript and usage
  persistence. Every failure writes a failed `run_status` transcript entry whose `detail` is the
  same `{code, message}` error before `run_failed`. For a failure inside the loop the code is the
  loop's own (for example `model_execution.quota_exhausted` or `model_execution.rate_limited`).
- If failure persistence itself fails, `run_failed` still ends the run and the session releases its
  claim. A terminal-triggered read cannot promise a saved error while storage is unavailable.
  A failure's `message` names what to act on: configuration details, affected memory namespaces,
  and a provider's own refusal (quota, rate limit, rejected credentials, context length) are shown,
  because they belong to the account that has to fix them. Internal causes read as
  `Internal server error: …`; their details and panic payloads stay out of the transcript.

## Failure behavior

- Installation fails while a table Agents needs has not been chosen, and surfaces as a workflow
  install diagnostic.
- A run Verdalia cannot queue is retried.
