Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(vibey): continue an Anthropic pause_turn as the same response (#2587)
Call White0ec0d9f7dc86
diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex e7e570b3d..c782f8ba1 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -211,6 +211,8 @@ class StreamAssembler:self._hosted_counts: dict[str, int] = {}self._hosted_cited: tuple[HostedSource, ...] = ()self._hosted_cost: HostedCost | None = None+ #: Whether the response was paused and continues (``pause``).+ self._continuing = Falseself._terminal_seen = Falseself._emitted_output = False# Text or a tool call: output past which a dropped response is never retried.@@ -249,6 +251,11 @@ class StreamAssembler:return self._emitted_outputdef set_origin(self, origin: Origin, verified_origin: bool, source_id: str | None = None) -> None:+ if self._continuing:+ # A continued response is one message (§4.3): verified only when every response in it was, from one origin,+ # and its usage is the latest response's, none if that reports none.+ verified_origin = verified_origin and self.verified_origin and origin == self.origin+ self.usage = Noneself.origin = originself.verified_origin = verified_originself.source_id = source_id@@ -1105,6 +1112,13 @@ class StreamAssembler:hosted_summary=self._hosted_summary(final),)+ def pause(self) -> AssistantMessage | ProviderError:+ """The response so far, as the assistant turn its continuation sends back (§4.3). The continuation's output+ joins the same content, so the response stays one message."""++ self._continuing = True+ return self.finalize("tool_use")+def partial(self, *, stop_reason: str = "error") -> AssistantMessage | None:if self.usage is None and not self._emitted_output:return None@@ -1583,12 +1597,24 @@ PIN_SOURCE_HEADER = "x-avibe-pin-source"PIN_MODEL_HEADER = "x-avibe-pin-model"-class PinUnavailable:- """The gateway's answer to a pinned request it cannot serve from the pinned Source (§3.5): HTTP 409- ``pin_unavailable``, before anything reached a model. ``drive_sse_stream`` yields it in place of a terminal."""+class HandOff:+ """A send that ends without a terminal, because the adapter sends again (§3.5, §4.3). ``drive_sse_stream`` yields+ it in place of a terminal and commits nothing."""++ def __init__(self, reason: str) -> None:+ self.reason = reason+ def __repr__(self) -> str:+ return f"HandOff({self.reason!r})"-PIN_UNAVAILABLE = PinUnavailable()++#: The gateway's answer to a pinned request it cannot serve from the pinned Source (§3.5): HTTP 409+#: ``pin_unavailable``, before anything reached a model.+PIN_UNAVAILABLE = HandOff("pin_unavailable")+#: A response the provider paused (Anthropic ``pause_turn``, §4.3): the adapter continues it as the same response.+PAUSE_TURN = HandOff("pause_turn")+#: An HTTP error the adapter answers by sending again (``drive_sse_stream``'s ``refused``).+REFUSED = HandOff("refused")def _pin_unavailable(body: str) -> bool:@@ -1742,9 +1768,13 @@ async def drive_sse_stream(gateway: bool,translate: WireTranslator,max_line_size: int | None = None,+ refused: Callable[[ProviderError], bool] | None = None,) -> AsyncIterator[Any]:"""Own the complete request/stream/terminal/cleanup lifecycle.+ ``refused`` names an HTTP error the adapter answers by sending again: the driver yields ``REFUSED`` for it in place+ of a terminal, as for ``pin_unavailable``, so nothing the response already holds is lost.+Protocol adapters provide only ``translate``. It receives the shared SSEiterator and yields canonical deltas or a candidate ``Done``/``ProviderError``. The driver commits exactly one terminal event before@@ -1806,6 +1836,9 @@ async def drive_sse_stream(status=response.status_code,headers=response.headers,)+ if refused is not None and refused(candidate):+ yield REFUSED+ returnelse:resolved_origin = await resolve_served_origin(endpoint,@@ -1823,6 +1856,8 @@ async def drive_sse_stream(candidate = itembreakyield item+ if isinstance(item, HandOff):+ returnif candidate is None:candidate = (assembler.aborted(cancel.reason)diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex 4ff642822..897eed82b 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -12,6 +12,7 @@ import jsonimport loggingimport refrom collections.abc import AsyncIterator, Mapping+from dataclasses import replacefrom typing import Anyimport httpx@@ -26,7 +27,10 @@ from core.agent_core.ai._common import (dispatch_wire_event,endpoint_origin,hosted_pin,+ PAUSE_TURN,+ PIN_SOURCE_HEADER,PIN_UNAVAILABLE,+ REFUSED,portable_request,join_endpoint_url,json_object,@@ -57,12 +61,18 @@ from core.agent_core.messages import (ThinkingBlock,ToolCallBlock,ToolResultMessage,+ Usage,UserMessage,)logger = logging.getLogger(__name__)ANTHROPIC_VERSION = "2023-06-01"+#: How many times one response may be continued after the provider paused it (``vibey-hosted-tools.md`` §4.3).+MAX_PAUSE_CONTINUATIONS = 5+PAUSE_LIMIT_MESSAGE = f"the provider paused the turn more than {MAX_PAUSE_CONTINUATIONS} times"+#: A paused response continues only on the Source that served it, pinned there (§4.3 as implemented).+PAUSE_UNSERVED_MESSAGE = "the Source that served the paused turn cannot continue it"_MAX_CACHE_BREAKPOINTS = 4# A Claude route caches its static prefix, the tools and then the system prompt, for an hour (``_prefix_ttl``); the# conversation's breakpoints keep the default five minutes. Anthropic evaluates breakpoints as tools, system, messages@@ -256,9 +266,22 @@ class AnthropicAdapter(ProviderAdapter):hosted = frozenset(native_hosted_tools(request))# Each hosted call's ``server_tool_use`` by stream index; its input JSON streams into the assembler.uses: dict[int, dict[str, Any]] = {}+ # A paused response continues as the same one (§4.3): a continuation's blocks follow the paused ones, its hosted+ # counters add to theirs, and its usage, the final request's, stands for the whole response.+ paused = False+ offset = next_index = 0+ response_usage: Usage | None = None+ carried_counts: dict[str, int] = {}+ response_counts: dict[str, int] = {}++ def block_index(chunk: Mapping[str, Any]) -> int | None:+ index = _stream_index(chunk)+ return None if index is None else index + offset+try:async def translate(events: AsyncIterator[Any]) -> AsyncIterator[Any]:- nonlocal message_started, message_stopped, stop_reason+ nonlocal message_started, message_stopped, stop_reason, paused, next_index, response_usage+ nonlocal response_countsasync for event in events:if cancel.cancelled:terminal = assembler.terminal(assembler.aborted(cancel.reason))@@ -360,14 +383,16 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn- assembler.set_usage(- _anthropic_usage(message.get("usage"))- )+ # Each response's own usage: the last request's input already holds every paused part, so+ # it is the context the merged response stands for (plan §4.3 as implemented).+ response_usage = _anthropic_usage(message.get("usage"))+ assembler.set_usage(response_usage)start_usage = message.get("usage")if isinstance(start_usage, Mapping) and "server_tool_use" in start_usage:- assembler.set_hosted_facts(counts=reported_counts(start_usage.get("server_tool_use")))+ response_counts = reported_counts(start_usage.get("server_tool_use"))+ assembler.set_hosted_facts(counts=_summed(carried_counts, response_counts))elif event_type == "content_block_start":- index = _stream_index(chunk)+ index = block_index(chunk)if index is None:terminal = assembler.terminal(assembler.error("content_block_start index must be an integer", kind="invalid_request")@@ -375,6 +400,7 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn+ next_index = max(next_index, index + 1)block = chunk.get("content_block")if not isinstance(block, Mapping):terminal = assembler.terminal(@@ -544,7 +570,7 @@ class AnthropicAdapter(ProviderAdapter):if isinstance(initial_input, Mapping):assembler.set_tool_arguments_object(index, initial_input)elif event_type == "content_block_delta":- index = _stream_index(chunk)+ index = block_index(chunk)if index is None:terminal = assembler.terminal(assembler.error("content_block_delta index must be an integer", kind="invalid_request")@@ -661,7 +687,7 @@ class AnthropicAdapter(ProviderAdapter):# Pi ignores delta variants it does not know yet.# Known event shape has already been validated above.elif event_type == "content_block_stop":- index = _stream_index(chunk)+ index = block_index(chunk)if index is None:terminal = assembler.terminal(assembler.error("content_block_stop index must be an integer", kind="invalid_request")@@ -734,10 +760,13 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn+ paused = delta.get("stop_reason") == "pause_turn"stop_reason = _normalize_stop_reason(delta.get("stop_reason"))- assembler.set_usage(_anthropic_usage(usage, current=assembler.usage))+ response_usage = _anthropic_usage(usage, current=response_usage)+ assembler.set_usage(response_usage)if isinstance(usage, Mapping) and "server_tool_use" in usage:- assembler.set_hosted_facts(counts=reported_counts(usage.get("server_tool_use")))+ response_counts = reported_counts(usage.get("server_tool_use"))+ assembler.set_hosted_facts(counts=_summed(carried_counts, response_counts))elif event_type == "error":shape_error = _error_event_shape_error(chunk)if shape_error is not None:@@ -767,6 +796,9 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalreturn+ if paused:+ yield PAUSE_TURN+ returnfinal = assembler.finalize(stop_reason or ("tool_use" if assembler.has_tools() else "stop"))@@ -787,6 +819,9 @@ class AnthropicAdapter(ProviderAdapter):yield terminalreturnif stop_reason is not None:+ if paused:+ yield PAUSE_TURN+ returnfinal = assembler.finalize(stop_reason)terminal = assembler.terminal(final if isinstance(final, ProviderError) else Done(final)@@ -798,6 +833,7 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalsending = request+ continuations = 0while True:# The lifetime ``wire_request`` gives the prefix: the default once this route has rejected the field.prefix_ttl = _prefix_ttl(sending)@@ -814,14 +850,20 @@ class AnthropicAdapter(ProviderAdapter):resolver=self._served_hop_resolver,gateway=self._gateway,translate=translate,+ # The endpoint refused the lifetime before answering: sent again below, with nothing lost.+ refused=_rejects_ttl if prefix_ttl is not None else None,)- rejected = unavailable = False+ rejected = unavailable = continued = paused = message_started = message_stopped = False+ stop_reason = Nonetry:async for event in driver:if event is PIN_UNAVAILABLE:unavailable = Truebreak- if prefix_ttl is not None and _rejects_ttl(event):+ if event is PAUSE_TURN:+ continued = True+ break+ if event is REFUSED:rejected = Truebreakyield event@@ -831,30 +873,63 @@ class AnthropicAdapter(ProviderAdapter):# The pinned Source cannot serve this content: the same request once more, in portable form and# unpinned, which the gateway fails over as any other (§3.5). Never the generic retry.sending = portable_request(request)- hosted = frozenset()- prepared = await prepare_messages(- sending.messages,- target=origin,- supports_images=sending.supports_images,- protocol=self.protocol,- media_loader=self._media_loader,- cancel=cancel,- endpoint=sending.endpoint,- )- if isinstance(prepared, ProviderError):- terminal = assembler.terminal(prepared)+ elif unavailable or (+ continued+ and self._gateway+ and (PIN_SOURCE_HEADER not in wire.headers or not assembler.verified_origin)+ ):+ # A paused response continues only on the Source that served it, pinned, so it stays one origin's+ # message: a continuation that Source cannot serve, a send no pin held there, or a response whose+ # Source is unknown (no served-hop report, so its hosted calls could not be kept and sent back) ends+ # the response with what it has (§4.3 as implemented).+ terminal = assembler.terminal(assembler.error(PAUSE_UNSERVED_MESSAGE, kind="interrupted"))+ if terminal is not None:+ yield terminal+ return+ elif continued:+ # The provider paused the turn: send its content back as it is, with no new user message, pinned to+ # the Source and model that served it, and keep streaming the same response, at most+ # MAX_PAUSE_CONTINUATIONS times (§4.3).+ if continuations == MAX_PAUSE_CONTINUATIONS:+ terminal = assembler.terminal(assembler.error(PAUSE_LIMIT_MESSAGE, kind="interrupted"))+ if terminal is not None:+ yield terminal+ return+ so_far = assembler.pause()+ if isinstance(so_far, ProviderError):+ terminal = assembler.terminal(so_far)if terminal is not None:yield terminalreturn- transformed_messages, loaded_images = prepared- assembler = new_assembler()+ continuations += 1+ response_usage = None+ carried_counts, response_counts = _summed(carried_counts, response_counts), {}+ offset = next_index+ sending = replace(sending, messages=(*request.messages, so_far))+ elif rejected:+ # The endpoint refused the lifetime before answering, so nothing reached the consumer: the same+ # send once more with the default lifetime, which this route keeps from now on.+ _remember_ttl_rejection(sending.endpoint)continue- if not rejected:+ else:+ return+ hosted = frozenset(native_hosted_tools(sending))+ prepared = await prepare_messages(+ sending.messages,+ target=origin,+ supports_images=sending.supports_images,+ protocol=self.protocol,+ media_loader=self._media_loader,+ cancel=cancel,+ endpoint=sending.endpoint,+ )+ if isinstance(prepared, ProviderError):+ # A paused response keeps what it streamed, as a failed continuation request does.+ terminal = assembler.terminal(replace(prepared, partial=prepared.partial or assembler.partial()))+ if terminal is not None:+ yield terminalreturn- # The endpoint refused the request before answering, so the consumer saw nothing: send it once more- # with the default lifetime, which this route keeps from now on.- _remember_ttl_rejection(request.endpoint)- assembler = new_assembler()+ transformed_messages, loaded_images = preparedexcept Exception as exc:terminal = assembler.terminal(assembler.exception(exc))if terminal is not None:@@ -1155,11 +1230,17 @@ def _usage(input_tokens: int = 0, output_tokens: int = 0, cache_read: int = 0, c)+def _summed(counts: Mapping[str, int], more: Mapping[str, int]) -> dict[str, int]:+ summed = dict(counts)+ for name, value in more.items():+ summed[name] = summed.get(name, 0) + value+ return summed++def _normalize_stop_reason(value: Any) -> str:normalized = {"end_turn": "stop","stop_sequence": "stop",- "pause_turn": "stop","max_tokens": "length",# Generation reached the context window (Claude 4.5 and newer accept input plus max_tokens over the window);# Anthropic says to treat the response as truncated, as at max_tokens.diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 540fcad5b..89c3c63f7 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -538,7 +538,8 @@ Anthropic stop reasons:| Wire value | Canonical || --- | --- |-| `end_turn`, `stop_sequence`, `pause_turn` | `stop` |+| `end_turn`, `stop_sequence` | `stop` |+| `pause_turn` | none: the response continues (Hosted tools, `pause_turn`) || `max_tokens`, `model_context_window_exceeded` | `length` || `tool_use` | `tool_use` || `refusal` | `refusal` |@@ -679,9 +680,7 @@ far:base64 comes back beside its record and is saved through the same `MediaSink` as a native one; the record lists thefile.-Still to come: `pause_turn`.-Until `pause_turn` lands, the Anthropic stop table above still maps it to `stop`. An Anthropic citation covers its-whole text block, so it carries no range.+An Anthropic citation covers its whole text block, so it carries no range.| Concern | Anthropic Messages | OpenAI Responses (OpenAI, xAI) | OpenAI Chat Completions || --- | --- | --- | --- |@@ -693,7 +692,7 @@ whole text block, so it carries no range.| Same-Source replay (target hop is `native.source_id`, same origin, and `hosted_tools[tool].replay` is true now) | `native.payload` blocks verbatim, in place; citations not sent | `native.payload` items verbatim, in place; annotations not sent; never for `image_generation` | — || Images | — | `image_generation_call` → a file saved through the `MediaSink` from its `output_item.done`. The record lists it as a `HostedImage`: absolute path, mime type sniffed from its bytes, the item's size as width and height, and the file's byte count. The action is `generate` with the revised prompt and the resolved size and quality. `native.payload` holds the path in place of `result`, so no base64 is ever stored. `partial_image` previews are skipped before parsing. The duplicate `result` in the terminal response is never decoded, and a call that saved no image is `failed`. The model reads the path record, and a file over `read`'s inline limit says so. A stream that declares `image_generation` gets the 32 MiB event cap as its line cap; others keep 8 MiB. | — || Other-origin replay | assistant `tool_use(name=<tool>, input=<per-action arguments>)` + user `tool_result(record as text)`, splitting the assistant message; a `failed`/`incomplete` record sets `is_error: true` | `function_call(name=<tool>, arguments)` + `function_call_output(record as text)`; a failed record's text starts `[<tool> failed: <error>]` | assistant `tool_calls` + `tool` message, failure as in Responses |-| Pinning (any protocol) | a request with a native declaration or a verbatim `native.payload` carries `x-avibe-pin-source: <hop source_id>`. A continuation whose calls go back verbatim also carries `x-avibe-pin-model: <its served model>`, the hop's own model. A `409` `model_hub_pin_unavailable` / `pin_unavailable` answer is not shown: the same request is rendered again in portable form (proxy declarations, synthetic history, in-place text) and sent unpinned, exactly once. | same | — |+| Pinning (any protocol) | a request with a native declaration or a verbatim `native.payload` carries `x-avibe-pin-source: <hop source_id>`. A continuation whose calls go back verbatim also carries `x-avibe-pin-model: <its served model>`, the hop's own model. A `409` `model_hub_pin_unavailable` / `pin_unavailable` answer is not shown: the same request is rendered again in portable form (proxy declarations, synthetic history, in-place text) and sent unpinned, exactly once. A `pause_turn` continuation is the exception (below). | same | — || Citations at delivery | `TextBlock.citations` → `core/citations.py` builder → Markdown links + Web sidecar | same | — |-| `pause_turn` | not a stop: the adapter re-sends the request with the paused assistant content appended (no new user message), pinned to the paused response's Source (`x-avibe-pin-source`), and keeps streaming as one response, at most 5 continuations. `usage` is the sum of every continuation's counters. | — | — |+| `pause_turn` | not a stop. The adapter sends the request again with the paused content appended as the last assistant message, with no new user message. That continuation goes to the same hop, pinned to the Source and model that served the paused response, and its output streams on as the same response. A continuation block's index follows the paused ones, and a result finalizes its pending call by id. The hosted counters and cost are summed over every response. `usage` is the final request's, whose input already holds every paused part, so the context estimate stays right; billing comes from the gateway's per-call metering. After 5 continuations, a sixth pause ends the response with one `interrupted` error whose partial keeps everything assembled. A continuation is never sent in portable form. One that Source answers `pin_unavailable`, or a pause of a send that carried no pin, ends the response the same way. The merged message is verified only when every response in it was verified and reported the same origin; otherwise it is sanitized as any unverified response. | — | — || In-flight replay (same turn, pinned Source) | verbatim when the fresh hop is the Source that served it, else in place as text. On `pin_unavailable`, which the gateway also answers for a narrow rejection of the replayed content (§3.5), each server block pair is replaced in place by one text block; signed thinking is kept on the same origin. | same | — |diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex 2a61f3bef..9f15b5d02 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -360,6 +360,15 @@ as a half-open code-point range into `text`.- Each continuation is pinned to the Source the paused response came from (§3.5). On `pin_unavailable`, thecontinuation is re-rendered in portable form, with the paused server blocks converted in place (§4.4), and goesout unpinned.+ - **As implemented (orchestrator decision, 2026-10-14):** a continuation goes only to the Source that served the+ paused response, pinned there, and is never re-rendered in portable form. A continuation that Source answers+ `pin_unavailable`, or a pause of a send that carried no pin, ends the response with one terminal+ `ProviderError(kind="interrupted")` whose partial keeps all assembled content, as at the bound. The merged+ message is then always one origin's, so no paused part needs a stored form other than the one it streamed in.+ The merged message is verified only when every response in it was verified and reported the same origin;+ otherwise it is sanitized as any unverified response. The case given up is rare: the pinned Source becoming+ unavailable seconds into a paused turn. The user keeps the partial answer and can retry. A turn's first request+ still gets its one portable resend on `pin_unavailable` (§3.5).- **After the 5th continuation**, if the response is still `pause_turn`, the adapter ends with one terminal`ProviderError(kind="interrupted")`. Its partial keeps all assembled content and the summed usage, and its`error_message` is "the provider paused the turn more than 5 times". C-2's existing rule then applies: terminal@@ -369,6 +378,12 @@ as a half-open code-point range into `text`.- Its `usage` is the **sum** of every continuation response's counters: input, output, and cache read and write.Today's parser resets usage at each `message_start`. The gateway already meters each continuation as its owncall, so the usage ledger and provenance need no change.+ - **As implemented (orchestrator decision, 2026-10-14):** the merged message carries the **final** continuation's+ usage, not the sum. The context estimate anchors on a response's usage as the size of the request that produced+ it, and the final request's input already holds every paused part, so a sum would roughly double the next+ estimate. Billing and the ledger come from the gateway's per-call metering, and `hosted_summary` still sums+ counts and cost across continuations. Vibey-side token sums that read message usage, such as side-turn audit+ totals, undercount the earlier continuations.- **Pending calls carry over by id.** The adapter keeps its hosted blocks keyed by tool-call id acrosscontinuations. A result arriving in a continuation for a `pending` block finalizes that block, its `record` andits `native.payload`, so each call stays exactly one block.@@ -675,9 +690,10 @@ Each has a **Re-verify** action with its cost. Unknown shows nothing.the same for either mode. One function renders a record to model-facing text, for proxied results and forsynthetic replay alike. A failed record never renders as a successful empty result.5. Any transcript with hosted calls replays to any supported target without a history-shape error.-6. `pause_turn` never ends a turn. Continuations are bounded, pinned to the paused response's Source, merged into- one message, and their usage is summed. Past the bound, the turn ends with one `interrupted` error that keeps- the partial.+6. `pause_turn` never ends a turn while its Source can continue it. Continuations are bounded, pinned to the+ paused response's Source, and merged into one message that carries the final request's usage and summed hosted+ counters (§4.3 as implemented). Past the bound, or when that Source cannot continue it, the turn ends with one+ `interrupted` error that keeps the partial.7. A generated image never enters model context or history as bytes. The model gets the text path record, and theuser sees the image.8. A Codex CLI request reaches the upstream with exactly the image tool CPA would have injected. No other caller@@ -696,7 +712,7 @@ shapes. No live upstream and no real credentials.| --- | --- | --- || Adapter parsing | each adapter against stub SSE | the mapping rule, one case per row of §4.2's table, including `queries[]` versus the deprecated `query`, every xAI X-search variant, and an unknown item becoming `other`; `hosted_summary` with one and with several X searches (reported cost once, no per-call copies); Anthropic citations; pending `server_tool_use` at `pause_turn`; a hosted call that fails || Cross-provider transform | `ai` request builders | each hosted block to each target, verified same Source versus other: native verbatim, synthetic call/result, split assistant message; citations never sent |-| `pause_turn` | Anthropic adapter, stub returns `pause_turn`, then `end_turn` | one logical response; the bound; the merged message with summed usage; the pin header; `pin_unavailable` falls back to the in-place text form |+| `pause_turn` | Anthropic adapter, stub returns `pause_turn`, then `end_turn` | one logical response; the bound; the merged message with the final request's usage and summed hosted counters; the pin header; `pin_unavailable` on a continuation ends `interrupted` with the partial (§4.3 as implemented) || Gateway selection and pinning | real gateway + loopback fake engine | native only with evidence and an eligible credential; a pinned request is never failed over; an inadmissible pinned Source and a pre-output failure both answer `pin_unavailable`; Vibey's portable re-render is then served by failover; `x_search` to OpenAI never sent || Evidence | classifier against recorded error bodies | `400 Unsupported tool type`, `invalid_value` effort and `Invalid encrypted_content` each create exactly one record; overload and 5xx create none || Proxy executor | gateway endpoint, stub provider | executor choice; no effort sent; the record with excerpts; metering on the executor Source; error when no executor is verified; refusal of a Claude subscription |@@ -789,6 +805,9 @@ encoded either as a schema clause or as a producer test. The PR names which for`pin_unavailable` continuation served by another origin makes the merged message take the serving origin, andthe paused part is kept in the portable form that was actually sent (§4.4 fallback, C-1 cross-origin rules), sono payload or signature from the first origin remains.+ **As implemented (orchestrator decision, 2026-10-14):** there is no portable continuation, so no cross-origin+ merge (§4.3). A continuation whose response reports another origin, or none, leaves the merged message+ unverified, so it keeps no payload or signature of any response.22. The `generate` action records the output's resolved `quality` and `size`; pricing uses those output values, notthe declaration's.23. The replay probe asks for a URL the call probe actually returned (such as the first). An answer with no earlierdiff --git a/tests/agent_core/ai/test_hosted_pause_turn.py b/tests/agent_core/ai/test_hosted_pause_turn.pynew file mode 100644index 000000000..cab66e4bd--- /dev/null+++ b/tests/agent_core/ai/test_hosted_pause_turn.py@@ -0,0 +1,316 @@+"""Anthropic ``pause_turn`` (``vibey-hosted-tools.md`` §4.3). Scenario MH-HOSTED-VIBEY-006.++A paused response is not a stop. The adapter sends its content back as it is, with no new user message, pinned to the+Source and model that served it, and keeps streaming the same response: one message of one origin, its pending call+finalized by id, its hosted counters summed. Past five continuations, or when that Source cannot continue it, it ends+``interrupted`` and keeps what it has.+"""++from __future__ import annotations++import json+from dataclasses import replace+from typing import Any, Callable++import httpx+import pytest++from core.agent_core.ai._common import PIN_MODEL_HEADER, PIN_SOURCE_HEADER+from core.agent_core.ai.anthropic import MAX_PAUSE_CONTINUATIONS, PAUSE_LIMIT_MESSAGE, PAUSE_UNSERVED_MESSAGE+from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest, ProviderError+from core.agent_core.ai.registry import create_adapter+from core.agent_core.cancel import CancelToken+from core.agent_core.messages import HostedToolBlock, ImageBlock, TextBlock, ThinkingBlock, Usage, UserMessage+from core.agent_core.tools.hosted import hosted_tool_spec++SOURCE = "src_served00001"+MODEL = "claude-opus-5-5"+DECLARATION = {"type": "web_search_20250305", "name": "web_search"}+USE = {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {}}+RESULT = {+ "type": "web_search_tool_result",+ "tool_use_id": "srvtoolu_1",+ "content": [{"type": "web_search_result", "url": "https://avibe.bot/r", "title": "R", "encrypted_content": "opaque"}],+}+_PIN_UNAVAILABLE = {"type": "error", "error": {"type": "model_hub_pin_unavailable", "code": "pin_unavailable"}}+++def _request(*, cache: str = "none", base_url: str = "http://hub.invalid/vibey/v1") -> ModelRequest:+ route = HostedToolRoute("native", None, False, declaration=DECLARATION)+ return ModelRequest(+ endpoint=ModelEndpoint(+ "anthropic",+ base_url,+ MODEL,+ "hub-token",+ provider="anthropic",+ source_id=SOURCE,+ hosted_tools={"web_search": route},+ ),+ system="system",+ messages=(UserMessage((TextBlock("search, then search again"),)),),+ tools=(hosted_tool_spec("web_search"),),+ max_tokens=256,+ cache=cache, # type: ignore[arg-type]+ )+++def _response(+ *blocks: list[dict[str, Any]],+ stop_reason: str,+ input_tokens: int,+ output_tokens: int,+ searches: int = 0,+ framed: bool = True,+) -> str:+ """A Messages stream; one not ``framed`` has no ``message_start`` or ``message_stop`` and ends at a clean EOF."""++ events: list[dict[str, Any]] = [{"type": "message_start", "message": {"usage": {"input_tokens": input_tokens}}}]+ for index, frames in enumerate(blocks):+ events.extend({**frame, "index": index} for frame in frames)+ events.append({"type": "content_block_stop", "index": index})+ usage: dict[str, Any] = {"output_tokens": output_tokens}+ if searches:+ usage["server_tool_use"] = {"web_search_requests": searches}+ events.append({"type": "message_delta", "delta": {"stop_reason": stop_reason}, "usage": usage})+ events.append({"type": "message_stop"})+ if not framed:+ events = events[1:-1]+ return "".join(f"data: {json.dumps(event)}\n\n" for event in events)+++def _use() -> list[dict[str, Any]]:+ return [+ {"type": "content_block_start", "content_block": USE},+ {"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": '{"query": "avibe release"}'}},+ ]+++def _text(text: str) -> list[dict[str, Any]]:+ return [+ {"type": "content_block_start", "content_block": {"type": "text", "text": ""}},+ {"type": "content_block_delta", "delta": {"type": "text_delta", "text": text}},+ ]+++def _thinking() -> list[dict[str, Any]]:+ return [+ {"type": "content_block_start", "content_block": {"type": "thinking", "thinking": ""}},+ {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "plan"}},+ {"type": "content_block_delta", "delta": {"type": "signature_delta", "signature": "signed-by-opus"}},+ ]+++def _served(model: str = MODEL, source: str = SOURCE, *, reported: bool = True) -> dict[str, str]:+ if not reported:+ return {"content-type": "text/event-stream"}+ report = {"provider": "anthropic", "api": "anthropic", "model": model, "source": source}+ return {"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(report, separators=(",", ":"))}+++async def _stream(+ answer: Callable[[int], httpx.Response], request: ModelRequest | None = None, media_loader: Any = None+) -> tuple[list[httpx.Request], list[Any]]:+ sent: list[httpx.Request] = []++ def gateway(wire: httpx.Request) -> httpx.Response:+ sent.append(wire)+ return answer(len(sent))++ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ adapter = create_adapter("anthropic", client=client, gateway=True, media_loader=media_loader)+ events = [event async for event in adapter.stream(request or _request(), CancelToken())]+ return sent, events++[email protected]("framed", [True, False], ids=["framed", "clean-eof"])+async def test_a_paused_response_continues_as_one_response_pinned_to_its_source_with_summed_counters(framed):+ """MH-HOSTED-VIBEY-006: the continuation sends the paused content back as it is, with no new user message, pinned+ to the Source and model that served it; the result that arrives finalizes the pending call by its id. A paused+ stream that ends at a clean EOF continues as one that sent ``message_stop``."""++ def answer(number: int) -> httpx.Response:+ if number == 1:+ body = _response(+ _use(), stop_reason="pause_turn", input_tokens=100, output_tokens=10, searches=1, framed=framed+ )+ else:+ body = _response([{"type": "content_block_start", "content_block": RESULT}], _text("v8 is out"),+ stop_reason="end_turn", input_tokens=300, output_tokens=20, searches=1)+ return httpx.Response(200, headers=_served(), text=body)++ sent, events = await _stream(answer)++ assert len(sent) == 2+ first, continued = (json.loads(wire.content) for wire in sent)+ assert continued["messages"][:-1] == first["messages"]+ assert continued["messages"][-1] == {+ "role": "assistant",+ "content": [{**USE, "input": {"query": "avibe release"}}],+ }+ assert sent[1].headers[PIN_SOURCE_HEADER] == SOURCE and sent[1].headers[PIN_MODEL_HEADER] == MODEL+ message = events[-1].message+ assert isinstance(events[-1], Done) and message.stop_reason == "stop"+ (call,) = [block for block in message.content if isinstance(block, HostedToolBlock)]+ assert call.id == "srvtoolu_1" and call.record.status == "completed"+ assert [source.url for source in call.record.sources] == ["https://avibe.bot/r"]+ assert call.native.payload == ({**USE, "input": {"query": "avibe release"}}, RESULT)+ assert [block.text for block in message.content if isinstance(block, TextBlock)] == ["v8 is out"]+ # The final request already re-sent every paused part: its usage is the response's context (§4.3 as implemented).+ assert message.usage == Usage(input_tokens=300, output_tokens=20)+ assert dict(message.hosted_summary.counts) == {"web_search_requests": 2}+ assert not [event for event in events if isinstance(event, ProviderError)]+++async def test_a_continuation_that_reports_no_usage_leaves_the_message_without_the_paused_requests():+ """The merged message's usage stands for the final request; a final response that reports none leaves it unknown,+ never the smaller paused request's."""++ def answer(number: int) -> httpx.Response:+ if number == 1:+ body = _response(_text("part 1"), stop_reason="pause_turn", input_tokens=100, output_tokens=10)+ else:+ events = [+ {"type": "message_start", "message": {}},+ *({**frame, "index": 0} for frame in _text("done")),+ {"type": "content_block_stop", "index": 0},+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}},+ {"type": "message_stop"},+ ]+ body = "".join(f"data: {json.dumps(event)}\n\n" for event in events)+ return httpx.Response(200, headers=_served(), text=body)++ sent, events = await _stream(answer)++ message = events[-1].message+ assert len(sent) == 2 and isinstance(events[-1], Done)+ assert [block.text for block in message.content if isinstance(block, TextBlock)] == ["part 1", "done"]+ assert message.usage is None+++async def test_a_response_paused_past_the_bound_ends_interrupted_and_keeps_everything_it_assembled():+ def answer(number: int) -> httpx.Response:+ body = _response(_text(f"step {number}"), stop_reason="pause_turn", input_tokens=10, output_tokens=1)+ return httpx.Response(200, headers=_served(), text=body)++ sent, events = await _stream(answer)++ assert len(sent) == 1 + MAX_PAUSE_CONTINUATIONS+ error = events[-1]+ assert isinstance(error, ProviderError) and error.kind == "interrupted" and error.message == PAUSE_LIMIT_MESSAGE+ assert [block.text for block in error.partial.content] == [f"step {n}" for n in range(1, len(sent) + 1)]+ assert error.partial.usage == Usage(input_tokens=10, output_tokens=1)+ assert sum(isinstance(event, (Done, ProviderError)) for event in events) == 1+++ ("unavailable", "reported", "sends", "kept"),+ [(2, True, 2, "part 1"), (1, True, 2, "part 2"), (None, False, 1, "part 1")],+ ids=["continuation-pin-unavailable", "paused-unpinned-send", "paused-unverified-response"],+)+async def test_a_paused_response_its_source_cannot_continue_ends_interrupted_and_keeps_what_it_has(+ unavailable, reported, sends, kept+):+ """§4.3 as implemented: a continuation goes only to the Source that served the paused response, pinned, so the+ response stays one origin's message. It ends without another send when:+ - that Source answers the continuation ``pin_unavailable``;+ - the paused send carried no pin (the turn's portable resend);+ - the paused response named no Source, so its hosted calls could not be kept to send back."""++ def answer(number: int) -> httpx.Response:+ if number == unavailable:+ return httpx.Response(409, json=_PIN_UNAVAILABLE)+ body = _response(_text(f"part {number}"), stop_reason="pause_turn", input_tokens=10, output_tokens=1)+ return httpx.Response(200, headers=_served(reported=reported), text=body)++ sent, events = await _stream(answer)++ assert len(sent) == sends+ error = events[-1]+ assert isinstance(error, ProviderError) and error.kind == "interrupted" and error.message == PAUSE_UNSERVED_MESSAGE+ assert [block.text for block in error.partial.content if isinstance(block, TextBlock)] == [kept]+ assert sum(isinstance(event, (Done, ProviderError)) for event in events) == 1+++async def test_a_continuation_whose_route_refuses_the_cache_lifetime_is_sent_again_and_keeps_what_it_has():+ """The 1-hour cache lifetime a continuation's route refuses is dropped and the same continuation sent once more,+ as for a first request; the response keeps its paused content."""++ rejection = {"type": "error", "error": {"type": "invalid_request_error", "message": "system.0.cache_control.ttl: Extra inputs are not permitted"}}++ def answer(number: int) -> httpx.Response:+ if number == 2:+ return httpx.Response(400, json=rejection)+ stop = "pause_turn" if number == 1 else "end_turn"+ body = _response(_text(f"part {number}"), stop_reason=stop, input_tokens=10, output_tokens=1)+ return httpx.Response(200, headers=_served(), text=body)++ import uuid++ request = _request(cache="default", base_url=f"http://{uuid.uuid4().hex}.invalid/vibey/v1")+ sent, events = await _stream(answer, request)++ first, refused, retried = (json.loads(wire.content) for wire in sent)+ assert '"ttl"' in json.dumps(refused) and '"ttl"' not in json.dumps(retried)+ assert refused["messages"] == retried["messages"]+ message = events[-1].message+ assert [block.text for block in message.content if isinstance(block, TextBlock)] == ["part 1", "part 3"]+ assert message.usage == Usage(input_tokens=10, output_tokens=1)+++ ("first", "second"),+ [+ ({}, {"reported": False}),+ ({}, {"model": "claude-sonnet-5-5"}),+ ],+ ids=["then-unverified", "another-origin"],+)+async def test_a_continued_response_is_verified_only_when_every_response_in_it_was_from_one_origin(first, second):+ """A continuation with no served-hop report, or one another origin served, makes the whole message unverified: no+ signature of any part is kept, the paused part's included."""++ def answer(number: int) -> httpx.Response:+ if number == 1:+ body = _response(_thinking(), _text("part 1"), stop_reason="pause_turn", input_tokens=10, output_tokens=1)+ return httpx.Response(200, headers=_served(**first), text=body)+ body = _response(_thinking(), _text("done"), stop_reason="end_turn", input_tokens=10, output_tokens=1)+ return httpx.Response(200, headers=_served(**second), text=body)++ sent, events = await _stream(answer)++ message = events[-1].message+ assert len(sent) == 2 and isinstance(events[-1], Done)+ thinking = [block for block in message.content if isinstance(block, ThinkingBlock)]+ assert len(thinking) == 2 and all(block.signature is None for block in thinking)+++async def test_a_paused_response_whose_continuation_cannot_be_prepared_keeps_what_it_streamed():+ """A continuation that fails before it is sent (here an image of the turn that no longer loads) ends the response+ with an error that keeps the paused part, as a failed continuation request does."""++ loads = []++ class Media:+ async def load(self, media_token: str) -> tuple[bytes, str]:+ loads.append(media_token)+ if len(loads) > 1:+ raise RuntimeError("media snapshot is gone")+ return b"\x89PNG\r\n\x1a\n", "image/png"++ def answer(number: int) -> httpx.Response:+ body = _response(_text("part 1"), stop_reason="pause_turn", input_tokens=10, output_tokens=1)+ return httpx.Response(200, headers=_served(), text=body)++ request = _request()+ request = replace(+ request,+ messages=(UserMessage((TextBlock("look and search"), ImageBlock("image/png", "tok_1"))),),+ supports_images=True,+ )+ sent, events = await _stream(answer, request, media_loader=Media())++ error = events[-1]+ assert len(sent) == 1 and isinstance(error, ProviderError)+ assert [block.text for block in error.partial.content if isinstance(block, TextBlock)] == ["part 1"]+ assert error.partial.usage == Usage(input_tokens=10, output_tokens=1)diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 191fa117e..c878ea878 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -59,6 +59,7 @@ capabilities:- tests/agent_core/ai/test_hosted_transform.py- tests/agent_core/ai/test_hosted_replay.py- tests/agent_core/ai/test_hosted_images.py+ - tests/agent_core/ai/test_hosted_pause_turn.py- tests/test_vibey_agent.py- tests/test_model_hub_evidence_rules.py- tests/test_model_hub_admission.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 05ee7b833..ba8c63253 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -17,6 +17,7 @@ capability:- tests/agent_core/ai/test_hosted_transform.py- tests/agent_core/ai/test_hosted_replay.py- tests/agent_core/ai/test_hosted_images.py+ - tests/agent_core/ai/test_hosted_pause_turn.py- tests/test_vibey_agent.py- tests/test_model_hub_evidence_rules.py- tests/test_model_hub_config.py@@ -323,6 +324,16 @@ scenarios:related_tests:- tests/agent_core/ai/test_hosted_replay.py::test_a_hosted_call_goes_back_verbatim_and_pinned_only_to_its_own_source_with_replay_evidence- tests/agent_core/ai/test_hosted_replay.py::test_a_continuation_goes_back_verbatim_only_to_the_hop_that_served_it+ - id: MH-HOSTED-VIBEY-006+ name: An Anthropic pause_turn continues as one response pinned to its Source and model, with the final request's usage and summed hosted counters, pending calls finalized by id, at most five continuations, ending interrupted when its Source cannot continue it, and verified only when every response was from one origin+ status: covered+ kind: contract+ layer: contract+ test: tests/agent_core/ai/test_hosted_pause_turn.py::test_a_paused_response_continues_as_one_response_pinned_to_its_source_with_summed_counters+ related_tests:+ - tests/agent_core/ai/test_hosted_pause_turn.py::test_a_response_paused_past_the_bound_ends_interrupted_and_keeps_everything_it_assembled+ - tests/agent_core/ai/test_hosted_pause_turn.py::test_a_paused_response_its_source_cannot_continue_ends_interrupted_and_keeps_what_it_has+ - tests/agent_core/ai/test_hosted_pause_turn.py::test_a_continued_response_is_verified_only_when_every_response_in_it_was_from_one_origin- id: MH-HOSTED-VIBEY-007name: A native generated image is saved to a file as its done item is parsed and its record names that file; no base64 enters history, partial and terminal copies are never decoded, and an image over read's inline limit says sostatus: covered