# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.16.0] - 2026-11-26

Alloy 0.16 brings major-lab wire parity (multimodal PDFs/documents, image URLs,
dynamic `:api_key` callbacks, provider caching, Gemini native tools, portable
`:reasoning`), uniform v1 streaming events, cooperative cancellation
(`Alloy.Cancel`), mid-run `:steering` and completion `:follow_up` controls,
`Alloy.Tool.Executor.run_tool/3`, and optional `Alloy.ModelCatalog` capability
and pricing metadata — with zero new mandatory runtime dependencies. See
[Upgrading to 0.16](docs/upgrading-to-0.16.md).

### Breaking Changes

- **New `:cancelled` status, error kind, and atom `result.error`:** `Alloy.Agent.State.status()`, `Alloy.Result.status`, and `Alloy.Provider.Error.kind()` add `:cancelled`. Cooperatively cancelled runs return `{:error, %Alloy.Result{status: :cancelled, error: :cancelled}}` (with any `%Alloy.Provider.Error{kind: :cancelled}` in `result.metadata.run.provider_error`), so `result.error` is no longer guaranteed to be a `String.t()` on `{:error, result}`. Callers with exhaustive `case` matches on run/turn status or provider error kind must handle `:cancelled`, and persistent `Alloy.Provider.Codex` (`persist_session: true`) callers should rotate `:session_generation` after `:cancelled`.
- **Fail-closed `Alloy.Middleware.run_before_tool_call/2`:** Direct callers of `Middleware.run_before_tool_call/2` must handle the new `:cancelled` return value when `state.config.cancel_token` is cancelled (explicit `{:block, reason}` verdicts remain preserved).
- **Global provider config validation for `:api_key`, `:origin_key`, and `:reasoning`:** `Alloy.Agent.Config` now validates auth and `:reasoning` options on **every** primary and `:fallback_providers` config (including custom providers). Any provider configured with a 0-arity `:api_key` function or `auth_scheme: :bearer` requires a non-empty string `:origin_key`, any `:reasoning` key in provider config must conform to Alloy's portable format (`nil | :off | :low | :medium | :high | :xhigh | %{effort: ..., display: ...}`), and built-in HTTP providers validate both static string and callback `:api_key` values as printable ASCII without CR/LF characters.
- **Injected `:alloy_cancel_token` and `:reasoning` provider config keys:** When `:cancel_token` is set, Alloy injects `:alloy_cancel_token` into `provider_config` alongside `:alloy_request_deadline`, and when top-level `:reasoning` is set, Alloy injects normalized `:reasoning`; custom providers using strict option validators should tolerate unknown `:alloy_*` keys and `:reasoning`.
- **Anthropic `reasoning: :off`:** Explicitly sends `%{"thinking" => %{"type" => "disabled"}}` (`reasoning: nil` continues to omit `"thinking"`).
- **Stricter `OpenAIStream` and `OpenAI` streaming tool-call validation:** `Alloy.Provider.OpenAIStream` (Chat Completions streaming) rejects negative/malformed tool-call indices and conflicting tool identities (`id`/`name`) with non-retryable `:protocol_error`, and invalid/non-object tool argument JSON with retryable `:malformed_reply`; `Alloy.Provider.OpenAI` (OpenAI/xAI Responses streaming) rejects conflicting tool-call headers and contradictory completed arguments with `:malformed_reply` (retryable before output is emitted; retries/fallbacks remain suppressed once output has been emitted to caller callbacks).
- **`Alloy.Events.build_correlation_id/1`:** Empty strings (`""`) and invalid UTF-8 values in `context[:request_id]` / `context[:correlation_id]` now fall back to a generated correlation ID so downstream tool events and telemetry always carry valid non-empty UTF-8 correlation IDs.

### Added

- **Multimodal & major-lab wire parity:**
  - Portable `image` (`url:` or `data:`) and `document` (`data:`, `uri:`, or origin-scoped `file_id:`) content blocks across `Anthropic`, `OpenAI`, `XAI`, and `Gemini` (plus `image` URLs on `OpenAICompat`), with origin-scoped `file_id` and Gemini File API URI omission in `Alloy.Message.normalize_for/3` on cross-origin switches.
  - Dynamic 0-arity `:api_key` callbacks (resolved per HTTP attempt within the request deadline and cancellation token, rejecting non-ASCII/CR/LF keys, never invoked during origin hashing, and redacting auth error diagnostics) plus `auth_scheme: :bearer` support.
  - First-class provider caching and native tools: Anthropic `:cache` TTL (`"5m"` / `"1h"`) and `:web_search` shorthand; OpenAI/xAI `:prompt_cache_key` and `:prompt_cache_retention`; Gemini `:cached_content`, `:google_search`, `:url_context`, and `:code_execution` (all stripped automatically on compaction summary requests).
- **Portable `:reasoning` option:** Unified `:reasoning` config (`nil | :off | :low | :medium | :high | :xhigh | %{effort: ..., display: ...}`) across all 6 built-in providers (updatable via `Alloy.Agent.State.prepare/2`, forwarded to fallback providers, stripped on compaction summaries, and overridable by explicit `extra_body` / `generation_config`).
- **Uniform v1 streaming events (`docs/events.md`):**
  - `:thinking_delta` across Anthropic, OpenAI/xAI Responses, Gemini, and OpenAICompat/OpenAIStream.
  - `:tool_call_delta` (`%{id:, index:, name:, arguments_delta:}`) across streaming providers.
  - `:turn_start` (`%{turn:}`) and `:turn_end` (`%{turn:, status:, stop_reason:, usage:}`) across both `Alloy.run/2` and `Alloy.stream/3`.
  - `:tool_update` (`%{id:, name:, chunk:, start_event_seq:}`) marshalled back to the caller process via per-call `Process.alias/0` with bounded in-flight backpressure, wired into `Alloy.Tool.Core.Bash` alongside optional `:bash_on_output`.
- **Cooperative cancellation (`Alloy.Cancel`):**
  - Lock-free `:atomics`-backed cancellation tokens (`new/0`, `cancel/1`, `cancelled?/1`, `combine/2`, `valid?/1`, zero processes, zero ETS tables, zero polling overhead when `nil`) propagated through `Turn`, `Retry`, `OwnedWorker`, `HTTP`, `SSE`, `CodexRunner`/`Codex`, `Compactor`, `Middleware`, and `Executor` — including `timeout_ms: :infinity` runs, OS process-group teardown, verbatim compaction history preservation, retry/fallback suppression, and valid repaired transcripts (`Alloy.Transcript.validate/1 == :ok`).
- **Mid-run `:steering` & completion `:follow_up` callbacks:**
  - `:steering` polled between completed tool batches to redirect active runs, skip remaining unstarted batches with synthetic error `tool_result` blocks, and bypass `:stop_after_tool`.
  - `:follow_up` polled before normal non-refusal `:end_turn` completion once `:until_tool` is satisfied, bounded by `:max_turns`, `:timeout_ms`, and `:cancel_token`, firing `:after_completion` once on final completion.
  - Strict `[%Alloy.Message{}]` and JSON-compatibility validation plus `:redact` exception/throw/exit sanitization for both callbacks.
- **Reusable single-tool execution (`Alloy.Tool.Executor.run_tool/3`) & native `:parent_call_id`:**
  - Shared single-tool execution entrypoint with full middleware, validation, supervised timeout/deadline clamping (`state.run_deadline`), composed cancellation (`Alloy.Cancel`), truncation, caller-process `:tool_update` marshalling, and native `:parent_call_id` tagging across `:tool_start`, `:tool_update`, `:tool_end`, tool telemetry, and metadata.
  - Updated `examples/minimal_host/code_mode.exs` and `docs/recipes/code-mode.md` to route single nested calls through `Executor.run_tool/3`, clamp outer deadlines, and finalize child calls gracefully on cancellation/timeout.
- **Optional `Alloy.ModelCatalog` metadata & `LLMDB` recipe:**
  - Added optional `c:Alloy.ModelCatalog.max_output_tokens/1`, `c:Alloy.ModelCatalog.capabilities/1`, and `c:Alloy.ModelCatalog.pricing/1` callbacks plus `Alloy.ModelCatalog.info/1,2` (fully backwards-compatible with minimal v0.14 catalogs exporting only `context_window/1`).
  - Implemented all three optional callbacks in `Alloy.ModelMetadata` (including `gpt-5.2-pro`/`gpt-5.4-pro` `structured_output?: false`, `grok-4.20-multi-agent` `tools?: false`, non-reasoning Grok distinction, and `nil` optional metadata for retired models).
  - Added provider-scoped `LLMDB` adapter recipe (`docs/recipes/llm-db-catalog.md`) and `docs/upgrading-to-0.16.md`.

## [0.14.0] - 2026-11-24

Alloy 0.14 hardens run deadlines, worker supervision, provider wire parsing,
and tool/config validation, splits non-retryable `:protocol_error` from
retryable `:malformed_reply`, and adds first-class portable `:output_schema`
structured outputs. See [Upgrading to 0.14](docs/upgrading-to-0.14.md).

### Breaking Changes

- **Run deadline enforcement (`:timeout_ms`, or `:infinity` to disable):** `Alloy.Agent.Turn`, `Alloy.Provider.Retry`, built-in HTTP/SSE and Codex runners, and `Alloy.Tool.Executor` now enforce `:timeout_ms` (default `120_000` ms) across stalled or trickling HTTP/SSE requests, provider retries, sequential tool batches, in-flight and queued tool tasks, and turn boundaries without renewing expired budgets. Previously, actively streaming requests and long tool batches could run past `:timeout_ms`.
  - **Retry & timeout headroom:** Retries and fallback attempts stop 5 seconds before `:timeout_ms` (so `timeout_ms <= 5_000` skips both retries and fallback providers). Non-streaming requests reserve that 5-second headroom in `receive_timeout` once `:timeout_ms > 8_000` (with a 3-second floor clamped to remaining budget), while streaming requests receive the full remaining run budget up to `:timeout_ms` across both HTTP/1.1 and HTTP/2. Cancellation teardown adds a brief grace window (`~1.5s` for HTTP/SSE worker cleanup, up to `5s` for Codex subprocess cleanup), so hosts wrapping runs in `Task.await/2` should add buffer above `:timeout_ms`.
  - **Termination precedence:** Already-completed `:end_turn` answers and successful `stop_after_tool` outcomes are returned rather than discarded; otherwise an expired deadline fails the run with `:timeout` ahead of `:max_turns`.
  - **Unstarted tool batches:** Tool calls in a batch that has not started before `:timeout_ms` expires (including middleware-blocked calls in that batch) receive matching error `tool_result` blocks in the transcript (preserving any `:before_tool_call` block reason) without emitting `:tool_start`/`:tool_end`, running `:after_tool_call`, or appearing in `result.tool_calls`. Calls already queued inside an in-progress parallel batch whose `:tool_start` was already emitted still settle through `:tool_end`, `:after_tool_call`, and `result.tool_calls` with a run-deadline timeout error so start/end pairs stay balanced.
  - **Migration:** Callers with multi-turn or streaming runs exceeding 2 minutes (or single non-streaming generations exceeding `timeout_ms - 5_000`) can raise `:timeout_ms` or pass `timeout_ms: :infinity` to disable the run-level deadline (per-tool `:tool_timeout`, Codex's own per-invocation `:timeout_ms` default of `120_000` ms, and a 60-second ceiling on unbounded retries — capping jitter at 60 s and aborting if `Retry-After` exceeds 60 s — still apply; HTTP requests default to `receive_timeout: :infinity`, so pass `req_options: [receive_timeout: ...]` if you still want a per-request idle/socket timeout). When `:timeout_ms` is finite, `:tool_timeout` (default `120_000` ms) is bounded by the remaining `:timeout_ms` run budget, and a tighter caller-provided `req_options[:receive_timeout]` is preserved.
- **Supervised worker execution for deadline-bounded HTTP/SSE requests:** When `:timeout_ms` is finite (the default), built-in HTTP/SSE providers execute `Req` inside a linked worker under `Alloy.TaskSupervisor` (so the `:alloy` application must be started). `Logger.metadata/0`, OpenTelemetry context (`:"$__current_otel_ctx"`), and `$callers` are propagated to the worker, while other custom process-dictionary entries are not; custom `Req` test plugs that call `send(self(), ...)` run in the worker process and should capture the test PID in a closure instead.
- **Internal `:alloy_request_deadline` provider config key:** When `:timeout_ms` is finite, Alloy now passes `:alloy_request_deadline` (an internal monotonic millisecond deadline) in the `provider_config` map given to providers, alongside existing runtime keys (`:system_prompt`, `:on_event`, `:provider_state`). Custom providers that validate `provider_config` strictly (for example via `Keyword.validate!/2` or `NimbleOptions`) should ignore unknown `:alloy_*` keys, as documented in `Alloy.Provider`.
- `Alloy.Tool.Executor` now treats explicit `input: nil` (for example from a custom provider or `:before_tool_call` `{:edit, ...}` middleware) as an invalid non-object tool input instead of coercing it to `%{}`; omit `:input` or pass `%{}` for no-argument calls.
- `Alloy.Provider.decode_body/1` now rejects non-object JSON (such as `null`, arrays, or scalars) with `{:error, %Alloy.Provider.Error{kind: :protocol_error}}` and invalid JSON with `{:error, %Alloy.Provider.Error{kind: :malformed_reply}}` instead of a bare string. `Error` implements `String.Chars`, so string interpolation continues to work, but callers pattern-matching a binary error or decoding non-object JSON via `decode_body/1` must update.
- `Alloy.Agent.Config.from_opts/1` validates startup options strictly and raises `ArgumentError` on `provider: nil`, boolean provider values, non-positive `:max_turns` / `:max_tokens` / `:tool_timeout`, non-positive/non-`:infinity` `:timeout_ms`, negative `:max_retries` / `:retry_backoff_ms`, non-map `:context`, non-string `:system_prompt`, empty or non-string `:working_directory`, non-2-arity `:on_compaction`, non-boolean `:code_execution`, empty or non-string `:until_tool`, and invalid `:middleware` or `:fallback_providers` entries (including `{Mod, nil}`). (`retry_backoff_ms: 0` and `timeout_ms: :infinity` are valid.)
- `Alloy.Tool.resolve_path/2` expands relative `:allowed_paths` entries against `:working_directory` rather than the BEAM process working directory, and rejects non-string paths, NUL bytes, and non-list `:allowed_paths`.
- `Alloy.Provider.Codex` launches via non-login `sh -c` with explicit port `:env` instead of a login shell, rejects option-like `:codex_bin` values, and treats non-zero exits under `persist_session: true` as errors even when a `last_message` file exists. Set `:codex_bin` explicitly if `codex` is only on a login-profile `PATH`.
- `Alloy.Testing.run_with_responses/3` now validates options through `Alloy.Agent.Config.from_opts/1` (defaulting to `compaction: false`, enforcing the scripted `Alloy.Provider.Test`, and clearing `:fallback_providers`) and raises `ArgumentError` on unknown or invalid options that were previously ignored.
- `Alloy.Provider.OpenAI`, `Alloy.Provider.OpenAICompat`, and `Alloy.Provider.OpenAIStream` now require a non-empty string tool-call `"id"`/`"call_id"` and `"name"` (returning non-retryable `:protocol_error` if missing or empty instead of emitting tool calls with `nil` IDs), except under `finish_reason: "length"` / Responses `status: "incomplete"` (where cut-off calls receive unique placeholder `"truncated_<n>_<uniq>"` IDs, `"truncated"` names, and `input: %{}` so the loop abandons them with its `max_tokens` error and matching error tool results in `result.messages`) and `finish_reason: "content_filter"` / Responses `incomplete_details.reason: "content_filter"` (where partial calls are dropped so the refusal reaches the loop without retrying).
- `Alloy.Provider.Error.kind()` adds `:protocol_error` (non-retryable, for deterministic wire-schema contract violations such as valid non-object JSON replies, malformed choices/candidates/content/blocks, missing required tool-call `id`/`name`, or mismatched Anthropic SSE deltas) and `:shutdown` (non-retryable; skipped by retries and fallback loops) for supervisor shutdown interrupts across HTTP and Codex providers (including resumed Codex turns, which preserve `:shutdown` instead of `:session_uncertain` while noting `:session_generation` rotation in `error.message`); callers with exhaustive `case` matches on `error.kind` or rotating `:session_generation` by `kind` should handle `:protocol_error` and `:shutdown`.
- `tool_validation: :schema` now converts unsupported `$schema` dialects (`ExJsonSchema.Schema.UnsupportedSchemaVersionError`, e.g. Draft 2020-12) into an `ArgumentError` naming the tool and `$schema` value.
- **Value-safe tool & custom `:bash_executor` exception redaction:** Raised exceptions inside tools or custom `:bash_executor` functions now keep their message only for `RuntimeError` (capped to 500 bytes), standard `:badarg` (`"argument error"`), and atom key names on `KeyError` (`"KeyError (key :foo not found)"`). All other raised exceptions (including `MatchError`, `CaseClauseError`, custom-message `ArgumentError`, and custom `defexception` structs) report only their exception module in `tool_result` blocks, `result.tool_calls[].error`, `[:alloy, :tool, :stop]`, and logs so captured `context`/credential maps cannot leak. Tools that want the model or telemetry to see an error message should return `{:error, message}` or `raise "..."`.
- **Strict middleware return-value validation:** Middleware `{:halt, reason}`, `{:halt, reason, state}`, and `{:block, reason}` now require a binary (`String.t()`) `reason`, and `{:edit, modified_call}` requires a plain map; non-conforming returns raise `ArgumentError` instead of propagating into worker crashes or `Protocol.UndefinedError`.

### Added

- **Portable structured outputs (`:output_schema` / `result.output`):** `Alloy.run/2`, `Alloy.stream/3`, and `Alloy.Agent.State.prepare/2` accept `:output_schema` (a plain JSON Schema map or `%{name: ..., schema: ..., strict: ...}`), translating it into each built-in provider's native structured-output wire format (`output_config.format` on Anthropic, `text.format` on OpenAI/xAI, `response_format` on OpenAICompat, `generationConfig.responseJsonSchema` on Gemini, prompt schema instructions on Codex), keeping compaction summaries schema-free, decoding/validating the final assistant JSON into `result.output`, and exposing machine-readable failures on `result.metadata.run.output_error`.
- **Opt-in live provider contract test suite (`@tag :live`):** Excluded by default in `test/test_helper.exs`; runnable via `mix test --only live` (or per-provider `@tag :live_anthropic`, `:live_openai`, `:live_gemini`, `:live_xai`, `:live_openai_compat`, `:live_codex`) against real API credentials.
- **OpenTelemetry tracing recipe & 0.14 upgrade guide:** Added `docs/recipes/opentelemetry.md` and `docs/upgrading-to-0.14.md`.
- `Alloy.Provider.OpenAI` and `Alloy.Provider.XAI` now accept `:extra_headers`.
- `Alloy.Provider.Gemini` now accepts `:extra_body` (merged last with stringified keys, merging `generationConfig` one level deep so caller keys coexist with `:output_schema`).
- CI now verifies compilation and tests without the optional `:ex_json_schema` dependency.

### Changed

- **Typed `:malformed_reply` vs `:protocol_error` errors:** Transient JSON/SSE corruption (undecodable JSON bodies or SSE chunks, invalid/non-object tool-argument JSON from the model, incomplete Anthropic tool blocks, Codex empty `tool_use` / stream mismatch) returns retryable `%Alloy.Provider.Error{kind: :malformed_reply}` (bounded by `:max_retries` before output is emitted), whereas deterministic provider wire-schema violations (valid non-object top-level/SSE JSON, malformed choices/message/delta/content/candidates/parts/blocks, missing required tool-call `id`/`name`, mismatched Anthropic SSE deltas) fail fast with non-retryable `%Alloy.Provider.Error{kind: :protocol_error}`. Rescued SSE event-handler crashes halt the stream early, log only the exception module plus argument-stripped stacktrace, and return non-retryable `kind: :unknown`. Valid JSON objects with unexpected top-level keys return `kind: :unknown` (non-retryable) with bounded inspect output.
- **Shared internal sanitization (`Alloy.Internal.Sanitize`):** Consolidated UTF-8-safe byte capping, bounded term inspection, value-safe outer-shape summaries (used in `Config` and `Middleware` `ArgumentError` messages so misconfigured provider tuples, `:fallback_providers`, `:context`, `:system_prompt`, or invalid middleware return values never leak secrets), value-safe exception/exit summaries (keeping capped `RuntimeError` messages, `:badarg`, atom-key `KeyError` names, and safe atom-tagged exit tuples while omitting payloads from other raised exceptions and compound exits so `context` or `provider_config` secrets never leak into tool results, logs, or telemetry), and stacktrace argument stripping into one internal helper used across providers, tools, compactor, events, retry, middleware, and `OwnedWorker`.
- **OpenAI & OpenAICompat refusal blocks:** `Alloy.Provider.OpenAI`, `Alloy.Provider.OpenAICompat`, and `Alloy.Provider.OpenAIStream` now surface assistant refusal fields (`OpenAI` Responses refusal blocks, `OpenAICompat`/`OpenAIStream` `message.refusal`, `delta.refusal`, and array-of-parts `%{"type" => "refusal"}`) as `%{type: "text", text: ..., refusal: true}` blocks (making refusal text visible in `result.text` / `result.messages` and enabling structured-output `:refusal` detection), and `OpenAICompat` / `OpenAIStream` reject non-string, non-null `refusal` payloads with non-retryable `:protocol_error`.
- **Core tool & memory bounds:** `Alloy.Tool.Core.Edit` refuses binary files, files over 10 MiB, and non-boolean `replace_all` values; `Bash` and `Write` reject non-string inputs; custom `:bash_executor` functions returning shapes other than `{binary, integer}` now return `{:error, ...}` instead of misreporting a timeout or crashing; `Alloy.Memory.tool/1` caps results at 50,000 characters and rejects `create`/`str_replace`/`insert` on `/memories`.
- **Event & stream callback resilience:** `Alloy.Events.emit/3` rescues raising `:on_event` callbacks (logging at most once per run with argument-stripped stacktraces) so a buggy UI callback cannot abort a run after side-effecting tools execute, and `Alloy.Provider.Retry` suppresses repeated warnings to at most once per callback per stream (likewise with argument-stripped stacktraces) when `:on_chunk` or `:on_event` raises.
- **Sequential tool event ordering (`tool_concurrency: 1`):** `Alloy.Tool.Executor` now executes each tool call as a singleton batch when `tool_concurrency: 1`, so `:tool_start` and `:tool_end` events alternate per call instead of emitting all `:tool_start` events upfront, and later calls are cleanly skipped if `:timeout_ms` expires mid-round.
- **Per-run `Turn.run_loop/2` transient state reset:** `Alloy.Agent.Turn.run_loop/2` now resets `status` (to `:running`), `error`, `stop_reason`, `provider_response_metadata`, and `run_metadata` at the start of every run so hosts driving `Turn.run_loop/2` on a reused `%Alloy.Agent.State{}` never see stale `final_tool`, `output`, `output_error`, `provider_error`, or response metadata from an earlier run.

### Fixed

- **Structured output prefill scoping:** `Alloy.Agent.Turn` now scopes structured-output refusal detection and JSON decoding strictly to the final turn's returned assistant messages, so an empty final turn following an assistant prefill or prior refusal classifies as `:missing_text` instead of decoding or re-triggering on pre-turn messages.
- **SSE framing, backpressure & cancellation:**
  - Non-200 SSE error bodies (including multi-paragraph HTML/JSON with `\n\n`) are captured verbatim, scoped per response so redirect bodies never leak into later errors, and capped at 64 KiB (halting runaway non-200 streams early).
  - `SSE.parse_event/1` strips at most one leading space and keeps the last `event:` line per the SSE spec.
  - Deadline-bounded HTTP/SSE workers monitor caller termination and use acknowledged per-chunk delivery to preserve backpressure while executing callbacks in the caller process.
- **Error classification & bounds (`Alloy.Provider.Error`):**
  - Added dedicated non-retryable `:shutdown` kind for supervisor shutdown interrupts across HTTP and Codex providers (skipped by both retries and fallback loops, and never produced from provider error payloads).
  - `Error.from_body/1` classifies numeric and string-numeric HTTP status codes (`400..599`) in in-band `error.code` fields (populating `:status` so typeless in-band errors format as `"HTTP <code>: <message>"`) and checks `error.type` before falling back to `error.status`.
  - Overflow phrase checks scan the first 64 KiB of the sanitized message (skipped for 5xx, while explicit `context_length_exceeded` `code` or `type` labels still classify as `:context_overflow`), and stored error messages slice before UTF-8 sanitization and are capped by byte size (2,000 bytes for string error bodies/messages; 500 bytes for `Jason.encode/1`/`inspect/2` and transport fallbacks).
- **Provider streaming & parsing:**
  - `OpenAIStream` and `OpenAICompat`:
    - Map non-truncation/non-refusal finish reasons (including `"stop"` and omitted reasons) with present tool calls to `:tool_use`, and tolerate truncated tool-call arguments under `finish_reason: "length"` and `"content_filter"` so `:max_tokens` tool abandonment and `:refusal` reach the loop without retrying.
    - Support array-of-parts `content` (extracting text and thinking parts, skipping unknown well-formed part types forward-compatibly, tagging content-part thinking with JSON-safe `source: "content_part"` and withholding it from top-level `reasoning_content` on subsequent turns, and rejecting malformed present content/reasoning values).
    - Preserve `usage` on non-empty `choices` chunks, capture `finish_reason` when `delta` is omitted, reject non-map choices and explicit non-map `delta`, validate `extra_content` shapes, and guard usage parsing against malformed fields.
    - Support tool calls without an `index` (reusing slots for repeated `id`s, allocating fresh slots safely alongside sparse explicit indices, and routing id-less continuations to the most recently touched call) and accept missing or `""` no-arg tool call arguments (while still rejecting explicit `nil`/`false`/non-object arguments).
  - `Anthropic`: concatenates split `signature_delta` chunks, rejects non-object SSE JSON, malformed SSE event/delta shapes, and mismatched target-block deltas with non-retryable `:protocol_error` on every stop except `:refusal`, rejects undecodable SSE JSON and invalid or unclosed streaming tool blocks outside `max_tokens`/`model_context_window_exceeded`/`refusal` stops with retryable `:malformed_reply`, and adds a bounded `parse_response/1` catch-all.
  - `Gemini`: rejects cut-off streams whose chunks carry `"finishReason": null`, guards usage parsing (preserving earlier non-nil counts over later `null`s), ignores `"error": null`, and prioritizes real object/string (and list-wrapped) in-band API errors over malformed or present candidates in both `complete/3` and `stream/4`.
  - Trailing `/` is trimmed on `:api_url` across HTTP providers, and `ModelMetadata` matches `models/gemini-*` prefixes.
- **Retry & fallback safety:**
  - Fallback providers without optional `stream/4` fall back to `complete/3` (without emitting `on_chunk`/`:text_delta` chunks; the full reply is returned in `result.text` and `result.messages`); fallback `provider_state` is isolated from the primary origin; `:shutdown` interrupts skip fallback providers (both from primary and mid-fallback loop); `retry_backoff_ms: 0` no longer crashes `:rand.uniform(0)`; Alloy deadline metadata stays outside `req_options` so custom providers forwarding `req_options` to Req work without unknown-option errors; request timeouts scale monotonically across the 5-second headroom boundary.
- **Tool loop & middleware controls:**
  - `Message.normalize_for/3` uses round-local ID renaming so reused same-origin IDs stay paired.
  - `tool_validation: :schema` preflights fail-fast (raising `ArgumentError` / `InvalidSchemaError` / `Jason.EncodeError` on invalid schemas) before the first provider request and whenever middleware changes tools, accepts tool properties literally named `"$ref"`, normalizes and scope-resolves subschemas under literal property names (`"default"`, `"const"`, `"enum"`, `"examples"`) while rejecting nested `$id`/`id` inside literal-keyword values and failing closed on `$ref` targets pointing into non-schema literal data (such as `#/default`), and enforces `$id`/`id`-scoped local-only `#`-prefixed `$ref` resolution (rejecting external and absolute self-references, verified against `ex_json_schema` `0.11.x`) so the remote schema resolver is never invoked.
  - `stop_after_tool` succeeds when `:after_tool_execution` appends a user message; invalid middleware return values raise a descriptive `ArgumentError`.
- **Compactor & overflow recovery:**
  - `drop_thinking/1` and `compact_messages/2` drop empty `content: []` messages; `force_compact/2` shrinks large tool results on single-round overflows even with adaptive thinking blocks or under-estimated token counts; multimodal `tool_result` lists reuse fixed media token budgets instead of counting base64 bytes; `before_completion` skips `:after_compaction` when messages are unchanged.
  - Summary requests sanitize primary and fallback provider configs (stripping session, tool/server-tool/web-search controls, OpenAI `"text"`, and Gemini `generationConfig` schema/thinking fields while preserving privacy keys like `:store` / `"store" => false`); `Turn` only sets `prompt_too_long_recovery: true` when recovery does not fail; eliminated O(N^2) `Enum.at/2` cut-point scans.
- **Process cleanup & OTP hygiene:**
  - Custom `:bash_executor` runs and `Provider.HTTP` share `Alloy.OwnedWorker` for supervised caller-monitored execution with Logger metadata and OpenTelemetry context propagation, killing workers on timeout/cancellation even when trapping exits, preserving abnormal worker crash propagation to linked children, re-raising caught Req adapter/plug crashes in the caller under `:deadline` with argument-stripped stacktraces, and returning `{:error, %Alloy.Provider.Error{kind: :unknown}}` with a sanitized exit reason on external worker/owner kills (such as `max_heap_size` or `Process.exit/2`) instead of crashing the caller.
  - `Core.Bash` traps supervisor shutdown signals, checks for immediate caller exit before `Port.open`, and kills the process group on runner exits.
  - `Codex` creates `0700` temp directories atomically with cryptographically random names (`umask 077` + `mkdir`, failing closed if unavailable), writes input files with `[:exclusive]` and `set -C` defense in depth, stops the process group on mid-stream crashes without unbounded stack traces, and wraps input-file write errors in `%Alloy.Provider.Error{}`.
  - `OSProcess.signal_group/2` falls back cleanly when `/bin/sh` is absent; added `:crypto` to `extra_applications` in `mix.exs`; `Usage.merge/2` handles explicit `nil` fields; `Transcript.validate/1` omits spurious `:missing_result` for invalid call IDs.
- **Docs & dependencies:** Fixed compactor order in `README.md` and `CHANGELOG.md` (including correcting the `[0.13.0]` compactor ordering note), added missing `Alloy` options and upgrade notes for `:after_tool_call`, fixed `docs/recipes/code-mode.md` and `livebooks/quickstart.livemd`, and updated `plug`/`plug_crypto` test dependencies to clear Hex advisories.

## [0.13.0] - 2026-10-14

Alloy 0.13 is the loop and nothing else: the supervised runtime moves to
the `alloy_agent` package, memory and compaction become an ordinary tool
and ordinary middleware, and what 0.12.5 deprecated is removed. See
[Upgrading to 0.13](docs/upgrading-to-0.13.md).

### Removed

- **The agent runtime moved to [`alloy_agent`](https://github.com/alloy-ex/alloy_agent):**
  `Alloy.Agent.Server`, `Alloy.Session`, `Alloy.send_message/3`,
  `Alloy.cancel_request/2`, the `config :alloy, :pubsub` app-start PubSub
  and the optional `phoenix_pubsub` dependency. The deprecated
  `Alloy.Agent.Events` shim is gone; use `Alloy.Events`.
- **Everything 0.12.5 deprecated:**
  - `:max_budget_cents` and the `:budget_exceeded` status. Use the
    budget middleware recipe.
  - Anthropic `:extended_thinking`. Setting it now raises instead of
    silently turning thinking off.
  - Codex `:auth_path`. Setting it now raises instead of silently running
    as the default account.
  - `State.materialize/1`, `State.cleanup/1` and `state.messages_new`.
  - `ModelMetadata.catalog/0` and its `model_entry` type.
  - `Message.server_tool_result_block/3`.
- `Alloy.Memory.Router`'s public functions (`dispatch_all/2`,
  `memory_call?/1`, `tool_name/0`); the router is internal now.
- `state.current_task` and `state.pending_requests`, which were server
  state.

### Added

- **Composable loop controls:**
  - `:after_tool_call` middleware can replace each result's content and
    structured data before publication, while preserving success/error status.
  - Opt-in `tool_validation: :schema` validates arguments using the optional
    `ex_json_schema` dependency (drafts 4/6/7, local references, no coercion).
    The default remains object/required-key validation.
  - `stop_after_tool: "name"` completes successfully after a matching successful
    call and the rest of its round settle. `result.text` is the selected output;
    `result.metadata.final_tool` includes its ID, name, and structured data.
  - `Alloy.Agent.State.prepare/2` prepares messages, tools, system prompt, and
    provider through existing middleware, rebuilding definitions and model limits.
  - `Alloy.Transcript.validate/1` checks client tool pairing; `repair/1`
    explicitly supplies interrupted outcomes only where a result is missing.
  - `tool_concurrency:` caps parallel tool execution without changing sequential
    tool barriers. The default remains the scheduler count.
- **Opt-in Codex continuation (`persist_session: true`) and streaming:**
  - The default remains ephemeral. Continuation fingerprints the serialized
    transcript rather than loop-added provenance, and starts fresh when
    execution configuration or earlier history changes. Failed resumes return
    non-retryable `:session_uncertain`. Hosts can change `:session_generation`
    after failure/cancellation to recover without losing Alloy history.
    Continuation metadata is JSON-safe.
  - Codex streams the last validated structured answer at `turn.completed`,
    before process exit, keeping command diagnostics and commentary out of
    answer text. Final-response disagreement is an error; callbacks run in the
    caller and cancellation stops the subprocess tree.
- `Alloy.Tool.native_types/0` (optional) and `:native_types` on inline
  tools: a provider's built-in type for the tool, such as Anthropic's
  `memory_20250818`.
- The `:on_context_overflow` middleware hook.
- `Alloy.Agent.State.deadline`: the monotonic deadline for the run's
  provider requests, for middleware that makes its own.
- `Alloy.Message.normalize_for/3` and `Alloy.Message.origin/2`, for
  callers who call a provider directly.
- Tested host-only recipes for bounded producer-side output capture and nested
  tool execution. No scripting runtime, file store, or Claude adapter is added
  to Alloy's core or runtime dependencies.

### Changed

- **Tool argument edits compose:** `:before_tool_call` edits now pass through
  later middleware instead of ending the chain. Block and halt still stop it.
- **Gemini tool-result envelopes:** Gemini preserves tool-result text inside
  explicit `output`/`error` envelopes rather than decoding JSON-looking text
  into arbitrary response fields. Public tool results and transcripts retain
  their original content and error status.
- **Unknown options raise.** `Alloy.run/2`, `Alloy.stream/3` and
  `Config.from_opts/1` ignored options they did not know, so a typo ran
  silently without its setting. Server options name `alloy_agent` in the
  error. Removed provider options (`:extended_thinking`, `:auth_path`) raise
  at startup too, for fallback providers as well as the primary, and
  `compaction: false` with the compactor in `:middleware` raises.
- **`%Alloy.Agent.Config{}` drops** `memory`, `pubsub`, `subscribe`,
  `max_pending`, `on_shutdown` and `max_budget_cents`. Middleware reading
  one gets a `KeyError` when that hook runs.
- **Memory is an ordinary tool.** `Alloy.Memory.tool/1` builds it, and
  `memory:` is shorthand for it.
  - Memory calls run through the tool executor, so `:before_tool_call`
    middleware, tool events, `:tool_timeout` and `result.tool_calls` cover
    them; they bypassed all four.
  - They run one at a time in call order.
  - Memory now works with every provider: Anthropic gets its native
    `memory_20250818` tool, and the others get a function tool with the
    same commands.
  - Store callbacks now run in a supervised task, like every tool, not in
    the process that called `Alloy.run/2`. Stores that rely on the calling
    process need checking: the process dictionary, caller-owned ETS
    tables, Logger metadata, or a `Repo.transaction` around the run.
  - A store that raises now becomes an error result the model reads (and
    is logged), instead of crashing the run.
- **Compaction is middleware.** `Alloy.Context.Compactor` implements
  `Alloy.Middleware`, and `Alloy.run/2` puts it last so it budgets inputs
  prepared by caller middleware.
  - `compaction: false` turns it off, and listing it in `:middleware`
    chooses its position.
  - A hand-built `%Config{}` gets no compaction unless it lists the
    compactor.
  - On a context-overflow error the loop runs the new
    `:on_context_overflow` hook and retries once, only if the messages
    changed. 0.12 retried even when nothing could be removed.
  - `:after_compaction` and `[:alloy, :compaction, :done]` now also fire
    after that forced compaction.
  - The retried request runs `:before_completion` again, including
    compaction. A history still estimated over budget can be compacted
    again in that turn.
  - `[:alloy, :turn, :prompt_too_long_recovery]` fires on a turn's first
    overflow as before, and now carries `retry: true | false`.
- **A middleware halt keeps the work done before it in that hook.** In
  0.12 a halt returned the state from before the hook ran. Now a halt
  after compaction keeps the compacted history and the summary request's
  usage. Middleware can return `{:halt, reason, state}` to keep its own
  changes as well.
- **Module tools are validated like inline tools** at startup. An invalid
  `strict?/0`, `input_examples/0`, `defer_loading?/0` or `native_types/0`
  raises `ArgumentError`.
- **Tool names must be unique.** Two tools with the same name raise at
  startup instead of reaching the API, which rejects them.
- **Assistant messages record where they came from.**
  - New fields: `message.provider`, `message.model`, and `message.origin`.
    The origin is a hash of the provider module, `:api_url` and `:api_key`;
    the key itself is never stored.
  - Code that compares whole messages with `==` sees the new fields.
    Messages you build yourself leave them `nil`.
  - Persist all three with transcripts. A message without an origin is
    sent as it is.
- Release publication now requires the full `mix ci` gate, warning-free docs,
  and a tag matching the package version.

### Performance

- Reuse resolved tool schemas across agent turns when their input schemas are
  unchanged. Schema changes are checked before execution; cache entries remain
  bounded to the active tool set and never appear in result/session metadata.

### Fixed

- Gemini tools use `parametersJsonSchema` so valid JSON Schema keywords such as
  `additionalProperties` are accepted by the API instead of producing HTTP 400.
- Compaction summary requests omit thinking and redacted thinking blocks,
  including string-keyed blocks, while preserving visible text and tool evidence.
- Subscription-sharing quota exhaustion is not retried as transient throttling.
- Provider retries honor HTTP-date `Retry-After` headers as well as numeric delays.
- Codex `tool_use` replies with no calls return a typed `:malformed_reply`
  failure, retried within the existing attempt/deadline budget on fresh calls.
  Text accompanying an empty call list is never silently treated as completed work.
- **Switching provider, endpoint or account mid-conversation** no longer
  sends one origin's signed reasoning to another. That failed with HTTP
  400s such as `invalid_encrypted_content` or an invalid thinking
  signature. It covers a fallback provider, an OpenAI fallback on another
  organisation's key, and a model switch to another provider. Before every
  request the loop applies `Alloy.Message.normalize_for/3`, following pi's
  rules:
  - another provider's thinking becomes text;
  - its redacted thinking, raw OpenAI/xAI items and server tool records
    are dropped;
  - signatures are removed, and blank text blocks (kept only for a
    signature, and rejected by Anthropic) are dropped;
  - tool-call ids Anthropic would reject (Kimi's `functions.read:0`, for
    one) are rewritten together with their results.

  Switching models with the same provider and credentials keeps
  everything, as Anthropic, OpenAI and Gemini document. Messages without an
  origin (built by hand, or saved without it) are sent unchanged.
- **Gemini tool calls written by another provider** get Google's
  documented placeholder thought signature
  (`skip_thought_signature_validator`) on the first call of each step, so
  Gemini 3 accepts a tool loop that started elsewhere.
- **Anthropic thinking without a signature** (written by hand, or by a
  reasoning model behind OpenAICompat) is sent as text instead of failing
  the request; empty unsigned thinking is dropped.

## [0.12.5] - 2026-10-09

### Security

- **`:allowed_paths` is enforced on a directory boundary.** It was a string
  prefix match, so allowing `/proj` also admitted `/proj-secrets/key.txt`. The
  path that was checked (symlinks resolved) is now the path that is opened,
  and a symlink loop returns an error instead of hanging the tool. Custom
  tools calling `Alloy.Tool.resolve_path/2` with `:allowed_paths` set get
  that resolved path (for example `/private/var/...` on macOS).
- **The bash tool no longer passes secrets to commands.** Variables whose
  names contain `KEY`, `TOKEN`, `SECRET`, `PASSWORD` or `CREDENTIAL` are
  removed from the command's environment by default, so a prompt-injected
  `printenv` can't read your API keys. Pass `:bash_env` in the tool context
  (a map of the variables to set, or `:inherit` for the previous behaviour)
  if a command needs one.
- **Bash timeouts kill the command.** A timeout stopped only the Elixir task,
  so the command kept running; the whole process group (including background
  jobs) is now killed. Output is capped while it streams (the first 8 KB and
  last 20 KB are kept), so a command printing hundreds of megabytes no longer
  exhausts memory, and the model-requested timeout is capped (10 minutes, or
  `:bash_max_timeout`).
- **Memory tool paths are validated strictly.** `/memories_evil/...`,
  `/memories..` and percent-encoded `..` were accepted, and the model could
  delete or rename the `/memories` root.
- **Codex no longer copies `auth.json` into temp directories**, and the temp
  directory holding the prompt (the whole conversation) is created `0700`
  instead of the default mode, which left it readable on a shared `/tmp`.
- **Mint is now constrained to `~> 1.11`** (and through it HPAX `~> 1.1`).
  Mint 1.9 and earlier carry several advisories on the HTTP/1 client path
  every Alloy provider uses by default, including memory-exhaustion DoS from
  unbounded response headers and chunked bodies (CVE-2026-58229,
  CVE-2026-56810, CVE-2026-82728) and response smuggling on pooled
  connections (CVE-2026-82672, CVE-2026-94194, CVE-2026-59249), plus HTTP/2
  issues (CVE-2026-91043, CVE-2026-92103, CVE-2026-59246). HPAX before 1.0.4
  has an HPACK decoding DoS (CVE-2026-58226). These matter because Alloy talks
  to user-configured, possibly untrusted, OpenAI-compatible endpoints. If your
  application pins Mint below 1.11, run `mix deps.update mint hpax`.
- Req is required at `>= 0.6.1 and < 0.8.0` (tested on 0.7.5).

### Changed

- **Built-in providers return `{:error, %Alloy.Provider.Error{}}`** instead of
  a string when called directly. `Alloy.run/2` and `Alloy.Agent.Server` are
  unaffected: `result.error` is still the same string
  (`Exception.message/1` of the struct), and the struct is added at
  `result.metadata.run.provider_error`. The struct implements `String.Chars`,
  so interpolating it still works; code that applies `=~` or binary
  patterns to a provider's raw error should use `Exception.message/1`.
  Messages keep their `"<type>: <message>"` shape when the error body has a
  type; untyped bodies now read `"HTTP <status>: <message>"` (OpenAICompat
  produced `": message"`, Gemini `"429: message"`), and a blocked Gemini
  prompt is a `:refusal` instead of an error. `Alloy.Provider.OpenAIStream.stream/5`
  returns the struct too.
- **Turn telemetry fires in order.** Each `[:alloy, :turn, :stop]` is
  emitted when that turn ends; previously the loop recursed first, so stops
  arrived in reverse and turn 1's stop carried the run's final status. A
  turn the loop continues past now reports `status: :running`. Dashboards
  that read a turn's stop status as the run outcome should use
  `[:alloy, :run, :stop]`.
- **`Alloy.Agent.Server.chat/3` and `stream_chat/4` return `{:error, result}`
  for `:budget_exceeded`**, as `Alloy.run/2` always did (it returned
  `{:ok, result}`), and its default call timeout is the agent's
  `timeout_ms` plus 10 seconds instead of 30 seconds, so a caller no longer
  gives up while the turn is still running.
- **Compaction strips stale reasoning.** Claude Fable 5.1, Opus 5.5,
  Sonnet 5.5 and Haiku 5.5 reject signed thinking whose earlier history
  changed, for accounts created on or after 2026-08-31. After any
  compaction, every thinking block is removed, including the turn in
  progress, which was produced before the rewrite. This is the documented
  valid change, and those models think adaptively, which doesn't require the
  turn to start with thinking. Under manual thinking (`:extended_thinking`,
  or `"type" => "enabled"` in `:extra_body`), which does require it and
  whose models don't check history, the turn in progress keeps its
  thinking. Truncation never splits a tool round, and oversized retained
  tool results are shortened with a marker.
- `Alloy.Context.Compactor`: in `compact_messages/2`, `:keep_recent` is a
  minimum (whole tool rounds are kept) and `redacted_thinking` blocks are
  dropped with other earlier-turn thinking; `force_compact/1` always
  summarizes, which costs a provider call.
- A limit-only `model_metadata_overrides` entry for a catalog model now also
  covers its dated snapshots (`-2026-03-05`, `-20251001`, `-0309-...`) but
  not other suffixes such as `-fast`; give `suffix_patterns` for those.
- `Alloy.run/2` raises `ArgumentError` for an `:on_event` that is not a
  1-arity function, as `Alloy.stream/3` already did.
- **The compaction estimate counts the whole request** — system prompt, tool
  definitions and every block type, by bytes rather than characters (CJK text
  was undercounted about 3x) — so compaction fires earlier and more
  accurately.
- **A tool is not called when the model omits a `required` key** (or sends
  non-object input); the model gets an error result naming the missing keys
  instead of a `FunctionClauseError` it can't act on. If a tool supplies a
  default for a key, remove that key from `required`. Types are not checked
  or coerced.
- **Every tool call runs in a supervised, unlinked task** (previously
  sequential tools ran in the agent process). `self()` and the process
  dictionary inside a tool differ for sequential tools; Ecto's SQL sandbox
  still works through `$callers`. Event and telemetry handlers for tool
  start/end now run in the agent process.
- `Alloy.Testing.tool_response/2` gives tools input as real providers do: a
  map goes through a JSON round trip, so keys are strings and atom values
  become strings (`%{unit: :celsius}` arrives as `%{"unit" => "celsius"}`;
  expect `"celsius"` in `assert_tool_called/3`). Tests that relied on atom
  keys were passing for the wrong reason; update the tool or the test.
- **Codex runs against your real `CODEX_HOME`** (or `:codex_home`) with
  `--ignore-user-config --ignore-rules`, and requires Codex CLI 0.122.0 or
  later. Your `$CODEX_HOME/AGENTS.md` and skills now reach Alloy runs; for
  full isolation, and to keep agents from refreshing the same token as your
  interactive Codex, log in to a dedicated home
  (`CODEX_HOME=~/.codex-alloy codex login`) and pass it as `:codex_home`.
  Codex failures return `%Alloy.Provider.Error{}`; timeouts are retried
  within the turn deadline. `response_metadata.command_output` is now the
  JSONL event stream.
- **OpenAI, xAI and OpenAI-compatible providers no longer send a default
  output cap** (`max_output_tokens`/`max_tokens` were 4,096). Reasoning
  tokens count against the cap on current models, so responses came back
  incomplete or empty. Set `:max_tokens` to cap output; some
  OpenAI-compatible servers have small defaults of their own.
- **`usage.input_tokens` means uncached input for every built-in provider.**
  OpenAI-family and Gemini usage now reports cache reads in
  `cache_read_input_tokens` (and writes in `cache_creation_input_tokens`)
  instead of inside `input_tokens`, matching Anthropic. Total prompt tokens
  are the sum of the three. Reported `input_tokens` — and with them
  `Alloy.Usage.total/1` and `Alloy.Usage.estimate_cost/3` — drop by the
  cached amount.
- `Alloy.Provider.SSE.process_chunk/2` scans only the new bytes for event
  boundaries (a large event went from 663 ms to 8 ms), so `buffer` must be
  the remainder returned by the previous call, as in normal use.
- **Anthropic default `max_tokens` is 16,000** (was 4,096). Adaptive
  thinking is on by default on Claude 5.x and counts toward `max_tokens`, so
  the old default truncated answers. Set `:max_tokens` to keep a lower cap.
- **Anthropic code execution uses `code_execution_20260521`** (required for
  programmatic tool calling), and Alloy no longer adds beta headers for
  features that went GA on 2026-02-17 (memory, tool search, input examples,
  code execution). `context-management-2025-06-27` is still added when the
  body uses context editing; user-supplied `anthropic-beta` values are merged
  into one header.
- **OpenAI context limits are the documented maximum input**, not the
  advertised window (which includes output): `gpt-5.4`/`gpt-5.5` and the
  GPT-6 family budget 922,000 tokens, `gpt-5`/`5.1`/`5.2` 272,000. Compaction
  now fires before the API rejects the request instead of after.
- **Long-tail OpenAI-compatible models** (Kimi, Qwen, GLM, Mistral, Gemma)
  are no longer in the built-in catalog, because their limits could not be
  verified; they use the 200,000-token default. Set
  `model_metadata_overrides` or a `:model_catalog` for them. Compaction may
  fire earlier than before, which is the safe direction.
- Restrict test-only Plug to patched 1.19/1.20 versions.
- Pin the contributor toolchain to Elixir 1.20.4 / OTP 28.5.0.7, add OTP 29
  coverage, dependency audits, weekly CI, and explicit read-only CI permissions.
- **Stricter quality gates.** `mix ci` runs every gate CI enforces: format,
  unused-lock check, `hex.audit` (advisories), warnings-as-errors compile,
  compile-time cycle check, strict Credo with opt-in correctness checks,
  tests with a coverage floor, and Dialyzer with `:unmatched_returns`,
  `:missing_return`, `:extra_return` and `:error_handling`. Docs must build
  without warnings.

### Added

- **More provider stop reasons.** `Alloy.Provider.stop_reason/0` adds
  `:max_tokens`, `:refusal` and `:pause_turn`, and `Alloy.Result` gains a
  `:stop_reason` field. The loop now:
  - completes a truncated answer (`:max_tokens`) with
    `result.stop_reason == :max_tokens`, so callers can detect truncation
    instead of receiving it silently;
  - fails the run when `:max_tokens` cuts off a tool call (its arguments are
    incomplete). The orphaned call gets an error result, so the transcript
    stays valid for a follow-up request;
  - fails on `:refusal` and discards the refused partial output;
  - resends the conversation unchanged on `:pause_turn`.

  Custom providers that only return `:tool_use`/`:end_turn` are unaffected.
  A provider returning an unknown stop reason now fails the run with a clear
  error instead of crashing the loop.
- **Codex reports token usage** from `codex exec --json` `turn.completed`
  events (it reported zero), and a `:config_overrides` option passes `-c`
  settings to the CLI.
- `Alloy.Result.wrap/1` (the status → `{:ok, _}`/`{:error, _}` mapping shared
  by `Alloy.run/2` and `Alloy.Agent.Server`), `Alloy.Agent.Server.default_call_timeout/1`
  and `Alloy.Context.Compactor.force_compact/2`.
- **Telemetry:** `[:alloy, :turn, :exception]` and `[:alloy, :run, :exception]`
  (with `kind`, `reason`, `stacktrace`); turn start gains `monotonic_time`,
  turn stop gains `duration` and `monotonic_time`, and turn metadata gains
  `telemetry_span_context`. The compaction summary request emits
  `[:alloy, :provider, :request]`.
- **Read pages large files**: output ends with
  `[Showing lines X-Y of N. Use offset=Z to continue.]` when cut, and binary
  files are refused.
- `Alloy.Provider.Error.from_body/1` for errors a provider reports inside a
  200 response (mid-stream `error` events, failed responses).
- **OpenAI Responses replay keeps every output item.** Assistant `phase`
  (which gpt-5.3-codex and later expect back) and items such as built-in tool
  calls and compaction items are preserved as `%{type: "output_item", raw:
  item}` blocks instead of being dropped.
- **Anthropic `:server_tools`** — raw server tool definitions (web search,
  web fetch, `mcp_toolset`, tool search) appended after the generated tools,
  so local and server tools can be combined. Previously the only route was
  `extra_body["tools"]`, which replaces every generated tool.
- **Anthropic programmatic tool calling works.** `allowed_callers` atoms are
  translated to the API's values (`:code_execution` →
  `"code_execution_20260120"`, `:human`/`:direct` → `"direct"`), the
  `caller` field is kept on `tool_use` blocks, and the code-execution
  container is reused across turns via `provider_state` (skipped once its
  `expires_at` has passed, so a resumed session gets a fresh container).
- **Model catalog: current models.** Claude Opus 4.7, Opus 5/5.5, Sonnet
  5/5.5, Haiku 5.5, Fable 5.1 and Mythos (1M); GPT-6 Astra/Sol/Luna, GPT-6.1
  Sol and GPT-5.6 Sol/Terra/Luna; Gemini 3.1 Flash-Lite, 3.5–3.8 Flash and
  3.5 Flash-Lite; Grok 4.5–4.7 and Build 0.1. Every limit was checked against
  the vendor's model pages on 2026-10-09 and the source is cited in the code.
- **`Alloy.Provider.Error`** — structured provider failures with a `:kind`
  (`:rate_limited`, `:overloaded`, `:server_error`, `:timeout`, `:network`,
  `:context_overflow`, `:quota`, `:auth`, `:invalid_request`, `:unknown`),
  plus `:status`, `:type`, `:code` and `:retry_after_ms`. Custom providers
  may return it; string errors keep working.

### Deprecated

- **`:max_budget_cents`** (removed in 0.13). It stops a run only when the
  provider reports `usage.estimated_cost_cents`, which no built-in provider
  does, so with them it never fired. A warning is logged once per node when
  it is set. The `Alloy` module docs have a "Budget limits" recipe: a
  `:before_completion` middleware that prices `state.usage` with
  `Alloy.Usage.estimate_cost/3`.
- `Alloy.Agent.State.materialize/1`, `Alloy.Agent.State.cleanup/1` and the
  `messages_new` field (removed in 0.13): the history now lives in
  `state.messages`.
- Codex `:auth_path` (removed in 0.13; a warning is logged once per node).
  Use `:codex_home`. An `auth.json` path uses its directory as `CODEX_HOME`;
  a file with another name is still copied into a private per-call home, as
  in 0.12.4.
- Anthropic `:extended_thinking` (removed in 0.13). It sends manual thinking
  (`type: "enabled"` with `budget_tokens`), which Claude 4.7 and later
  reject. It keeps working for older models; for current ones pass
  `extra_body: %{"thinking" => %{"type" => "adaptive"}}` (see the provider
  docs for effort and `display`).
- `Alloy.ModelMetadata.catalog/0`. The built-in catalog is now a short list of
  family patterns; the function keeps its entry shape (one entry per family,
  empty `:name`, full-id pattern as the suffix pattern) and will be removed
  in 0.13. Use `context_window/1`.
- `Alloy.Message.server_tool_result_block/3`. No provider accepts the block
  it builds; it will be removed in 0.13.

### Fixed

- **A streamed tool call keeps its id when later chunks repeat it as
  `null`.** Some OpenAI-compatible hosts (DeepInfra, serving DeepSeek and GLM)
  send `"id": null` on every chunk after the first, which overwrote the real
  id; the next request then echoed a null `tool_call_id` and was rejected.
  Chunks carrying `"tool_calls": null` are also accepted. Thanks @johns10
  (#50).
- **`until_tool` requires a successful call.** A failed, blocked or unknown
  call to the target tool used to satisfy it.
- **A middleware halt no longer leaves an unanswered tool call.** Halting in
  `:before_tool_call` or `:after_tool_request` left the assistant's
  `tool_use` without a result, so the next request in that session failed
  with HTTP 400; each call now gets an error result first.
- **A tool named `memory` works when `:memory` is not configured** (the turn
  crashed with a `KeyError`); configuring both `:memory` and a tool named
  `memory` raises at startup instead of silently shadowing the tool.
- **The compaction summary call** goes through retries and the turn
  deadline, and its token usage is counted. Results that compaction already
  cleared are not cleared again (which lost their original size and
  invalidated the prompt cache).
- **A stream callback that raises no longer corrupts history.** Text from a
  delta whose `on_chunk`/`on_event` raised was missing from the stored
  message, so the UI and the transcript disagreed. A raised exception is now
  logged and the stream continues; a `throw` or `exit` from a callback still
  stops the stream, as before.
- `Alloy.run/2` passes `:on_event` through (it was silently ignored), and the
  documented top-level `code_execution: true` now reaches the provider.
- `Alloy.Usage.estimate_cost/3` no longer rounds per-million rates to whole
  cents ($0.075/M priced as 8¢).
- **A tool that calls `exit/1` or `throw/1` no longer kills the agent**, and
  `:tool_timeout` now applies to `concurrent?: false` tools too (they had no
  time limit; they are now stopped after `:tool_timeout`, 120 s by
  default). Cancelling a turn
  (`Alloy.Agent.Server.cancel_request/2`) still stops its in-flight tools: a
  supervised watcher kills them when the turn is killed.
- **Tools run in the order the model called them.** Sequential tools used to
  run before every concurrent one, so `[read f, edit f]` read the file after
  editing it. Consecutive concurrency-safe calls still run in parallel (at
  most `System.schedulers_online/0` at once, as before).
- **Invalid UTF-8 in a tool result no longer breaks the session.** Reading a
  binary file put bytes in the transcript that failed JSON encoding on every
  later request; results are now sanitised.
- **Tool start/end events and telemetry pair up** when a tool times out or
  crashes (the end event had no start sequence and a zero duration).
- **Edit** rejects an empty `old_string` (with `replace_all` it inserted the
  replacement between every character) and no-op edits, matches LF text in
  CRLF files and keeps their line endings and BOM.
- **Read** validates `offset`/`limit` (an `offset` of 0 dropped the last
  line; a negative `limit` returned the file's tail) and reports the line
  count when the offset is past the end.
- **Memory tool:** `view_range` is honoured and `new_str` is optional, as
  the tool contract specifies.
- `Alloy.Testing.assert_tool_called/3` works with `require` as well as `use`.
- **Codex keeps your login.** Each call copied `auth.json` into a temp
  `CODEX_HOME` and deleted it afterwards, discarding refreshed tokens; since
  Codex CLI 0.136.0 a reused refresh token forces a re-login. Keyring
  credentials and `:profile` (broken since CLI 0.134.0) now work too.
- Codex: an explicit `timeout_ms: nil` no longer raises `Enum.EmptyError`, a
  missing `:workdir` is reported by name instead of as "exit status 2", and
  every Codex failure is an `%Alloy.Provider.Error{}` (malformed responses
  were plain strings).
- **Cancelled or timed-out Codex turns no longer leak** the `codex` process,
  its children or temp files: a supervised owner process monitors the caller
  and stops the whole process group.
- **OpenAI Responses (and xAI) no longer chain responses on their own.**
  Every response's id was fed back as `previous_response_id` while the full
  history was still sent, so from the second request of a run the server
  replayed the conversation twice — duplicated context and billing — and
  with `store: false` the request pointed at a response that was never
  stored. The stateless encrypted-reasoning echo was also switched off after
  the first request. Chaining is now explicit: pass `:previous_response_id`
  and send only the new messages. If you continued a stored response by
  passing `provider_state: %{response_id: id}`, pass
  `previous_response_id: id` instead — that state is no longer sent.
- **OpenAI family:**
  - `response.failed`, `response.incomplete`, `error` events and cut-off
    streams are errors or `:max_tokens`/`:refusal` instead of partial
    successes; Chat Completions `length` maps to `:max_tokens` and
    `content_filter` to `:refusal`;
  - OpenAICompat sends `reasoning_content` back on assistant messages, which
    DeepSeek's thinking mode requires during tool calls (it returned HTTP 400
    on the second request of every tool loop);
  - atom keys in OpenAICompat `extra_body` now override generated fields
    (they produced duplicate JSON keys and were ignored).
- **Opaque OpenAI items no longer break other providers.** When a transcript
  moves from OpenAI Responses to Anthropic or Gemini (for example through
  `fallback_providers`), `reasoning` and `output_item` blocks are dropped
  instead of being sent as invalid blocks (Anthropic) or placeholder text
  (Gemini).
- **Anthropic:**
  - every stop reason is mapped (`max_tokens`,
    `model_context_window_exceeded`, `refusal` with its `stop_details`,
    `pause_turn`) instead of collapsing to `:end_turn`;
  - streamed usage is no longer double-counted (`message_delta` usage is
    cumulative; the docs' example reported 13,361 input tokens instead of
    10,682);
  - mid-stream `error` events, streams that end without a stop reason and
    error bodies on a 200 response are errors, not partial successes; an
    overload before any output is retried;
  - with `cache: true`, `cache_control` is never put on a `defer_loading`
    tool (HTTP 400).
- **Gemini:**
  - streamed text no longer gains a newline between chunks
    (`"Hello\n world"`); consecutive text and thought pieces are merged and
    thought signatures stay on the block they arrived with;
  - `output_tokens` now includes thinking tokens (billed as output), and
    `input_tokens` excludes cache reads (reported as
    `cache_read_input_tokens`, matching Anthropic) and includes tool-use
    prompt tokens;
  - `maxOutputTokens` is sent only when `:max_tokens` is set; the old 4096
    default also had to fit thinking, so 3.x responses were cut short;
  - `finishReason` maps to `:max_tokens`/`:refusal` (details in
    `response_metadata.stop_details`), blocked prompts are a `:refusal`,
    and malformed or unexpected function calls are retryable errors;
  - mid-stream error chunks and streams cut off before a `finishReason`
    are errors instead of partial successes.
- **Overstated context windows.** Grok 4.20 was listed at 2M (documented 1M)
  and retired Grok slugs at up to 2M, so compaction never fired before the
  API rejected the request. Claude Opus/Sonnet 4.6 were listed at 200k (now
  1M), and `claude-fable-5-1` fell through to the default.
- **Retries are classified on HTTP status and error code, not message
  text.** Previously not retried: Anthropic `api_error` (500) and
  `timeout_error` (504), OpenAI 503 `server_is_overloaded` and 429s whose
  type was not `rate_limit_error`. Quota and spend-limit 429s
  (`insufficient_quota`, `*_spend_limit_exceeded`) are no longer retried.
  `Retry-After` / `retry-after-ms` is honoured, within the turn deadline.
- **Context-overflow recovery now works for Gemini and OpenAI Responses.**
  Their overflow errors ("exceeds the maximum number of tokens", "exceeds
  the context window") were not recognised, so the one-shot compaction retry
  never ran.
- **A `:tool_use` response with no client tool calls** (only server-executed
  tools) now completes instead of sending an empty tool-results message.
- **Anthropic server tools are no longer answered by the client.** When a
  response mixed a server tool (`code_execution`, `web_search`, tool search)
  with a local tool call, Alloy also "executed" the `server_tool_use` block
  and sent back a `server_tool_result`, a block type the API rejects, so
  the next request failed with HTTP 400. `Alloy.Message.tool_calls/1` now
  returns only client `tool_use` blocks. Transcripts persisted by earlier
  versions still work: the Anthropic provider drops stale
  `server_tool_result` blocks when it builds a request.
- OpenAI-compatible Gemini streams preserve opaque thought signatures on
  tool calls, including late signatures and parallel calls, for the next request.
- OpenAICompat's `stream_options: false` now omits the field from streaming
  requests. Explicit `extra_body` stream option maps are preserved.
- Codex process timeouts use an absolute monotonic deadline, so progress output
  cannot extend `:timeout_ms` or the turn's `:receive_timeout` cap.
- **The Codex provider now honours the turn deadline in real runs.** The
  0.12.4 note claimed this, but the retry loop passes the deadline as
  `req_options: [receive_timeout: ms]` and Codex only read a top-level
  `:receive_timeout`, so production runs always waited the full
  `:timeout_ms`. All three caps are now respected; the smallest wins.

## [0.12.4] - 2026-07-03

### Fixed

- **`Alloy.Testing` default tools now ship in Hex.** The default echo tool is
  an inline `Alloy.Tool.Inline` instead of a `test/support` module.
- **Signed thinking blocks are never truncated.** Deterministic fallback
  compaction now drops signed thinking blocks instead of mutating provider
  signatures.
- **Tool crash results are model-legible.** Tool result errors are one
  actionable line, while full stacktraces remain in logs and telemetry.
- **Codex provider honors turn deadlines.** `:receive_timeout` now caps the
  Codex port timeout and still kills the subprocess on expiry.

### Added

- **Batched tool-result clearing before summary compaction.** Old
  `tool_result` and `server_tool_result` content is cleared in one batch before
  any summarizer call, with `:clear_tool_results`,
  `:keep_recent_tool_results`, and `[:alloy, :compaction, :cleared]`
  `bytes_cleared` telemetry.
- **`:thinking` on `Alloy.Result`** (#36): a run result now surfaces the final
  assistant reasoning text alongside `:text`, so callers no longer have to dig
  it out of the last message's content blocks. Adds an `Alloy.Message.thinking/1`
  helper for per-message extraction.
- **User-owned compaction prompts.** `:summary_system_prompt` and
  `:summary_prompt` are now configurable under `compaction:`.
- **OpenAI Responses reasoning persistence.** Stateless Responses calls request
  `reasoning.encrypted_content`, preserve raw reasoning items, and round-trip
  them before related function calls.
- **Strict tool schemas.** Tools can opt into `strict?/0` or `strict: true`;
  OpenAI, OpenAICompat, and Anthropic emit strict tool definitions, and Alloy
  validates `additionalProperties: false`.
- **Anthropic advanced tool-use metadata.** Tools can provide
  `input_examples` and `defer_loading`; Anthropic emits the fields and merges
  the `advanced-tool-use-2025-11-20` beta header when needed.
- **Anthropic `extra_body` passthrough.** Provider-specific body fields such as
  server-side MCP connector config can be merged into the request.

### Changed

- **Anthropic prompt caching adds a conversation-tail breakpoint.** With
  `cache: true`, the last content block of the last message gets
  `cache_control`, alongside existing system/tool breakpoints.
- **Docs grouping updated.** `Alloy.Events` is grouped under Core,
  `Alloy.Agent.Events` is left ungrouped as the deprecated shim, and
  `Alloy.Memory` / `Alloy.Memory.Router` have a Memory group.

### Docs

- README documents non-goals, the compaction knobs and cache trade-off, strict
  tools, Anthropic input examples/deferred loading, and OpenAI reasoning-item
  persistence.
- MCP recipe documents remote Anthropic MCP mounting via `mcp_servers`,
  beta headers, and provider passthrough while keeping the client-side recipe
  for local/stdio MCP.

## [0.12.3] - 2026-06-11

### Fixed

- **Gemini 3.x thought signatures in `OpenAICompat`** (lands PR #24):
  `thought_signature` from `extra_content.google` is preserved on tool_use
  blocks and echoed back on subsequent turns — without it Gemini 3.x returns
  HTTP 400 on multi-turn tool calls. Also handles Gemini's list-shaped error
  bodies (previously a `FunctionClauseError`) and adds a `parse_error`
  catch-all.
- **`Config.on_shutdown` type broadened to `(struct() -> any())`** (#40) so
  `alloy_agent`'s session struct satisfies dialyzer without a suppression.

### Added

- **`extra_body` on the native OpenAI (Responses) provider** (#18), merged
  last so callers can override any request field; atom keys are stringified.
  Brings the Responses provider to parity with `OpenAICompat`.
- **`grok-4.3` in the model catalog** (lands PR #41): xAI's current frontier
  model, 1M context window; xAI provider docs updated to reference it.
- **Mistral usage example** in the `OpenAICompat` moduledoc (#19).

- **Model catalog refresh.** Added `claude-fable-5` and `claude-opus-4-8`
  (1M-token context windows), `gpt-5.5`, and `gemini-3.5-flash` to the
  built-in catalog.
- **Docs:** v1 event envelope specification (`docs/events.md`) documenting
  the `:on_event` contract; a runnable Livebook quickstart
  (`livebooks/quickstart.livemd`); README repositioned around the
  harness-not-framework premise with honest bash-sandboxing language.
- **`alloy_agent` status clarified.** README and the migration doc now state
  plainly that `alloy_agent` is not yet on Hex and that the 0.13 removals
  will not happen before it ships.

- **Inline tool definitions (`Alloy.Tool.inline/1`).** Tools can now be
  defined as data — an `Alloy.Tool.Inline` struct with `name`, `description`,
  `input_schema`, and a 2-arity `execute` function — and passed in `tools:`
  alongside tool modules. This unlocks tools discovered at runtime (e.g.,
  building one tool per MCP-server tool from its discovery response — see the
  MCP recipe) and one-off tools that don't warrant a module. Optional fields
  mirror the behaviour's optional callbacks (`concurrent?`,
  `max_result_chars`, `allowed_callers`, `result_type`). The executor treats
  both kinds identically: same crash isolation, truncation, events, and
  parallel execution.
- **`Alloy.Testing.run_with_responses/3` accepts `:context`**, so tools that
  read from the agent context can be tested without dropping down to
  `Alloy.run/2`.

- **Recipes (hexdocs guides).** Two new documented, tested patterns instead of
  new core features: *Sub-agents as tools* (delegation via a ~30-line tool
  whose `execute/2` calls `Alloy.run/2`, verified verbatim in
  `test/alloy/recipes/sub_agent_recipe_test.exs`) and *MCP servers as tools*
  (a single gateway tool over `anubis_mcp`, keeping context cost to one tool
  definition). Core stays loop-only by design.

- **Pluggable model catalog (`Alloy.ModelCatalog`).** The built-in
  `Alloy.ModelMetadata` is now just the default implementation of a new
  behaviour. Pass any module implementing `context_window/1` (and optionally
  `default_context_window/0`) via the new `:model_catalog` option to source
  context windows from your own catalog — a static map, your own service, or
  an adapter over `llm_db`. Resolution order: explicit `:max_tokens` →
  `:model_metadata_overrides` → `:model_catalog` → default window.
  `Alloy.ModelMetadata.override_window/2` is new public API supporting this
  split. Fully backward compatible: the default catalog and override
  semantics are unchanged.

### Changed

- **Elixir 1.20 / OTP 28 support.** Verified on Elixir 1.20.1 (gradual type
  checker) with zero warnings; CI matrix now tests 1.20/OTP 28 and 1.19/OTP 27.
  The `~> 1.17` requirement is unchanged.
- **req `~> 0.6` (security).** req 0.6.0 fixes GHSA-px9f-whj3-246m (multipart
  header injection) and GHSA-655f-mp8p-96gv (decompression bomb). The floor is
  bumped because Alloy can target user-configured OpenAI-compatible endpoints,
  which is the malicious-server vector the bomb fix addresses.
- Dev/test deps updated: credo 1.7.19 (1.7.16 crashes under Elixir 1.20),
  jason 1.4.5, telemetry 1.4.2, plug 1.19.2, ex_doc 0.40.3.

### Fixed

- Removed a dead `parse_assistant_content/1` fallback clause in
  `Alloy.Provider.OpenAI` (flagged as unreachable by the Elixir 1.20 type
  checker).
- Internal tests no longer call the deprecated `Alloy.Agent.Events` shim;
  the suite now exercises `Alloy.Events` directly
  (`test/alloy/events_test.exs`).

## [0.12.2] - 2026-04-26

### Changed

- **`Alloy.Events`** is the new canonical module for v1 event envelope construction. The implementation moved from `Alloy.Agent.Events` to the top-level namespace because `Alloy.Agent.Turn` (the protocol loop) calls it directly — anything Turn calls is, by definition, part of Alloy's protocol surface, not a runtime concern.
- **`Alloy.Agent.Events`** is now a `@deprecated` thin shim that delegates to `Alloy.Events`. External callers receive compile-time deprecation warnings and should switch their `alias` lines from `Alloy.Agent.Events` to `Alloy.Events`. The shim will be removed in Alloy 0.13.0.

### Corrected

- **Retracts the 0.12.1 guidance to migrate `Alloy.Agent.Events` → `AlloyAgent.Events`.** That guidance was wrong: `Alloy.Agent.Turn` depends on event envelope construction, so the v1 envelope format is protocol-layer (stays in Alloy), not runtime-layer (move to `alloy_agent`). The migration table in `docs/MIGRATION-alloy_agent.md` has been updated to point at `Alloy.Events` instead. Users who already migrated to `AlloyAgent.Events` based on 0.12.1 should switch back to `Alloy.Events`; the two implementations are byte-equivalent today, but only `Alloy.Events` will receive future protocol updates.
- **`Alloy.Agent.Server`** and **`Alloy.Session`** deprecation guidance is unchanged — those modules still move to `alloy_agent` as `AlloyAgent.Server` and `AlloyAgent.Session` (they are runtime concerns Turn doesn't depend on).

## [0.12.1] - 2026-04-24

### Deprecated

- **`Alloy.Agent.Server`**, **`Alloy.Session`**, and **`Alloy.Agent.Events`** are now documented as deprecated in HexDocs (warning admonitions on each `@moduledoc`). These modules moved to the new [`alloy_agent`](https://hex.pm/packages/alloy_agent) package as `AlloyAgent.Server`, `AlloyAgent.Session`, and `AlloyAgent.Events`. The copies in Alloy continue to work unchanged in 0.12.x and will be **removed in 0.13.0**.

> **No `@deprecated` attribute / compile-time warnings yet.** The protocol loop (`Alloy.Agent.Turn`) still calls `Alloy.Agent.Events` internally, so adding `@deprecated` would break `mix compile --warnings-as-errors` for Alloy itself. The protocol/runtime split for events will be tightened in a follow-up patch ahead of 0.13.0; in the meantime, the HexDocs admonitions and the migration table below are the migration signal.

### Why

Alloy is refocusing as a protocol library: the loop, providers, tools, memory behaviour, message types. Runtime concerns (supervised processes, sessions, async dispatch, PubSub, backpressure, default memory stores) belong in the application layer, where OTP already gives you the primitives. `alloy_agent` is the opt-in runtime wrapper for users who want a supervised agent without wiring a GenServer themselves.

Elixir's value proposition here is stronger than in Python or TypeScript: the BEAM already is the runtime. A protocol library that composes *with* OTP beats a runtime library that competes with it.

### Migration

Add `{:alloy_agent, "~> 0.1"}` to your deps, then:

| Before (Alloy 0.12.0) | After (alloy_agent 0.1.0) |
|---|---|
| `alias Alloy.Agent.Server` | `alias AlloyAgent.Server` (or just `alias AlloyAgent`) |
| `%Alloy.Session{}` | `%AlloyAgent.Session{}` |
| `Alloy.Session.new/1` | `AlloyAgent.Session.new/1` |
| `Alloy.send_message/3` | `AlloyAgent.send_message/3` |
| `Alloy.cancel_request/2` | `AlloyAgent.cancel_request/2` |

Code that uses only `Alloy.run/2`, `Alloy.stream/3`, tools, providers, messages, or the memory behaviour needs **no changes**.

### Not changed

- No runtime behaviour change in this release. The deprecated modules work exactly as they did in 0.12.0. This is a soft-migration patch — you have until Alloy 0.13.0 to move your imports.

## [0.12.0] - 2026-04-24

### Added

- **`Alloy.Memory` behaviour** — first-class protocol for Anthropic's `memory_20250818` tool. Six callbacks (`view`, `create`, `str_replace`, `insert`, `delete`, `rename`) that any store can implement, matching the split used by Anthropic's own Python SDK (`BetaAbstractMemoryTool`). Memory is a protocol-level primitive with application-level storage — Alloy ships the behaviour, wire format, and path validation; user code (or future `alloy_agent`) ships the backing store.
- **Anthropic provider memory wiring** — passing `memory: {StoreModule, store_opts}` to `Alloy.run/2` when using `Alloy.Provider.Anthropic` now injects the `memory_20250818` tool into the request and adds the `context-management-2025-06-27` beta header. Memory tool calls are routed through `Alloy.Memory.Router` rather than the generic tool executor, keeping the pipelines clean.
- **`Alloy.run/2` `:memory` option** — validates at entry that memory requires `Alloy.Provider.Anthropic` (raises `ArgumentError` otherwise, with a clear migration path). Other providers will be wired as they ship their own memory primitives.
- **Model catalog** — added context-window entries for:
  - Kimi K2.5, K2.6 (Moonshot AI, 256K) — via `OpenAICompat` at `api.moonshot.ai`
  - Gemma 4 (Google open-weight, 256K) — via `Gemini` provider
  - GLM-4.6 (Zhipu AI, 200K) — via `OpenAICompat` at `open.bigmodel.cn`
  - Qwen 3 family — `qwen3-max`/`qwen3-coder-plus` (up to 1M context), `qwen3-vl-plus`, `qwen3-omni-flash`, `qwen3.5-397b-a17b` — via `OpenAICompat` at DashScope
  - Mistral Large 3 (`mistral-large-2512`, 256K) — via `OpenAICompat` at `api.mistral.ai`

### Notes

- Memory is non-breaking: existing callers who do not pass `:memory` see zero behavioural change.
- The `context-management-2025-06-27` beta header is injected **only** when memory is configured. Accounts without beta access continue to see requests exactly as before.
- The 1M-context Qwen 3 entries (`qwen3-coder-plus`, `qwen3.5-397b-a17b`) are notable — they offer a larger window than the current OpenAI/Anthropic ceilings and slot into Alloy through the generic `OpenAICompat` provider with no new code.

## [0.11.0] - 2026-04-21

### Added

- **grok-4.20 family in the model catalog** — `grok-4.20-0309-reasoning`, `grok-4.20-0309-non-reasoning`, and `grok-4.20-multi-agent-0309` now register their real 2M-token context window in `Alloy.ModelMetadata`. Users who explicitly pass one of these model IDs to `Alloy.Provider.XAI` no longer hit the generic 200K fallback in the Compactor. Suffix patterns use regex so future `-MMDD` snapshots on the same family don't need a catalog update.
- **Provider typespec parity** — every provider that implements the `Alloy.Provider` behaviour now exposes a `@type config` and `@spec` on `complete/3` and `stream/4`. Users who run dialyzer get type-checking at call sites for all six providers (previously only `Codex`). No runtime change — this is purely a tooling-visibility improvement.

### Changed

- **`Alloy.Provider.XAI` docstring example** — now uses `grok-4.20-0309-reasoning` as the default-suggestion model (was `grok-4`) to reflect the current xAI API frontier.

## [0.10.2] - 2026-04-18

### Fixed

- **Codex subprocess leak on timeout** — `Alloy.Provider.Codex` now spawns codex via `Port.open` and explicitly kills the OS process (SIGTERM → 100ms grace → SIGKILL) when `:timeout_ms` trips. Previously `Task.shutdown(:brutal_kill)` closed the BEAM task but left the `/bin/sh` + `codex` subprocess tree running, leaking one OS process per timeout.
- **Codex temp-dir leak** — `prepare_paths/1` now cleans up `base_dir` when `prepare_codex_home/2` fails mid-setup. Previously the directory was orphaned on disk because the `try/after` cleanup in `complete/3` never ran.
- **Codex `arguments_json` decode** — falls back to a backslash-escape repair pass for invalid JSON escapes (`\d`, `\s`, `\p`, `\A`) that Codex occasionally emits from regex-containing code payloads. Decodes that previously failed with `Jason.DecodeError` now retry cleanly.
- **UTF-8-safe truncation** — `response_metadata.command_output` (and other truncated fields) no longer splits multi-byte codepoints mid-sequence. `truncate/2` now uses `String.slice/3` (character budget) rather than `binary_part/3` (byte budget).

### Changed

- **Codex provider typespecs** — added `@type config` and `@spec` to `complete/3` and `stream/4`; corrected invalid `Path.t()` references to `String.t()` (Elixir's `Path` module defines no `t/0` type).
- **Codex provider internals** — module attribute constants replace scattered magic numbers; `Enum.reduce_while/3` replaces two-pass tool-block parsing; `with`-guards and pattern-matching replace awkward conditional chains; catchall `emit_chunks/2` clause prevents `stream/4` crashes on unknown result shapes. Observable behaviour unchanged.

## [0.10.1] - 2026-04-13

### Fixed

- **Tool result truncation** — `max_result_chars` guard now uses character count (`String.length`) instead of byte count (`byte_size`). Multi-byte UTF-8 content (CJK, emoji) was triggering truncation earlier than intended.
- **Codex provider timeout** — `run_codex` now wraps `System.cmd` in a `Task` with a configurable timeout (default 120s). Previously a hung `codex exec` process could block the turn loop indefinitely.
- **Symlink path traversal** — `allowed_paths` validation now resolves symlinks recursively via `resolve_real_path`, preventing symlink-based escapes from allowed directories.
- **OpenAICompat nil guard** — added pattern match on `tc["function"]` before accessing arguments. Malformed tool call responses now return a graceful error instead of crashing the turn loop.
- **Testing helper** — `assert_tool_called` no longer raises `ArgumentError` when matching string keys against atom-keyed input maps. Uses `safe_atom_get` with rescue fallback.
- **Gemini streaming performance** — `parse_stream_parts` uses prepend+reverse instead of `++` accumulation, eliminating O(n²) behavior on large streaming responses.
- **Terminate ordering** — `State.cleanup` now runs after `on_shutdown` callback and `:session_end` middleware, ensuring consumers can access state before resources are freed.
- **Middleware docs** — documented that `{:edit, ...}`, `{:block, ...}`, and `{:halt, ...}` all stop the middleware chain immediately (first responder wins).

## [0.10.0] - 2026-04-12

### Added

- **Gemini provider** — `Alloy.Provider.Gemini` adds native Google Gemini support via the GenerateContent API, including streaming and tool calling.
- **xAI provider** — `Alloy.Provider.XAI` wraps the OpenAI Responses API with xAI defaults. Use `{Alloy.Provider.XAI, api_key: key, model: "grok-4"}` instead of manually setting `api_url`. Supports `web_search: true` and `x_search: true` for Grok's native search tools.
- **Codex provider** — `Alloy.Provider.Codex` adds OpenAI Codex support with ChatGPT authentication and session management.
- **Tool concurrency control** — tools can implement `concurrent?/0` to declare whether they are safe to run in parallel. The executor runs non-concurrent tools sequentially first, then concurrent tools in parallel. Default: `true`.
- **Tool result truncation** — tools can implement `max_result_chars/0` to cap output length. The executor truncates results that exceed the limit, keeping head and tail. Default: `:unlimited`.
- **Prompt-too-long recovery** — when a provider returns a "prompt is too long" error, Alloy forces context compaction and retries the turn once before failing.
- **`until_tool` option** — `Alloy.run("question", until_tool: "submit")` forces the loop to continue until the model calls the named tool. If the model signals `:end_turn` without calling it, the loop injects a continuation prompt and keeps going. Useful for structured output enforcement via tool schemas.
- **HITL `:edit` variant** — middleware can return `{:edit, modified_call}` from `:before_tool_call` to rewrite tool arguments before execution. The modified call must preserve the original `:id` and `:name`. This enables human-in-the-loop argument correction, policy-based input rewriting, and tool-call sanitization.

### Fixed

- **Duplicate `prompt_too_long?/1` clause** — removed dead code (identical function clause).

## [0.9.0] - 2026-03-22

### Breaking

- **`Compactor.maybe_compact/1` return type** — now returns `{:compacted | :unchanged, State.t()}` instead of a bare `State.t()`.
- **`Alloy.Context.TokenCounter` removed** — token estimation logic inlined into `Compactor`. Users who called `TokenCounter` directly should use `Compactor` functions instead.

### Added

- **`:after_compaction` middleware hook** — fires after context compaction occurs, allowing middleware to inspect or modify state post-compaction.
- **Reasoning/thinking block parsing in OpenAICompat** — DeepSeek and xAI reasoning models that return `reasoning_content` now produce `%{type: "thinking", thinking: text}` blocks instead of silently dropping the reasoning data. Works in both `complete/3` and streaming.
- **`extra_body` config for OpenAICompat** — pass `extra_body: %{"response_format" => ..., "temperature" => 0.7}` to inject arbitrary provider-specific parameters into the request. Merges last so it can override defaults.
- **Anthropic prompt caching** — pass `cache: true` in Anthropic provider config to automatically add `cache_control` breakpoints to the system prompt and last tool definition. Enables 60-90% input token cost savings. Default: `false` (no behavior change).
- **6 new telemetry events** — `[:alloy, :run, :start]`, `[:alloy, :run, :stop]`, `[:alloy, :turn, :start]`, `[:alloy, :turn, :stop]`, `[:alloy, :provider, :request]`, `[:alloy, :compaction, :done]` provide full lifecycle observability for OTEL, logging, or custom metrics.
- **xAI grok-4.1-fast model family** — dot-notation models (`grok-4.1-fast`, `grok-4.1-fast-reasoning`, `grok-4.1-fast-non-reasoning`) added to the model catalog.

### Fixed

- **grok-4 context window** — corrected from 256K to 2M tokens per xAI documentation.

## [0.8.0] - 2026-03-21

### Added

- **Cost guard** — `Alloy.run/2` now accepts `max_budget_cents: N` to cap agent spend. The loop halts with `:budget_exceeded` status when cumulative `estimated_cost_cents` exceeds the threshold. Default is `nil` (no limit).
- **One-shot streaming helper** — `Alloy.stream/3` provides a simpler API for streaming agent responses without managing a GenServer.

### Changed

- **Summary-first context compaction** — `Alloy.Context.Compactor` now preserves the first message, keeps a recent token-budgeted verbatim window, and replaces older context with a single structured handoff summary generated through the configured provider. Falls back to deterministic truncation if summary generation fails.
- **Grouped compaction settings** — `compaction: [reserve_tokens: N, keep_recent_tokens: N, fallback: :truncate]` makes context compaction behavior configurable.
- **Reserve-based compaction trigger** — compaction now starts when the conversation exceeds `max_tokens - reserve_tokens` instead of the previous fixed 90% threshold.

### Fixed

- **Bash tool timeout** — fixed timeout override not being respected when passed via tool input.

## [0.7.6] - 2026-03-19

### Added

- **Grouped compaction settings** — `Alloy.run/2` now accepts `compaction: [...]` with `reserve_tokens`, `keep_recent_tokens`, and `fallback`, making context compaction behavior configurable without replacing `max_tokens`.

### Changed

- **Summary-first context compaction** — `Alloy.Context.Compactor` now preserves the first message, keeps a recent token-budgeted verbatim window, and replaces older context with a single structured handoff summary generated through the configured provider.
- **Reserve-based compaction trigger** — compaction now starts when the conversation exceeds `max_tokens - reserve_tokens` instead of relying on the previous fixed 90% threshold.
- **Repeated compactions reuse the handoff summary** — Alloy updates the existing synthetic summary message on later compactions instead of stacking multiple summaries, while still falling back to deterministic truncation if summary generation fails.

## [0.7.5] - 2026-03-13

### Fixed

- **EchoTool test crashes (7 warnings)** — `EchoTool.execute/2` now accepts both string and atom key maps, fixing pattern-match failures when the test provider sends atom-keyed tool inputs.
- **Anthropic double-timeout** — removed the `Task.Supervisor` wrapper from `Anthropic.complete/3`. Req's `receive_timeout` (injected by `Retry.inject_receive_timeout`) already enforces the deadline — the Task added a redundant `yield + 5s` buffer. `complete/3` now calls `Req.request` directly, matching the OpenAI and OpenAICompat providers.
- **6 Dialyzer warnings resolved** — changed `pending_requests` typespec from `:queue.queue()` (opaque in OTP 28) to `term()` in `State`, replaced `when value == %{}` guard with `map_size/1` in `Result`, and removed unreachable `nil` clause in `maybe_put_metadata/3`.
- **`stringify_keys/1` safety** — added explicit `is_binary(k)` clause and `raise ArgumentError` for unexpected (non-atom, non-string) map keys instead of silent pass-through.

## [0.7.4] - 2026-03-06

### Added

- **Config-level model metadata overrides** — `Alloy.run/2` now accepts `:model_metadata_overrides`, allowing applications to override or extend model context windows used to derive compaction budgets without waiting for a library release.

### Changed

- **`max_tokens` defaults now follow provider models** — `Alloy.Agent.Config` derives the compaction budget from the configured provider `:model` when the catalog knows that model, re-derives it when models change via `Server.set_model/2`, and falls back to `200_000` only when no model metadata is available or when no model is configured.

## [0.7.3] - 2026-03-06

### Fixed

- **Hex publish workflow validation** — the release workflow no longer references `secrets.*` directly in step `if:` guards, so tag-triggered publish jobs can run again and dispatch the landing-site sync correctly.

### Changed

- **Release version bump** — republishes the provider/model refresh from `0.7.2` as a valid Hex release candidate after fixing the GitHub Actions publish workflow.

## [0.7.2] - 2026-03-06

### Added

- **xAI Responses path documented and tested** — `Alloy.Provider.OpenAI` now explicitly documents `api_url: "https://api.x.ai"` usage, and tests verify custom Responses API routing.
- **Current xAI model budgeting** — `TokenCounter` now recognizes current public xAI API model names including `grok-4`, `grok-4-fast-reasoning`, `grok-4-fast-non-reasoning`, `grok-4-1-fast-reasoning`, `grok-4-1-fast-non-reasoning`, and `grok-code-fast-1`.

### Changed

- **Provider/model docs refreshed** — README and provider moduledocs now point to current Anthropic 4.6, OpenAI GPT-5.4, Gemini 2.5/3 preview, and xAI model setups.
- **Anthropic code execution integration updated** — provider now uses `code_execution_20250825` and automatically merges required `anthropic-beta` headers with caller-supplied beta flags.
- **Publish workflow aligned with CI strictness** — release pipeline now runs `mix credo --strict` before publishing to Hex.pm.

### Fixed

- **OpenAI token budgets corrected** — `gpt-5`, `gpt-5.1`, and `gpt-5.2` context limits were updated to current published limits, preventing stale compaction thresholds.
- **xAI token budgets corrected** — `grok-4` now uses the documented 256k window, while Grok 4 fast and Grok 4.1 fast variants use the documented 2M window.
- **Anthropic model drift removed** — stale Anthropic alias examples were replaced with current `claude-opus-4-6`, `claude-sonnet-4-6`, and `claude-haiku-4-5` references.

## [0.7.1] - 2026-03-04

### Added

- **`Alloy.Result` struct** — typed, `Access`-compatible return value from `Alloy.run/2` and `Server.chat/3`. Single source of truth for the 8-field result contract. Implements `Access` behaviour for bracket-syntax backwards compatibility (`result[:text]`).
- **`Alloy.Result` in hex docs** — added to the Core group in the sidebar.

## [0.7.0] - 2026-03-04

### Added

- **Anthropic code execution support** — configure `code_execution: true` to enable Anthropic's server-side Python sandbox. Alloy handles `server_tool_use` / `server_tool_result` round-trips across Message, Executor, and Anthropic provider layers. The `code_execution_20250522` tool type is appended to the request body when enabled.
- **Optional tool callbacks** — `Alloy.Tool` behaviour gains `allowed_callers/0` and `result_type/0` as `@optional_callbacks`. Tools that don't implement them compile and work as before. Registry uses `function_exported?/3` to conditionally include metadata in tool definitions.
- **Structured tool results** — tools can return `{:ok, text, data}` 3-tuples. Text goes into the result block (what the model sees), structured data goes into `meta.structured_data` for programmatic consumption (e.g., by a code execution sandbox).
- **`allowed_callers` forwarding** — Anthropic provider includes `allowed_callers` in the tool definition sent to the API when present, enabling tools to declare whether they can be invoked from a code execution sandbox.
- **`server_tool_use`/`server_tool_result` token counting** — `TokenCounter` now estimates tokens for server tool blocks, preventing compaction from underestimating context size when code execution is in use.
- **Thinking block truncation in compactor** — thinking blocks exceeding the truncation length are sliced during compaction, reducing context size for extended thinking conversations.
- **`Testing.last_text/1` accepts `%State{}`** — delegates to `State.last_assistant_text/1` when given a `%State{}` struct, avoiding redundant reverse-search logic.

### Changed

- **`pending_requests` migrated to `:queue`** — `State.pending_requests` changed from a plain list to an Erlang `:queue` for O(1) enqueue/dequeue. All Server functions (`enqueue_pending_request`, `maybe_start_next_pending`, `remove_pending_request`, `health`) updated accordingly.
- **`agent_event` handler now async** — `handle_info({:agent_event, message})` now dispatches via `start_async_turn/3` (supervised Task) instead of running the Turn synchronously in the GenServer process. Prevents blocking the GenServer mailbox during long-running turns.
- **`handle_info` catchall logs unexpected messages** — the catch-all `handle_info/2` now logs via `Logger.debug/1` instead of silently discarding unknown messages.
- **`on_shutdown` crash logging** — `terminate/2` now logs `Logger.warning` with the exception and stacktrace when `on_shutdown` callbacks crash, instead of silently swallowing.
- **`:after_tool_request` middleware hook** — renamed from `:after_completion` in the tool-use code path. `:after_completion` now fires only on `:end_turn` (final response). `:after_tool_request` gates tool execution.
- **`within_budget?/3` accepts configurable ratio** — third parameter (default `0.9`) replaces the hardcoded 90% budget threshold.
- **SSE parser crash logging** — `SSE.parse_stream` now logs `Logger.warning` with exception message and stacktrace when an event handler crashes, instead of silently recovering.
- **Executor crash logging** — `Executor.run_tagged` now captures `__STACKTRACE__` and logs `Logger.warning` with tool name and stacktrace when a tool crashes.
- **Compactor refactor** — extracted `split_messages/2` to DRY message splitting between `compact/2` and `fire_on_compaction`. The `on_compaction` callback now receives the middle slice directly instead of the full message list + keep_recent count.
- **Executor result dispatch** — `result_block_fn/1` dispatches to `Message.tool_result_block/3` or `Message.server_tool_result_block/3` based on call type, so timeout and crash results also respect the call type.
- **`Message.tool_calls/1`** — now matches both `"tool_use"` and `"server_tool_use"` block types.
- **`Alloy.Tool.execute/2` return type** — widened to `{:ok, String.t()} | {:ok, String.t(), map()} | {:error, String.t()}`.

### Breaking

- **Middleware hook `:after_completion` no longer fires on tool-use responses** — use `:after_tool_request` for middleware that should gate tool execution. `:after_completion` now only fires on `:end_turn` (the model's final response).

## [0.6.0] - 2026-03-02

### Breaking

- **OpenAI provider migrated from Chat Completions to Responses API** — requests now use `/v1/responses` with `input` items and `output` parsing instead of `/v1/chat/completions` with `messages`/`choices`. Streaming uses native SSE handler instead of the removed `OpenAIStream` module. Tool definitions use flat `{type, name, description, parameters}` instead of nested `{type, function: {name, description, parameters}}`.

### Added

- **Fallback providers** — configure `fallback_providers: [{Provider, config}, ...]` to automatically try alternative providers when the primary fails. Respects deadline budgets and never switches mid-stream (once chunks are emitted, the turn sticks with that provider).
- **`on_compaction` callback** — configure `on_compaction: fn messages, state -> ... end` to extract facts from messages about to be compacted. Crash-safe: callback failures are logged but never prevent compaction.

### Fixed

- **Deduplicated `normalize_provider_config/1`** — removed redundant copy from `Turn` module; `Config` now handles all provider config normalization at construction time.
- **Quadratic list concatenation in OpenAI response parsing** — `parse_output_to_blocks/1` now uses O(n) prepend+reverse instead of O(n²) `acc ++ blocks`.
- **Double list traversal in compaction callback** — cached `length(rest)` to avoid traversing the message list twice.
- **Silent callback failures now logged** — `fire_on_compaction` logs `Logger.warning` on callback crashes instead of silently swallowing.

## [0.5.1] - 2026-03-01

### Added

- **Docs coverage gate** — added `mix docs.check` and wired it into CI and publish workflows to enforce `@moduledoc` and `@doc` coverage on public Alloy APIs.

### Fixed

- **Missing test helper docs** — added `@doc` for `Alloy.Testing.assert_tool_called/3` so public test helper macro docs are complete.

## [0.5.0] - 2026-03-01

### Breaking

- **`on_event` contract is now a versioned envelope map** — runtime stream/tool events are emitted as `%{v: 1, seq:, correlation_id:, turn:, ts_ms:, event:, payload:}` instead of tagged tuples.

  Migration example:
  - before: `{:text_delta, chunk}`
  - after: `%{v: 1, event: :text_delta, payload: chunk}`

### Added

- **Unified runtime event protocol** — `:text_delta`, `:thinking_delta`, `:tool_start`, and `:tool_end` now share the same event envelope with deterministic sequencing and correlation IDs.
- **Per-tool lifecycle telemetry** — added `[:alloy, :tool, :start]` and `[:alloy, :tool, :stop]` events with correlation, turn, tool identity, and timing metadata.
- **Per-run runtime telemetry envelope** — added `[:alloy, :event]` with normalized event metadata (`seq`, `event`, `correlation_id`, `turn`).
- **Async request cancellation API** — `Alloy.cancel_request/2` and `Alloy.Agent.Server.cancel_request/2` cancel both queued and in-flight async requests by `request_id`.
- **Bounded async backpressure** — `send_message/3` now supports bounded queuing via `max_pending` and explicit rejections (`:busy`, `:queue_full`).

### Changed

- **`send_message/3` result contract** — now returns `{:ok, request_id}` (instead of bare `:ok`) for robust caller correlation.
- **Async run correlation propagation** — async turns now set event correlation to the async `request_id` by default.
- **Result maps now include `tool_calls` metadata** — one-shot and server flows expose structured tool execution details (`duration_ms`, `error`, correlation and event sequence data).
- **Agent health payload** — now includes queue metrics (`pending_count`, `max_pending`).

## [0.4.3] - 2026-03-01

### Fixed

- **Jason.decode! crash on malformed tool args** — all 6 OpenAI-compatible providers now use `Jason.decode/1` instead of `Jason.decode!/1` when parsing model-produced tool call arguments. Invalid JSON returns `{:error, reason}` instead of crashing the agent GenServer.
- **Multimodal user messages silently dropped** — DeepSeek, Mistral, Ollama, OpenRouter, and XAI providers now correctly format text and image blocks in list-content user messages (previously the `_other -> nil` catch-all discarded them).
- **Tool executor preserves tool_use_id on timeout/crash** — timed-out or crashed tool calls now return the original tool_use_id (was `"unknown"`, which broke provider protocol state).
- **File.stream! on directories** — `Tool.Core.Read` now uses `File.regular?/1` instead of `File.exists?/1`, returning a clean error for directories instead of raising `File.Error`.
- **File.mkdir_p! in Write tool** — replaced with `File.mkdir_p/1` + structured error return on permission failure.
- **One-shot Alloy.run/2 status** — now sets `status: :running` before entering the turn loop, consistent with `Server.chat/3`. Middleware no longer sees `:idle` during execution.
- **Timeout floor overshoot** — `inject_receive_timeout/2` floor reduced from 5,000ms to 1,000ms to prevent HTTP requests from outliving the agent's overall deadline.
- **Scheduler stale callbacks** — `remove_job/2` no longer fires callbacks for in-flight tasks that complete after the job is removed.
- **Context.Discovery cross-platform** — `find_git_root/1` now terminates correctly on all OS filesystem roots (was hardcoded to `"/"`).
- **Message.text/1 consistency** — always returns `String.t()` (never `nil`). Empty text returns `""` instead of `nil`.
- **OpenAI missing usage key** — `parse_response` now handles responses without a `"usage"` field (zero-count fallback) instead of raising `FunctionClauseError`.
- **Google unknown part types** — `parse_parts_to_blocks` now skips unrecognised part shapes instead of raising.

### Changed

- **Credo strict + Dialyzer in CI** — `mix credo --strict` and `mix dialyzer` now run on every push/PR. All 34 pre-existing Credo violations resolved. PLT caching added.
- **Scratchpad Agent cleanup** — `State.cleanup/1` stops the scratchpad process in `terminate/2` and `try/after` blocks. Prevents process leak on crash.
- **O(1) message append** — `State` uses a prepend accumulator (`messages_new`) instead of `++` for O(1) append per turn, materialised at turn boundaries.
- **Float cost precision** — `Usage.estimate_cost/3` uses float division instead of `div/2` to avoid truncating sub-cent costs to zero.
- **Agent :idle status** — `State` default status changed from `:running` to `:idle`. Agents are only `:running` during active turn execution.

## [0.4.2] - 2026-02-28

### Added

- **Extended thinking (Anthropic)** — pass `extended_thinking: [budget_tokens: N]` in provider config to enable Claude's reasoning mode. Thinking blocks are parsed and stored as first-class content (`%{type: "thinking", thinking: text, signature: sig}`) for correct round-trip. Non-Anthropic providers silently ignore this opt.
- **`on_event` streaming callback** — pass `on_event: fn {:text_delta, t} | {:thinking_delta, t} -> :ok end` alongside `on_chunk` to receive tagged stream events. `on_chunk` remains unchanged for backward compatibility. Anthropic emits both `:text_delta` and `:thinking_delta`; all other providers emit only `:text_delta`.
- **Thinking token counting** — `TokenCounter.estimate_block_tokens/1` now counts thinking blocks toward context budget. Prevents compaction from underestimating context size when extended thinking is in use.

### Fixed

- `on_event` now validated as a 1-arity function at `stream_chat/4` call site — invalid values raise `ArgumentError` before reaching the provider instead of crashing deep in the pipeline.
- `extended_thinking: [budget_tokens: nil]` now raises `ArgumentError` immediately rather than sending `null` to the Anthropic API and receiving a cryptic HTTP 400.
- `stream_opts` can no longer override internal `:streaming` and `:on_chunk` flags via `Keyword.merge/2` (previously used `++` which could theoretically be shadowed by user opts).
- `on_event` emissions (thinking deltas) now correctly mark `chunks_emitted?` in the retry guard — previously, a retryable error after a thinking delta but before any text chunk would re-emit the thinking delta on retry.

## [0.4.1] - 2026-02-28

### Added

- **Unified streaming across all 8 providers** — `Alloy.Provider.SSE` now handles all transport-level SSE framing (CRLF normalisation, event boundary splitting, cross-chunk boundary handling). Anthropic, OpenAI, Google, Ollama, OpenRouter, xAI, DeepSeek, and Mistral all stream through the same pipeline. Each provider pattern-matches on parsed events. Adding a new streaming provider is ~50 lines.
- **`send_message/2`** — async non-blocking dispatch for `Alloy.Agent.Server`. Returns `:ok` immediately; the agent runs its Turn loop in a supervised `Task` and broadcasts the result via Phoenix.PubSub when done. Returns `{:error, :busy}` if the agent is mid-turn. Designed for Phoenix LiveView and background jobs that cannot block.
- **`Alloy.Application`** — proper OTP application entry point. Starts `Alloy.TaskSupervisor` (a `Task.Supervisor`) under `Alloy.Supervisor`. Required for `send_message/2`. Add `alloy` to your `extra_applications` list if using an umbrella.
- **Persistence behaviour** — `Alloy.Persistence` defines the formal contract for session persistence backends (`save_session/1`, `load_session/1`, `delete_session/1`, `list_sessions/0`). Alloy itself remains in-memory only — this behaviour is the seam for your own Ecto/SQLite/Redis adapter.

## [0.4.0] - 2026-02-26

### Added

- **Configurable timeouts** — `Server.chat/3`, `Server.stream_chat/4`, `Team.delegate/4`, `Team.broadcast/3`, `Team.handoff/4` all accept `opts \\ []` with `:timeout` (default 120s). Removes all `:infinity` timeouts for daemon safety.
- **Provider retry with backoff** — `Config` now has `max_retries: 3` and `retry_backoff_ms: 1_000`. Retries on HTTP 429/500/502/503/504 and `:timeout` with linear backoff. Non-retryable errors (e.g. 401) fail immediately.
- **Middleware loop halting** — middleware can return `{:halt, reason}` to stop the agent loop. State status becomes `:halted`. Works at all hook points: `before_completion`, `after_completion`, `after_tool_execution`, `on_error`.
- **Cost estimation** — `Usage.estimate_cost/3` computes `estimated_cost_cents` from token counts and per-million prices. `Usage.merge/2` accumulates cost across turns.
- **Streaming as opts** — `Turn.run_loop/2` now accepts `streaming: true, on_chunk: fn` opts directly, eliminating the config mutation hack in `Server.stream_chat`. `:streaming` field removed from `Config`.
- **Export session** — `Server.export_session/1` returns a `%Alloy.Session{}` with messages, usage, and metadata. Session ID sourced from `context[:session_id]` if set.
- **Graceful shutdown** — `Config` accepts `on_shutdown: fn session -> ... end`. Called in `Server.terminate/2`. Combined with `Process.flag(:trap_exit, true)` to ensure callback fires on supervisor shutdown.
- **Pluggable bash executor** — `Alloy.Tool.Core.Bash` checks `context[:bash_executor]` for a custom `(command, working_dir) -> {output, exit_code}` function. Enables Docker sandboxing without modifying Alloy.
- **Health check API** — `Server.health/1` returns `%{status, turns, message_count, usage, uptime_ms}` cheaply without touching the message loop.
- **PubSub integration** — `Alloy.PubSub` wrapper module. Agents can subscribe to topics (`subscribe: ["tasks:new"]`) and react to `{:agent_event, message}` messages. Results broadcast to `"agent:<agent_id>:responses"` using a stable ID (from `context[:session_id]` or auto-generated). `phoenix_pubsub ~> 2.1` is an optional dependency.

### Changed

- `Turn.run_loop/1` → `Turn.run_loop/2` with `opts \\ []` (backward compatible)
- `Config` struct: removed `:streaming`, added `:max_retries`, `:retry_backoff_ms`, `:on_shutdown`, `:pubsub`, `:subscribe`
- `State.status` type: added `:halted`
- `Middleware.call_result` type: added `{:halt, String.t()}`
- `Middleware.run/2` return type: `State.t() | {:halted, String.t()}`
- `phoenix_pubsub` dependency is now optional (users add it to their own `mix.exs`)
- `Team.init/1` returns `{:stop, reason}` instead of raising on agent start failure
- PubSub response topic uses stable `agent_id` (from `context[:session_id]` or auto-generated UUID) instead of volatile PID string
- All `Team` GenServer callbacks now have `@impl GenServer` annotation
- `Executor.execute_all/3` short-circuits middleware checks on halt via `Enum.reduce_while`

### Fixed

- `retryable?/1` now matches OpenAI's native 429 shape (`"rate_limit_exceeded: ..."`) — previously OpenAI rate-limit errors were never retried
- PubSub response topic now uses `effective_session_id/1` (same as `export_session/1`) — topic and session ID no longer diverge when `:session_start` middleware injects `context[:session_id]`
- `retryable?/1` pattern clauses matched tuple shapes that no provider ever returned — rewritten to match actual string error shapes from providers
- `Middleware.run_before_tool_call/2` missing `{:halt, reason}` clause caused `CaseClauseError`
- `Executor.execute_all/3` did not propagate `{:halted, reason}` from `run_before_tool_call`
- `Team.broadcast/3` crashed on `{:exit, reason}` from `Task.async_stream`
- `Team.handoff/4` timed out immediately when called with empty agent list (`timeout * 0 = 0`)
- `Server.terminate/2` used `catch :exit, _` which missed throws — changed to `catch _, _`
- `Server.init/1` did not handle `{:halted, reason}` from `:session_start` middleware
- `Server.handle_call(:chat/:stream_chat)` treated `:halted` status as success — now returns `{:error, result}`
- `Bash` tool missing `{:exit, reason}` clause in `Task.yield` result handling
- `Usage.estimate_cost/3` used float arithmetic causing accumulation errors — converted to integer math
- `Turn.run_loop/2` streaming fallback — `function_exported?/3` returned `false` for unloaded provider modules, silently falling back to non-streaming `complete/3`. Fixed with `Code.ensure_loaded/1` before the capability check.

## [0.3.0] - 2026-02-26

### Added

- `Alloy.Testing` module — ExUnit helpers for testing agents (`run_with_responses`, `assert_tool_called`, `refute_tool_called`, `last_text`, `tool_calls`)
- Usage examples in all 8 provider `@moduledoc` sections
- Expanded `@moduledoc` for all 4 built-in tool modules
- Grouped module sidebar in hex docs (Core, Providers, Tools, Context, Middleware, Advanced, Testing)
- Dialyzer passing with 0 errors

### Fixed

- Dialyzer errors caused by missing `:mix` in PLT (`plt_add_apps: [:mix]`)
- Compile warnings from module attributes in `@moduledoc` strings

## [0.2.0] - 2026-02-26

### Added

- Test coverage for `Session`, `Tool.resolve_path/2`, and `Tool.Executor` (26 new tests)
- Automated hex.pm publish pipeline via GitHub Actions (tag-triggered)

### Changed

- Updated all provider model references to current models (Feb 2026)
- Total test suite: 298 tests

## [0.1.0] - 2026-02-26

### Added

- Core agent loop (`Alloy.run/2`) with configurable max turns
- **8 LLM providers**: Anthropic, OpenAI, Google Gemini, Ollama, OpenRouter, xAI (Grok), DeepSeek, Mistral
- **5 built-in tools**: read, write, edit, bash, scratchpad
- GenServer agent wrapper (`Alloy.Agent.Server`) with supervision support
- Multi-agent teams (`Alloy.Team`) with delegate, broadcast, and handoff
- Streaming responses with provider-level SSE support
- Mid-session model switching
- Context compaction (automatic conversation summarization when approaching token limits)
- Context file auto-discovery (`.alloy/context/*.md`, 3-tier: global/git-root/cwd)
- Skills system (frontmatter parsing, discovery, placeholder expansion)
- Cron/heartbeat scheduler with overlap protection
- Middleware pipeline with telemetry integration
- Extension events (`:before_tool_call` with blocking, `:session_start`, `:session_end`)
- Interactive REPL via `mix alloy`
- Deterministic test provider for full TDD workflows

[0.16.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.16.0
[0.14.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.14.0
[0.13.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.13.0
[0.12.5]: https://github.com/alloy-ex/alloy/releases/tag/v0.12.5
[0.12.4]: https://github.com/alloy-ex/alloy/releases/tag/v0.12.4
[0.12.3]: https://github.com/alloy-ex/alloy/releases/tag/v0.12.3
[0.12.2]: https://github.com/alloy-ex/alloy/releases/tag/v0.12.2
[0.12.1]: https://github.com/alloy-ex/alloy/releases/tag/v0.12.1
[0.12.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.12.0
[0.11.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.11.0
[0.10.2]: https://github.com/alloy-ex/alloy/releases/tag/v0.10.2
[0.10.1]: https://github.com/alloy-ex/alloy/releases/tag/v0.10.1
[0.10.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.10.0
[0.9.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.9.0
[0.8.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.8.0
[0.7.6]: https://github.com/alloy-ex/alloy/releases/tag/v0.7.6
[0.7.5]: https://github.com/alloy-ex/alloy/releases/tag/v0.7.5
[0.7.4]: https://github.com/alloy-ex/alloy/releases/tag/v0.7.4
[0.7.3]: https://github.com/alloy-ex/alloy/releases/tag/v0.7.3
[0.7.2]: https://github.com/alloy-ex/alloy/releases/tag/v0.7.2
[0.7.1]: https://github.com/alloy-ex/alloy/releases/tag/v0.7.1
[0.7.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.7.0
[0.6.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.6.0
[0.5.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.5.0
[0.4.3]: https://github.com/alloy-ex/alloy/releases/tag/v0.4.3
[0.4.2]: https://github.com/alloy-ex/alloy/releases/tag/v0.4.2
[0.4.1]: https://github.com/alloy-ex/alloy/releases/tag/v0.4.1
[0.4.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.4.0
[0.3.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.3.0
[0.2.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.2.0
[0.1.0]: https://github.com/alloy-ex/alloy/releases/tag/v0.1.0
