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
fix(agent-core): complete Anthropic server searches deferred behind client tool calls (#2926)
Call White4181fe42a6af
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex 4b7c1058a..ba3f66873 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -148,6 +148,7 @@ from core.agent_core.harness.projection import (validate_message_append,)from core.agent_core.harness.store import ContextEntry, EntryKind, TranscriptStore+from core.agent_core.hosted_continuations import pending_hostedfrom core.agent_core.messages import (AssistantMessage,HostedImage,@@ -449,6 +450,7 @@ class Agent:*,turn_id: str,turn_inputs: Iterable[int] | None = None,+ pending_inputs: Iterable[AgentInput] = (),) -> AsyncIterator[AgentEvent]:"""Continue from the committed transcript without consuming another input row.@@ -456,7 +458,8 @@ class Agent:unchanged; it is a control value, not a second transcript message. A freshAgent can provide the source Turn's input sequence numbers so compactionpins only that Turn's inputs. Within the same Turn, newly admitted inputs- extend the existing pins rather than replacing them.+ extend the existing pins rather than replacing them. ``pending_inputs`` restores+ accepted but unconsumed steers behind the next response, not into its request."""input = deepcopy(input)resume_turn_inputs = None if turn_inputs is None else set(turn_inputs)@@ -465,6 +468,7 @@ class Agent:lambda emit: self._drive(emit, input, consume=False),preserve_turn_inputs=True,resume_turn_inputs=resume_turn_inputs,+ pending_inputs=deepcopy(tuple(pending_inputs)),)async def _pump(@@ -474,6 +478,7 @@ class Agent:*,preserve_turn_inputs: bool = False,resume_turn_inputs: set[int] | None = None,+ pending_inputs: tuple[AgentInput, ...] = (),) -> AsyncIterator[AgentEvent]:previous_turn_inputs = set(self._turn_inputs)previous_seq = self._seq@@ -482,6 +487,7 @@ class Agent:raise RuntimeError("this Agent already has an active run")if self._steers or self._follow_ups:raise RuntimeError("return unconsumed inputs with take_pending_inputs() before starting another run")+ self._steers.extend(pending_inputs)continuing_turn = preserve_turn_inputs and self._ctx.turn_id == turn_idself._running = Trueself._open = True@@ -1205,7 +1211,10 @@ class Agent:return "ended_by_hook"if terminate:return "completed"- await self._drain_steers(emit)+ # Anthropic has not run these server tools yet. A steer after the client results would end its open+ # turn (and produce a 400), so admit it after the deferred result, not inside this continuation.+ if not pending_hosted(message):+ await self._drain_steers(emit)async def _drain_steers(self, emit: Callable[..., Awaitable[None]]) -> None:applied = []diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex 7660f869b..47c8a1c44 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -56,6 +56,8 @@ from core.agent_core.ai.provider import (MediaLoader,)from core.agent_core.cancel import CancelToken+from core.agent_core.hosted_continuations import pending_hosted+from core.agent_core.ai.transform import in_flight_position, native_replayfrom core.agent_core.messages import (MAX_HOSTED_COUNT,AssistantMessage,@@ -272,6 +274,16 @@ 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 mixed group crosses a committed response boundary. Carry only calls actually sent natively on this hop;+ # their result-only fragments belong to this response, never a rewrite of the earlier pending row.+ live = in_flight_position(request.messages)+ previous = request.messages[live] if live is not None else None+ deferred = (+ pending_hosted(previous)+ if isinstance(previous, AssistantMessage)+ and native_replay(previous, in_flight=True, endpoint=request.endpoint, target=target, protocol=self.protocol)+ else {}+ )# 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@@ -453,12 +465,17 @@ class AnthropicAdapter(ProviderAdapter):continueif kind == "web_search_tool_result":use = next((item for item in uses.values() if item.get("id") == block.get("tool_use_id")), None)- if use is not None and assembler.source_id is not None:- assembler.set_block_kind(index, "hosted_result")- assembler.hosted_block(- ("hosted", use.get("id")),- anthropic_hosted_block(use, block, source_id=assembler.source_id),- )+ prior = deferred.get(block.get("tool_use_id"))+ if use is None and prior is not None and prior.native.source_id == assembler.source_id:+ use = prior.native.payload[0]+ completed = anthropic_hosted_block(use, block, source_id=assembler.source_id)+ completed = replace(completed, native=replace(completed.native, payload=(dict(block),)))+ elif use is not None and assembler.source_id is not None:+ completed = anthropic_hosted_block(use, block, source_id=assembler.source_id)+ else:+ continue+ assembler.set_block_kind(index, "hosted_result")+ assembler.hosted_block(("hosted", use.get("id")), completed)continueif kind == "text":assembler.set_block_kind(index, "text")@@ -990,7 +1007,15 @@ def build_messages_payload(continueif converted["role"] == "assistant" and not converted["content"]:continue- payload_messages.append(converted)+ if (+ isinstance(message, ToolResultMessage) and payload_messages+ and payload_messages[-1]["role"] == "user"+ and isinstance(payload_messages[-1]["content"], list)+ and all(block.get("type") == "tool_result" for block in payload_messages[-1]["content"])+ ):+ payload_messages[-1]["content"].extend(converted["content"])+ else:+ payload_messages.append(converted)system: Any = request.systemif request.cache == "default" and request.system:diff --git a/core/agent_core/ai/hosted.py b/core/agent_core/ai/hosted.pyindex 793e7652c..5aa4e02d5 100644--- a/core/agent_core/ai/hosted.py+++ b/core/agent_core/ai/hosted.py@@ -456,7 +456,9 @@ class PortableHosted(NamedTuple):is_error: bool = False-def portable_hosted(message: AssistantMessage, *, in_flight: bool, interrupted: str) -> dict[int, PortableHosted]:+def portable_hosted(+ message: AssistantMessage, *, in_flight: bool, interrupted: str, parallel_group: bool = False+) -> dict[int, PortableHosted]:"""Each hosted call of a replayed response in portable form (§4.4, §5), keyed by the block's identity.Every call is exactly one unit with its own record:@@ -465,7 +467,8 @@ def portable_hosted(message: AssistantMessage, *, in_flight: bool, interrupted:* otherwise a synthetic same-named call and its result.The posts the answer cites are listed once, on its first call that was not cut off, whichever form it takes.- ``interrupted`` is the result of a synthetic call cut off with its turn.+ ``interrupted`` is the result of a synthetic call cut off with its turn. A deferred mixed ``parallel_group``+ is rendered intact by the caller, so calls after a client call can also be synthetic without splitting it."""blocks = [block for block in message.content if isinstance(block, HostedToolBlock)]@@ -475,7 +478,7 @@ def portable_hosted(message: AssistantMessage, *, in_flight: bool, interrupted:in_place = in_flightfor block in message.content:if not isinstance(block, HostedToolBlock):- in_place = in_place or isinstance(block, ToolCallBlock)+ in_place = in_place or (not parallel_group and isinstance(block, ToolCallBlock))continuecited = summary.cited_sources if summary is not None and block is owner else ()if in_place:diff --git a/core/agent_core/ai/transform.py b/core/agent_core/ai/transform.pyindex 383519cdb..1038fc317 100644--- a/core/agent_core/ai/transform.py+++ b/core/agent_core/ai/transform.py@@ -9,9 +9,10 @@ from __future__ import annotationsimport hashlibimport re-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom typing import Any, Mapping+from core.agent_core.hosted_continuations import effective_deferred_history, hosted_completions, result_fragmentfrom core.agent_core.ai.hosted import portable_hostedfrom core.agent_core.ai.provider import ModelEndpoint, OpaquePayloadfrom core.agent_core.messages import (@@ -83,9 +84,18 @@ def transform_messages("""target_protocol = protocol or target.api+ # Failed Anthropic attempts and their owned client results are audit facts, not request history. All three+ # continuation decisions below use this same effective view; raw positions are retained by the helper for callers+ # such as the provider adapter that must address the original request tuple.+ effective = effective_deferred_history(messages)+ raw_live = in_flight_position(messages)+ live = next((index for index, (raw, _) in enumerate(effective) if raw == raw_live), None)+ messages = tuple(message for _, message in effective)# The response the request continues within its turn keeps its hosted calls in place, verbatim or as text (§4.4);# every earlier one goes back verbatim with replay evidence or as a synthetic call and result (§5).- live = in_flight_position(messages)+ messages, portable_pairs, parallel_groups, continuing_pairs = _complete_hosted_history(+ messages, live=live, endpoint=endpoint, target=target, protocol=target_protocol+ )id_map: dict[str, str] = {}used_tool_ids: set[str] = set()tool_id_occurrences: dict[str, int] = {}@@ -132,8 +142,13 @@ def transform_messages(content: list[AssistantContent] = []turn_tool_ids: dict[str, list[str]] = {}in_flight = position == live- verbatim = native_replay(message, in_flight=in_flight, endpoint=endpoint, target=target, protocol=target_protocol)- hosted = {} if verbatim else portable_hosted(message, in_flight=in_flight, interrupted=SYNTHETIC_TOOL_RESULT)+ verbatim = position not in portable_pairs and native_replay(+ message, in_flight=in_flight or position in continuing_pairs,+ endpoint=endpoint, target=target, protocol=target_protocol+ )+ hosted = {} if verbatim else portable_hosted(+ message, in_flight=in_flight, interrupted=SYNTHETIC_TOOL_RESULT, parallel_group=position in parallel_groups+ )# The synthetic results of the current run of hosted calls, and the assistant parts they split off.results: list[ToolResultMessage] = []parts: list[Message] = []@@ -141,7 +156,7 @@ def transform_messages(def split() -> None:nonlocal content, results- if results:+ if results and position not in parallel_groups:parts.append(_assistant_part(message, content, stop_reason="tool_use"))parts.extend(results)content, results = [], []@@ -222,11 +237,72 @@ def transform_messages(# sent as an empty assistant message; one that was empty as served (a refusal) still goes, as before.if content or not (parts or foreign_thinking):transformed.append(_assistant_part(message, content, stop_reason=message.stop_reason))+ if position in parallel_groups:+ transformed.extend(results)transformed = _insert_synthetic_results(transformed)return TransformResult(messages=tuple(transformed), tool_call_id_map=dict(id_map))+def _complete_hosted_history(+ messages: list[Message] | tuple[Message, ...], *, live: int | None, endpoint: ModelEndpoint | None,+ target: Origin, protocol: str,+) -> tuple[tuple[Message, ...], set[int], set[int], set[int]]:+ """Join deferred records for eligibility/portable replay, not for native wire ordering (C-1).++ Both halves must be native or neither may be: a result-only native fragment cannot follow a synthetic call.+ Portable calls remain in the original parallel group and are settled alongside its client results.+ """+ pairs = hosted_completions(messages)+ paired = {(pair.result_position, id(pair.result)) for pair in pairs}+ orphaned = {+ position for position, message in enumerate(messages)+ if isinstance(message, AssistantMessage) and message.origin.api == "anthropic"+ for block in message.content if isinstance(block, HostedToolBlock) and result_fragment(block)+ and (position, id(block)) not in paired+ }+ if not pairs:+ return tuple(messages), orphaned, set(), set()+ continuing = {live} if live is not None else set()+ for pair in reversed(pairs):+ if pair.result_position in continuing:+ continuing.add(pair.use_position)+ resolved = list(messages)+ for pair in pairs:+ message = resolved[pair.use_position]+ resolved[pair.use_position] = replace(message, content=tuple(+ replace(block, record=pair.result.record) if block is pair.call else block for block in message.content+ ))+ blocked = orphaned | {+ position for pair in pairs for position in (pair.use_position, pair.result_position)+ if resolved[position].stop_reason in {"aborted", "error"}+ or not native_replay(resolved[position], in_flight=position in continuing, endpoint=endpoint,+ target=target, protocol=protocol)+ }+ # A response can finish a previous group and open another one. Admission is message-wide, so refusal propagates+ # through that connected exchange rather than leaving an orphan native fragment at either end.+ while True:+ expanded = blocked | {+ position for pair in pairs if pair.use_position in blocked or pair.result_position in blocked+ for position in (pair.use_position, pair.result_position)+ }+ if expanded == blocked:+ break+ blocked = expanded+ parallel = set()+ for pair in pairs:+ if pair.use_position not in blocked:+ continue+ parallel.add(pair.use_position)+ message = resolved[pair.result_position]+ content = tuple(block for block in message.content if block is not pair.result)+ resolved[pair.result_position] = replace(+ message, content=content,+ hosted_summary=message.hosted_summary if any(isinstance(b, HostedToolBlock) for b in content) else None,+ )+ return tuple(resolved), blocked, parallel, continuing++def _assistant_part(message: AssistantMessage, content: list[AssistantContent], *, stop_reason: str) -> AssistantMessage:hosted = any(isinstance(block, HostedToolBlock) for block in content)return AssistantMessage(@@ -240,19 +316,20 @@ def _assistant_part(message: AssistantMessage, content: list[AssistantContent],def in_flight_position(messages: list[Message] | tuple[Message, ...]) -> int | None:- """The position of the response a request continues within its turn (§4.4), or None.+ """The raw position of the response a request continues within its turn (§4.4), or None.- It is the request's last assistant message, stopped for tools, with nothing after it but tool results (a- ``pause_turn`` continuation has none). A user message after it means its turn ended, as one may right after its- tool results, so a later turn never counts as continuing it.+ The effective deferred-exchange history is shared with pairing and wire compilation: failed Anthropic attempts and+ their owned client results disappear before this tail check, while the returned position remains an index into the+ caller's original message sequence."""-- last = max((i for i, m in enumerate(messages) if isinstance(m, AssistantMessage)), default=None)- if last is None or messages[last].stop_reason != "tool_use": # type: ignore[union-attr]- return None- if any(not isinstance(message, ToolResultMessage) for message in messages[last + 1 :]):- return None- return last+ history = effective_deferred_history(messages)+ for raw_position, message in reversed(history):+ if isinstance(message, ToolResultMessage):+ continue+ if not isinstance(message, AssistantMessage) or message.stop_reason != "tool_use":+ return None+ return raw_position+ return Nonedef _opaque_admitted(message: AssistantMessage, endpoint: ModelEndpoint | None, payload: OpaquePayload) -> bool:diff --git a/core/agent_core/hosted_continuations.py b/core/agent_core/hosted_continuations.pynew file mode 100644index 000000000..acfb5cdae--- /dev/null+++ b/core/agent_core/hosted_continuations.py@@ -0,0 +1,128 @@+"""C-1 Anthropic deferred hosted calls: immutable fragments, one logical call.++The first response owns the use; the next valid continued response owns its result.+Only model-replay projections join them. Neither stored messages nor their usage are rewritten.+"""++from dataclasses import dataclass+from collections.abc import Sequence++from core.agent_core.messages import AssistantMessage, HostedToolBlock, Message, ToolResultMessage, UserMessage+++def pending_hosted(message: AssistantMessage) -> dict[str, HostedToolBlock]:+ """Anthropic server searches deferred at a tool boundary, not cut-off searches."""+ if message.origin.api != "anthropic" or message.stop_reason != "tool_use":+ return {}+ return {+ block.id: block for block in message.content+ if isinstance(block, HostedToolBlock) and block.tool == "web_search" and block.record.status == "pending"+ and len(block.native.payload) == 1+ and block.native.payload[0].get("type") == "server_tool_use"+ and block.native.payload[0].get("id") == block.id+ }+++def failed_deferred_attempt(previous: AssistantMessage, current: AssistantMessage) -> bool:+ """An error partial is retained for audit, not a response that closes this native exchange.++ This permits reconstructing an already-authorized retry, not granting one.+ Stop/aborted responses and another origin or account still close the exchange.+ """+ return (+ current.stop_reason == "error" and bool(pending_hosted(previous))+ and current.origin == previous.origin and current.source_identity == previous.source_identity+ )+++def effective_deferred_history(messages: Sequence[Message]) -> tuple[tuple[int, Message], ...]:+ """Return the request history after removing failed attempts and their owned results.++ A failed Anthropic response is not a valid response boundary when it follows a+ pending server search from the same Source identity. Its client-tool results are+ likewise failed-attempt facts, not results for the preceding valid response. Keep+ raw positions so callers that index the original request can still address rows;+ callers compiling a wire request should use the yielded message view itself.+ """+ effective: list[tuple[int, Message]] = []+ previous: AssistantMessage | None = None+ skipped_tool_ids: set[str] = set()+ for position, message in enumerate(messages):+ if isinstance(message, AssistantMessage):+ if previous is not None and failed_deferred_attempt(previous, message):+ skipped_tool_ids.update(call.id for call in message.tool_calls)+ continue+ previous = message+ skipped_tool_ids.clear()+ effective.append((position, message))+ continue+ if isinstance(message, UserMessage):+ previous = None+ skipped_tool_ids.clear()+ effective.append((position, message))+ continue+ if isinstance(message, ToolResultMessage) and message.tool_call_id in skipped_tool_ids:+ continue+ if not isinstance(message, ToolResultMessage):+ previous = None+ skipped_tool_ids.clear()+ effective.append((position, message))+ return tuple(effective)+++def result_fragment(block: HostedToolBlock) -> bool:+ return (+ block.tool == "web_search" and block.record.status != "pending" and len(block.native.payload) == 1+ and block.native.payload[0].get("type") == "web_search_tool_result"+ and block.native.payload[0].get("tool_use_id") == block.id+ )+++@dataclass(frozen=True)+class HostedCompletion:+ use_position: int+ result_position: int+ call: HostedToolBlock+ result: HostedToolBlock+++def hosted_completions(messages: Sequence[Message]) -> tuple[HostedCompletion, ...]:+ """Pair only a real continuation on the same origin/account/Source, across its client results.++ A new user input, another valid assistant response, missing client result, or moved Source cannot finish an old+ call. Failed attempts on that same deferred exchange are not valid responses. Call ids alone never authorize+ cross-Source pairing.+ """+ return _hosted_completions(effective_deferred_history(messages))+++def _hosted_completions(history: Sequence[tuple[int, Message]]) -> tuple[HostedCompletion, ...]:+ pairs = []+ previous: tuple[int, AssistantMessage] | None = None+ results: list[str] = []+ for position, message in history:+ if isinstance(message, ToolResultMessage):+ results.append(message.tool_call_id)+ continue+ if isinstance(message, AssistantMessage):+ if previous is not None:+ before_position, before = previous+ pending = pending_hosted(before)+ if (+ pending and message.origin == before.origin and message.source_identity == before.source_identity+ and sorted(results) == sorted(call.id for call in before.tool_calls)+ ):+ seen = set()+ for block in message.content:+ if not isinstance(block, HostedToolBlock) or not result_fragment(block):+ continue+ call = pending.get(block.id)+ if (call is not None and block.id not in seen and call.native.source_id == block.native.source_id+ and call.tool == block.tool and call.action == block.action):+ pairs.append(HostedCompletion(before_position, position, call, block))+ seen.add(block.id)+ previous = (position, message)+ else:+ previous = None+ results = []+ return tuple(pairs)diff --git a/core/hosted_activity.py b/core/hosted_activity.pyindex e0965a44b..b84b8202a 100644--- a/core/hosted_activity.py+++ b/core/hosted_activity.py@@ -25,6 +25,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldsfrom typing import Any, Callable, Literal, Mapping, Optional+from core.agent_core.hosted_continuations import pending_hostedfrom core.agent_core.messages import (HOSTED_ERROR_CODES,AssistantMessage,@@ -304,7 +305,10 @@ def native_activities(reports X-search results only as citations on the answer)."""- blocks = [block for block in message.content if isinstance(block, HostedToolBlock)]+ # A deferred call has not run. It produces no card on either surface; its later+ # result fragment is an ordinary hosted block at that response's own position.+ deferred = pending_hosted(message)+ blocks = [block for block in message.content if isinstance(block, HostedToolBlock) and block.id not in deferred]if not blocks:return []summary = message.hosted_summarydiff --git a/docs/plans/agent-core-contracts/README.md b/docs/plans/agent-core-contracts/README.mdindex bb52e54b3..4f7e649ef 100644--- a/docs/plans/agent-core-contracts/README.md+++ b/docs/plans/agent-core-contracts/README.md@@ -23,6 +23,9 @@ Conventions:- JSON Schema draft-07, like `../model-hub-contracts/`. Python implementations use dataclasses; the schemas describethe serialized form, which is what crosses a lane boundary or reaches disk.- Persisted shapes carry `"version": 1`. Readers accept every released version (persisted-shape rule).+ - C-1 clarification (approved 2026-10-22): Anthropic deferred hosted calls use existing v1 use-only and result-only+ fragments across immutable responses. Pairing/replay semantics are in `cross-provider.md`; released-reader+ round-trips cover v3.2.2 and gh-v3.2.3rc2. No wire-shape version change.- Field names are `snake_case`, except the tool parameters in C-7, which keep Pi's names (`oldText`, `newText`,`replaceAll`).- Every statement about existing code names its file and was checked against `master`; fields that already existdiff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 511472264..754aa9c43 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -655,7 +655,10 @@ These rows describe the wire mapping the `ai` lane implements.`TextBlock.citations`, and response-level facts go to `hosted_summary`. An `image_generation_call` is no hosted item:it is ignored like any undeclared item.- **Portable history.** A finished response's hosted calls become synthetic same-named calls and results, split around- the assistant message. There is one call per hosted block, and nothing folds. Each result shows its status line+ the assistant message. There is one call per hosted block, except that an Anthropic use-only pending fragment+ and its result-only completion are one logical call (`cross-provider.md`, 2026-10-22): one synthetic call in the+ original parallel group, its result alongside the client results, and no second call in the completing response.+ Each result shows its status linefirst and then every line attached to it. A response itsturn is still waiting on (the request's last assistant message, stopped for tools) keeps each call in place as text.So does a hosted call that follows a client tool call of the same response, because a split there would separate@@ -668,7 +671,12 @@ These rows describe the wire mapping the `ai` lane implements.model that served it (`x-avibe-pin-model`, when that id is ASCII). That response is the request's last assistantmessage, stopped for tools, with only tool results after it.- Any earlier response needs the hop's current `replay` for every tool it called, and every one of its calls must- have finished.+ have finished (a later paired completion counts). Linked fragments of the currently continuing Anthropic+ exchange follow its in-flight admission instead, including an internal `pause_turn` after the deferred result.+ - Anthropic mixed groups preserve response 1 → client-result-only user → response 2. The result in response 2+ carries only its `web_search_tool_result` in `native.payload`; the prior use remains in response 1. Both halves+ must be admitted natively together, never an orphan result after a portable use. Reported counters stay on+ the reporting response; the completion adds no inferred usage or cost.- Otherwise the calls take the portable form above. A continuation whose fresh hop is another Source thereforegoes in place as text: one hop builds and serves each request.- **`pin_unavailable`.** The gateway's `409` `model_hub_pin_unavailable` / `pin_unavailable` answer to a pinneddiff --git a/docs/plans/agent-core-contracts/cross-provider.md b/docs/plans/agent-core-contracts/cross-provider.mdindex 66881d687..016ee8ec1 100644--- a/docs/plans/agent-core-contracts/cross-provider.md+++ b/docs/plans/agent-core-contracts/cross-provider.md@@ -66,6 +66,25 @@ Invariants:`[tool call interrupted; no result recorded]`, with `is_error: true` (C-5 settles most such calls from the job handlefirst).- Responses API requests use `store: false` and never `previous_response_id`.+- Hosted calls deferred behind Anthropic client tools are one logical call across two immutable responses+ (clarified with orchestrator approval, **2026-10-22**; persisted shape remains **v1**). Response 1 has the pending+ `hosted_tool` and a use-only `native.payload`; response 2 has the same id, tool and action, its completed/failed+ record, and a **result-only** `native.payload`. No prior row changes. Pair only the immediately continued mixed+ response, its client results, and the same origin, Source and Source identity. The later fragment makes the+ earlier use finished for replay eligibility. Both halves are native or neither is: native replay keeps the use,+ client results and server result in their original response boundaries; portable replay emits one synthetic+ call in the first response's parallel group, with its result among that group's client results, and removes the+ completion fragment from response 2. Usage and cost remain on the reporting response and are never inferred+ again from the completion. An unmatched pending use keeps the interrupted rule for model replay. On Web and IM,+ deferred use-only calls produce no card; response 2's result fragment uses the ordinary hosted-card path at its own+ position. There is no cross-response card merge, held-card state or special delivery guarantee. Failed `error`+ attempts on the same deferred Anthropic exchange are omitted together with every client-tool result owned by each+ failed response from the shared effective request history used by in-flight discovery, pairing and wire compilation;+ an authorized retry resends the last valid continuation, preserving failed-attempt usage separately (hosted-tools+ §§4.4/15). This is a C-1 interpretation of+ existing v1 fields, verified by round-tripping both fragments through the v3.2.2 and gh-v3.2.3rc2 readers; no new+ message discriminator or reader-breaking field is introduced. Provider contract, fetched **2026-10-22**:+ [Server tools, mixed client/server groups](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools.md).- Hosted tool blocks ([`../vibey-hosted-tools.md`](../vibey-hosted-tools.md) §5): `native.payload` is anopaque provider payload under every rule above, and its replay is further limited to the recorded Source whilethat Source's current replay evidence is positive. The block never stores replay authorization. A differentdiff --git a/docs/plans/agent-core-contracts/recovery.md b/docs/plans/agent-core-contracts/recovery.mdindex e57cca285..8dbc02022 100644--- a/docs/plans/agent-core-contracts/recovery.md+++ b/docs/plans/agent-core-contracts/recovery.md@@ -25,8 +25,8 @@ at-least-once, and that is stated where it applies.| --- | --- | --- || T1 | `project()` reads only committed rows; the same rows always produce the same request. | projection before and after job state changes || T2 | At resume, before the first projection, and when a run ends without completing (a Stop), every tool call without a committed `tool_result` gets exactly one, chosen from the state of the job its call instance started (exited: the output; running: handover; stopped with a recorded reason: the output so far and that reason, `tools.md` §5; never ran: the interrupted result). The resume of a Turn rerun after a restart (T4) first waits for a running job as its live call would: until it exits, until the call's foreground window passes, counted from the job's launch (`meta.created_at`), or until a Stop, which ends the command as in a live Turn; only a job still running then is handed over, and one no Watch can take stays in the foreground until it ends, as in a live Turn. Startup's own pass leaves a running job of a Turn still open to that Turn's owner, which reruns the Turn or settles this Session itself before its notice; a job whose Turn a Stop canceled, or holds a stop never settled (a Stop or replacement control, or a cancel of one of its Runs), is ended instead of handed over. The wait commits nothing and starts nothing, so a crash during it leaves the call open for the next settlement. A call without job state (`write`, `edit`) gets `[tool call interrupted; it may or may not have completed; re-read the file before continuing]`. Retries settle nothing twice, and neither do concurrent writers: the store's `append_tool_result` returns the result already committed for the call instance instead of writing a second. | crash between settlement steps, then resume twice; a Stop while several calls of one group (C-3 §2) run; a restart rerun whose job exits inside its window, outlives it, or meets a Stop |-| T3 | Inputs accepted by `steer` or `follow_up` are never dropped: they enter the context, including after a crash. They belong to the Turn that accepted them and are never re-queued as a new P3 Turn. A run that ended by design runs again for them within its Turn; after a stop, an error, or a crash they are admitted into the context (at the end of the run, or at the Session's resume) and share the Turn's outcome. | a terminating tool while a steer is queued; a crash before consumption |-| T4 | An accepted Turn found unsettled at startup is continued after T2, whatever stopped the process (`vibey-restart-auto-resume.md`): it reruns in place, once its surface can deliver, keeping its identity, accepted start, Deliveries, and Runs, as a transcript resume of itself with no notice and no replayed tool call; a Turn whose final response was committed ends with it there through its live end, with no model call (Delivery below). A steer it accepted joins it first; while one is unsettled the Turn waits open. A command still running is waited for by the rerun's own T2 within its window from launch (startup leaves it to the open Turn, across repeated restarts) and is never run again; one handed to a Watch is read as the handover result. A command whose Turn a Stop canceled while it outlived the run is ended by T2, not handed to a Watch. A Turn that no longer qualifies (Stop or replacement requested, a Run cancelled or ended, Session archived, Agent off Vibey, or the third restart in a row without a committed model response) settles as interrupted with the restart notice after T2 hands its running commands to Watches (it stays open, retried, until a Watch takes them), so that notice names them and offers no Retry, because a resend would run them twice. A run that fails while the service is stopping leaves its Turn open for this. | crash after an `end` hook and after a mid-turn commit; a restart during a tool call, during a model call, and after the final commit |+| T3 | Inputs accepted by `steer` or `follow_up` are never dropped: they enter the context, including after a crash. They belong to the Turn that accepted them and are never re-queued as a new P3 Turn. A run that ended by design runs again for them within its Turn; after a stop, an error, or a crash they are admitted into the context (at the end of the run, or at the Session's resume) and share the Turn's outcome. Exception: an open Anthropic deferred server-tool continuation (hosted-tools §4.4) must precede any accepted steer. T3 reconstructs that barrier from the transcript and owning Turn; the unconsumed durable inputs restore to `Agent.resume`'s queue, not into its first request. A stopped or settled Turn admits them normally. | a terminating tool while a steer is queued; a crash before consumption; a restart between a mixed response and its continuation with an accepted steer |+| T4 | An accepted Turn found unsettled at startup is continued after T2, whatever stopped the process (`vibey-restart-auto-resume.md`): it reruns in place, once its surface can deliver, keeping its identity, accepted start, Deliveries, and Runs, as a transcript resume of itself with no notice and no replayed tool call; a Turn whose final response was committed ends with it there through its live end, with no model call (Delivery below). A steer it accepted joins it first (or waits behind its deferred native continuation under T3); while one is unsettled the Turn waits open. A command still running is waited for by the rerun's own T2 within its window from launch (startup leaves it to the open Turn, across repeated restarts) and is never run again; one handed to a Watch is read as the handover result. A command whose Turn a Stop canceled while it outlived the run is ended by T2, not handed to a Watch. A Turn that no longer qualifies (Stop or replacement requested, a Run cancelled or ended, Session archived, Agent off Vibey, or the third restart in a row without a committed model response) settles as interrupted with the restart notice after T2 hands its running commands to Watches (it stays open, retried, until a Watch takes them), so that notice names them and offers no Retry, because a resend would run them twice. A run that fails while the service is stopping leaves its Turn open for this. | crash after an `end` hook and after a mid-turn commit; a restart during a tool call, during a model call, and after the final commit |## Delivery (adapter wave)diff --git a/docs/plans/agent-core-contracts/transcript.md b/docs/plans/agent-core-contracts/transcript.mdindex 5a8386d48..c72e77fde 100644--- a/docs/plans/agent-core-contracts/transcript.md+++ b/docs/plans/agent-core-contracts/transcript.md@@ -58,6 +58,11 @@ and usage) orthe response's identity after restart. Legacy responses without it retain the input-order fallback.- A response row is inserted at `message_end` with both `content_json.model` and its commit-time display`content_text`.+- A deferred hosted use produces no activity card on Web or IM. Its completion fragment uses the ordinary hosted-card path at the completion response's own position. A deferred use that never completes has no card; old trace cards for that exact shape are hidden at read time. Other pending blocks retain interrupted rendering. There is no cross-response Web merge or extra delivery guarantee.+- An Anthropic server call deferred behind client tools finishes in a later response (C-1 `cross-provider.md`,+ 2026-10-22). Both existing v1 hosted-block fragments are appended in the provider's real response order; neither+ response row changes. C-1 request conversion joins the logical call for portable replay, while display joins+ append-only trace cards by owning durable Turn and call id. Usage remains on the reporting response.- A tool result row is inserted at `tool_finished`. The `tool_call` trace row is inserted at tool start without a`context_seq`.- Each commit is one SQLite transaction. The adapter delivers a row to surfaces only after it commits, through thediff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex 820e79d1b..e59a34c7e 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -444,9 +444,9 @@ never dropped.`native.payload`. Hosted payloads count against the 32 MiB `StreamAssembler` budget; search events measured atmost 96 KB, so every stream uses the 8 MiB line cap.-### 4.3 `pause_turn`+### 4.3 Anthropic server-tool continuation-Unchanged from v1 as implemented (orchestrator decision, 2026-10-14):+**`pause_turn`.** Unchanged from v1 as implemented (orchestrator decision, 2026-10-14):- The Anthropic adapter continues a paused response internally, at most 5 continuations, each pinned to the Sourcethat served the paused response. It never re-renders a continuation in portable form.- A continuation that Source answers `pin_unavailable`, a pause of a send that carried no pin, or a 6th pause ends@@ -455,6 +455,29 @@ Unchanged from v1 as implemented (orchestrator decision, 2026-10-14):`cited_sources` by URL. Pending calls carry over by tool-call id, so each call stays one block.- The merged message is verified only when every response in it was verified and reported the same origin.+**Mixed parallel groups** (C-1 clarification approved 2026-10-22). A response with `stop_reason: tool_use`, client+`tool_use` blocks, and a `server_tool_use` lacking its result has **not run** that server tool. After the client+results, the next response starts with a `web_search_tool_result` whose `tool_use_id` names that earlier use; it+never repeats the use. The adapter carries the pending use by id, as for `pause_turn`, but this continuation crosses+C-5's commit boundary, so its completion is append-only:++- Response 1 keeps its ordinary pending `HostedToolBlock`, with the use alone in `native.payload`.+- Response 2 holds an ordinary completed (or failed) `HostedToolBlock` with the **same id, tool and action**, and+ the result alone in `native.payload`. These are two immutable fragments of **one logical call**. No committed+ `content_json.model`, `context_seq` or trace row is rewritten. The v1 shape round-trips through the actual+ v3.2.2 and gh-v3.2.3rc2 readers; no schema version or new persisted message kind is needed.+- Pairing requires the preceding mixed response, its client results, and the same origin, Source and Source+ identity. A result from a re-resolved hop cannot complete an old Source's call.+- Usage and hosted counters remain on the response reporting them, unchanged. Parsing a completion never adds a+ charge inferred from a block. A missing reported counter remains missing; it is not manufactured as zero or one.+- Web and IM follow one rule: a deferred use produces no card; response 2's result fragment renders as an ordinary+ hosted card at its own position, after the client-tool activity, live and on reload. A call that never completes+ produces no card. Old pending trace cards of this exact deferred shape are also hidden at read time; other pending+ calls (for example a stream cut with `stop_reason: error`) retain interrupted rendering. No cross-response card+ merge, provisional state, held-card map, audit receipt or special delivery guarantee exists.++Provider source, fetched **2026-10-22**: [Server tools — Mixing server tools and client tools in one turn](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools.md).+### 4.4 In-flight turn replayWithin one turn, a client `tool_result` after server tools in the same assistant message makes the next request@@ -462,6 +485,23 @@ pinned to the Source the previous response came from, and the assistant contentown `pause_turn` continuations follow §4.3 and never take the fallback below.) This is the provider's own continuation contract, so it needs no `replay` evidence, but it does need thetool still declared natively on that hop (§3.5).+For a mixed pending group (§4.3), the assistant content is sent in its original order, followed by **one user+message containing only all client `tool_result` blocks**, with the same tool declarations. No user text follows+those results: it would close the still-open server-tool turn and the provider rejects it. Queued steers therefore+wait until the deferred result has arrived, including after a restart: T3 derives the open barrier from the+persisted transcript and owning Turn, leaves accepted inputs unconsumed, and restores them to `Agent.resume`'s+queue before it opens admission. A stopped/settled Turn has no continuation barrier and admits them normally.+A subsequent internal `pause_turn` preserves the entire linked exchange+natively without requiring historical replay evidence.++A failed partial and every client-tool result owned by that failed response are omitted together from the effective request history used by in-flight discovery, completion pairing and wire compilation. Their durable rows remain audit facts, and reused client call ids become eligible again only after the next valid assistant response resets that failed-attempt scope. For the same+Anthropic origin/account's deferred exchange, the partial neither closes the in-flight request nor completes a pair for+replay eligibility. An already-authorized transcript retry therefore sends the preceding valid mixed response+and its client results unchanged; a later successful response pairs across the failed attempts. The failed+partials and their reported usage stay immutable in storage. This does not grant retry permission or make a+failed stream resumable like `pause_turn`; Stop/`aborted`, a new user input, or another origin/account still closes+the exchange.+**Fallback form.** It applies when the pinned Source refuses in-flight verbatim replay, when the fresh hop nolonger declares the tool natively, or on `pin_unavailable`. Each server block pair is replaced **in place** by onetext block: `[web_search: <query>]` plus numbered titles and URLs.@@ -479,6 +519,12 @@ These rules are C-1 rows in `cross-provider.md` and per-protocol rows in `conver| `TextBlock.citations` | not sent | not sent || Proxied search or image call (`ToolCallBlock` + `ToolResultMessage.hosted`) | ordinary tool call and result | same |+- **Cross-response Anthropic completions** (§4.3) are joined before replay eligibility is decided. The earlier use+ counts as finished when its later fragment completed it. Native replay retains the exact response order:+ assistant use → client-result-only user → assistant server result. Both halves go native or neither does.+ Portable replay emits **one** same-named synthetic call in the first response's parallel group and its result+ alongside that group's client results; it suppresses the completion fragment in response 2, retaining its other+ content and its usage. An unmatched pending call still renders interrupted.- **Google targets** take the Chat pair; the engine translates it to Gemini `functionCall` / `functionResponse`parts. A failed record becomes `response: {error: <text>}`.- **Synthetic rendering rules**, by action, unchanged from v1: a `search` becomes one call with `{query:@@ -986,4 +1032,25 @@ and no real credentials.loads as an ordinary tool result, and a native call loads as portable text with its query or URL and sources whenavailable, otherwise a one-line unavailable placeholder. A degraded native block also clears unpartitionableresponse-wide facts (§4.2). The row is not rewritten, new writes stay strict, and known tools retain strict- validation; this is the intentional downgrade path before a new hosted tool ships.+ validation—including a result-only fragment for a known deferred completion; only an unrecognized tool name+ degrades portably. This is the intentional downgrade path before a new hosted tool ships.+9. **A deferred call without a completion stays unresolved in model history.** Stop, an error before its result,+ `pin_unavailable`, or re-resolution to a different Source do not synthesize a success or retry the search elsewhere.+ The existing §4.4 fallback remains unchanged. Already dropped result blocks in old transcripts cannot be recovered.+10. **Deferred calls have no card on any surface.** Response 1's use-only pending block with `stop_reason: tool_use`+ is a protocol fact, not a search that ran. Web and IM omit it, including the old interrupted cards emitted for this+ exact shape by earlier builds. A later completion uses the ordinary hosted-card path at response 2's position;+ a call that never completes has no card. Other pending blocks retain interrupted rendering. No Web merge,+ provisional searching state, held-card state, restart flush, audit receipt or special delivery guarantee exists;+ the ordinary commit-to-trace/send crash gap remains unchanged.+11. **Unreported hosted usage is unknown.** Counters/cost are read from wire usage only, never inferred from the+ number of parsed calls or completion fragments. The 2026-10-22 live probe's installed parser dropped the result+ block and its hosted summary, so that transcript cannot establish which response reported the search counter.+ Neither the mixed-group contract nor [web search usage and pricing](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool.md)+ (both fetched 2026-10-22) specifies attribution across this split; the latter defines the+ `usage.server_tool_use.web_search_requests` counter. Both present and absent counters are covered by+ raw-stream-shaped fixtures; the fix never adds a second charge.+12. **An existing authorized retry can repeat upstream work.** A failed partial is not a valid native response+ prefix, so a retry resends the last valid continuation rather than inventing a new provider resume protocol.+ Each attempt's reported usage stays on its own response: a partial reporting one search followed by a retry+ reporting two records all three, without synthesizing or deduplicating real charges. No new retry layer is added.diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 11be77aa6..66094a84f 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -61,7 +61,8 @@ from core.agent_core.agent.models import ModelSelectionfrom core.agent_core.agent.recovery import settle_open_callsfrom core.agent_core.harness.context import ContextConfigfrom core.agent_core.harness.projection import open_tool_calls-from core.agent_core.harness.store import ContextEntry+from core.agent_core.hosted_continuations import pending_hosted+from core.agent_core.ai.transform import in_flight_positionfrom core.agent_core.tools.base import CallInstancefrom core.agent_core.tools.jobs import call_instancefrom core.agent_core.messages import (@@ -325,7 +326,14 @@ class VibeyAgent(BaseAgent):)await self._fail(request, type(error).__name__, f"turn failed: {error}", cause=error)finally:- await self._admit_returned_inputs(turn)+ await self._admit_returned_inputs(turn, defer_continuation=self._service_stopping(turn))+ if (+ (context.platform_specific or {}).get("vibey_resume")+ and turn.reason not in _COMPLETED+ and not self._service_stopping(turn)+ ):+ # Preflight/Stop can end a rerun before its Agent took the durable inputs.+ self._schedule_recovery()self.store.bind_agent(session_id, None)if turn.router is not None:await turn.router.aclose()@@ -415,6 +423,7 @@ class VibeyAgent(BaseAgent):agent_input,turn_id=turn.turn_id,turn_inputs=resume_turn_inputs,+ pending_inputs=await self._recovered_inputs(session_id),)if transcript_resumeelse turn.agent.run(agent_input, turn_id=turn.turn_id)@@ -427,10 +436,10 @@ class VibeyAgent(BaseAgent):if turn.continuation_started_at is None:turn.continuation_started_at = time.monotonic()# Finish T2 before asking the same Agent to build its next request.- # Accepted P1 inputs are admitted into the transcript, but never- # become an implicit user-visible continuation message.+ # Accepted P1 inputs enter context unless the native continuation still+ # requires a tool-result-only user message; those restore to its queue.await self._settle_left_open(runtime)- resume_turn_inputs = await self._admit_returned_inputs(turn)+ resume_turn_inputs = await self._admit_returned_inputs(turn, defer_continuation=True)if await self._wait_auto_continue(turn):turn.continuations += 1turn.reason = None@@ -438,6 +447,8 @@ class VibeyAgent(BaseAgent):turn.final_row = Nonetranscript_resume = Truecontinue+ # Stop/backoff exhaustion ended the continuation we deferred T3 for.+ await self._resume(runtime)agent_input = await self._continuing_input(turn)if self._cut_by_service_stop(turn):# Stopping the service (its Model Hub gateway first) ended this run, not@@ -1029,7 +1040,7 @@ class VibeyAgent(BaseAgent):run.reason = Nonereturn pending[-1]- async def _admit_returned_inputs(self, run: _Run) -> tuple[int, ...]:+ async def _admit_returned_inputs(self, run: _Run, *, defer_continuation: bool = False) -> tuple[int, ...]:"""Inputs a stopped or failed run accepted but did not consume enter the context (T3).They belong to the Turn that accepted them and share its outcome, as a message@@ -1040,7 +1051,11 @@ class VibeyAgent(BaseAgent):if run.agent is None:return ()try:- for item in await run.agent.take_pending_inputs():+ pending = await run.agent.take_pending_inputs()+ if pending and defer_continuation and await self._deferred_continuation_open(run.session_id):+ # Durable accepted rows restore the queue at resume, including after shutdown.+ return ()+ for item in pending:entry = await self.store.consume_input(run.session_id, item.message_id, item.message)consumed.append(entry.context_seq)except Exception:@@ -1069,9 +1084,35 @@ class VibeyAgent(BaseAgent):returnif not runtime.cwd:runtime.cwd = await asyncio.to_thread(self._session_workdir, session_id)+ if (defer_continued or stop is not None) and await self._deferred_continuation_open(session_id):+ # T3 cannot close an Anthropic server-tool turn. Startup leaves the accepted+ # rows untouched; Agent.resume restores them to its queue before admission opens.+ return+ for item in await self._recovered_inputs(session_id):+ await self.store.consume_input(session_id, item.message_id, item.message)++ async def _deferred_continuation_open(self, session_id: str) -> bool:+ turn = await asyncio.to_thread(self._active_turn, session_id)+ if turn is None:+ return False+ entries = [row for row in await self.store.load_turn(session_id, str(turn["id"])) if row.message is not None]+ position = in_flight_position([row.message for row in entries])+ return (+ position is not None+ and bool(pending_hosted(entries[position].message))+ and await asyncio.to_thread(self._work_state, str(turn["id"])) == "open"+ )++ def _active_turn(self, session_id: str) -> Optional[dict[str, Any]]:+ with self._engine.connect() as conn:+ return delivery_store.active_turn(conn, session_id)++ async def _recovered_inputs(self, session_id: str) -> tuple[AgentInput, ...]:+ inputs = []for message_id, text_value, files, delivery in await asyncio.to_thread(self._unconsumed_inputs, session_id):message = await self._render_input(session_id, text_value, files, await self._input_metadata(delivery))- await self.store.consume_input(session_id, message_id, message)+ inputs.append(AgentInput(message_id, message))+ return tuple(inputs)async def _input_metadata(self, delivery: dict[str, Any]) -> Optional[AgentInputMetadata]:"""A recovered input's sender facts, from the owner the live steer path uses (T3).diff --git a/modules/agents/vibey/store.py b/modules/agents/vibey/store.pyindex 9fcd49492..eb3d07f6b 100644--- a/modules/agents/vibey/store.py+++ b/modules/agents/vibey/store.py@@ -113,6 +113,9 @@ class AdapterTranscriptStore:async def load(self, session_id: str) -> Sequence[ContextEntry]:return await self._store.load(session_id)+ async def load_turn(self, session_id: str, turn_id: str) -> Sequence[ContextEntry]:+ return await self._store.load_turn(session_id, turn_id)+async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:await self._await_input_row(session_id, message_id)previous = self._env_state.get(session_id)diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.pyindex 3c1166000..1e0962a43 100644--- a/storage/agent_activity_service.py+++ b/storage/agent_activity_service.py@@ -37,14 +37,17 @@ are exactly the ones covered.from __future__ import annotations+import jsonfrom datetime import datetime, timezonefrom typing import Any, Optionalfrom sqlalchemy import select+from core.agent_core.hosted_continuations import pending_hosted+from core.agent_core.messages import AssistantMessage, message_from_dictfrom core.backend_failure import is_backend_failure_notificationfrom storage import agent_events_service, messages_service-from storage.models import message_deliveries, session_turns+from storage.models import message_deliveries, messages, session_turnsfrom vibe.message_types import (PROMOTED_FROM_KEY,PROMOTED_FROM_TYPES,@@ -247,6 +250,36 @@ def _event_emit_micros(event: dict[str, Any], ts: datetime) -> int:return anchor - 1 if isinstance(precedes, str) and precedes else anchor+def _without_deferred_traces(conn, session_id: str, events: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Old releases emitted interrupted cards for calls Anthropic deferred, which never ran.++ Suppress only that exact shape, using each trace's own response. No fragment+ merging or position changes; every other pending/terminal card stays as written.+ """+ candidates = {}+ for event in events:+ card = (event.get("content") or {}).get("hosted")+ if isinstance(card, dict) and card.get("mode") == "native" and card.get("status") == "pending":+ response_id = card.get("response_id") or (event.get("metadata") or {}).get("precedes_message_id")+ if isinstance(response_id, str) and response_id:+ candidates[event["id"]] = (response_id, card.get("call_id"))+ if not candidates:+ return events+ deferred = set()+ for row_id, owner_session, raw in conn.execute(select(messages.c.id, messages.c.session_id, messages.c.content_json).where(+ messages.c.id.in_({owner for owner, _ in candidates.values()})+ )):+ if owner_session != session_id:+ continue+ try:+ message = message_from_dict(json.loads(raw or "{}")["model"]["message"])+ except (KeyError, TypeError, ValueError):+ continue+ if isinstance(message, AssistantMessage):+ deferred.update((row_id, call_id) for call_id in pending_hosted(message))+ return [event for event in events if candidates.get(event["id"]) not in deferred]++def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, Any]]:"""Merge the recent tail of relevant messages + tool-call events into onechronologically-ordered list of classified items."""@@ -264,6 +297,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, Anlimit=EVENT_SCAN_LIMIT,newest_first=True,)+ events = _without_deferred_traces(conn, session_id, events)message_ids = tuple(str(message["id"])for message in msgsdiff --git a/storage/agent_transcript.py b/storage/agent_transcript.pyindex 24459b89b..5be79d1fa 100644--- a/storage/agent_transcript.py+++ b/storage/agent_transcript.py@@ -68,7 +68,7 @@ from dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Any, Callable, Literal, Mapping, Optional, Sequence, TypeVar-from sqlalchemy import and_, func, or_, select, text+from sqlalchemy import and_, bindparam, func, or_, select, textfrom sqlalchemy.engine import Connection, Enginefrom core.agent_core.harness.fork import fork_point, latest_cut@@ -89,7 +89,7 @@ from core.agent_core.messages import (from storage import agent_events_service, media_service, messages_servicefrom storage.agent_session_rows import reserve_write_lockfrom storage.message_deliveries import TURN_OWNER_STATES-from storage.models import agent_events, agent_sessions, message_deliveries, messages, scopes, session_turns+from storage.models import MESSAGE_TURN_ID_SQL, agent_events, agent_sessions, message_deliveries, messages, scopes, session_turnsfrom storage.vibey_recovery import VIBEY_RECOVERY_INPUT_PREDICATEINPUT_TYPES = ("user", "harness", "agent_initiated", "annotation")@@ -217,6 +217,10 @@ class SQLiteTranscriptStore:async def load(self, session_id: str) -> Sequence[ContextEntry]:return await asyncio.to_thread(self._load, session_id)+ async def load_turn(self, session_id: str, turn_id: str) -> Sequence[ContextEntry]:+ """Load one durable Turn's own context, excluding older history and fork ancestry."""+ return await asyncio.to_thread(self._load, session_id, turn_id=turn_id)+async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:if not isinstance(message, UserMessage):raise TypeError("consume_input takes a UserMessage")@@ -433,11 +437,13 @@ class SQLiteTranscriptStore:session_id, seq, kind, row["id"], message=message, payload=payload, created_at=_epoch(row["created_at"]))- def _load(self, session_id: str) -> list[ContextEntry]:+ def _load(self, session_id: str, *, turn_id: Optional[str] = None) -> list[ContextEntry]:with self._engine.begin() as conn:- # One read snapshot across both tables and every ancestor.+ # One read snapshot across both tables and every ancestor (or just the requested Turn).if not conn.connection.dbapi_connection.in_transaction:conn.exec_driver_sql("BEGIN")+ if turn_id is not None:+ return _turn_context_entries(conn, session_id, turn_id)return _context_entries(conn, session_id)async def _settle(task: asyncio.Future[Any]) -> None:@@ -934,6 +940,36 @@ def _context_rows(conn: Connection, session_id: str, bound: Optional[int]) -> lireturn entries+def _turn_context_entries(conn: Connection, session_id: str, turn_id: str) -> list[ContextEntry]:+ """Read one Turn through its owner indexes, without loading Session history or forks."""+ entries: list[ContextEntry] = []+ for table, index, owner, columns, to_entry in (+ ("messages", "ix_messages_turn_id", MESSAGE_TURN_ID_SQL, "type", _message_entry),+ ("agent_events", "ix_agent_events_turn_sequence_id", "turn_id", "event_type, visibility", _event_entry),+ ):+ query = text(+ f"SELECT id, context_seq, content_json, created_at, {columns} FROM {table} INDEXED BY {index} "+ f"WHERE session_id = :session_id AND context_seq IS NOT NULL AND ({owner}) = :turn_id"+ + (" AND type IN :response_types" if table == "messages" else "")+ )+ params: dict[str, Any] = {"session_id": session_id, "turn_id": turn_id}+ if table == "messages":+ query = query.bindparams(bindparam("response_types", expanding=True))+ params["response_types"] = RESPONSE_TYPES+ entries.extend(to_entry(session_id, row) for row in conn.execute(query, params).mappings())+ # Inputs are owned by Deliveries, not response metadata. Include accepted steers as barriers in this Turn.+ query = text(+ "SELECT messages.id, messages.context_seq, messages.content_json, messages.created_at, messages.type "+ "FROM message_deliveries INDEXED BY ix_message_deliveries_turn "+ "CROSS JOIN messages ON messages.id = message_deliveries.message_id "+ "WHERE message_deliveries.turn_id = :turn_id AND message_deliveries.state = 'accepted' "+ "AND messages.session_id = :session_id AND messages.context_seq IS NOT NULL AND messages.type IN :input_types"+ ).bindparams(bindparam("input_types", expanding=True))+ rows = conn.execute(query, {"session_id": session_id, "turn_id": turn_id, "input_types": INPUT_TYPES}).mappings()+ entries.extend(_message_entry(session_id, row) for row in rows)+ return sorted(entries, key=lambda row: row.context_seq)++def _message_entry(session_id: str, row: Mapping[str, Any]) -> ContextEntry:row_id = row["id"]if row["type"] in INPUT_TYPES:diff --git a/tests/agent_core/ai/test_anthropic_deferred.py b/tests/agent_core/ai/test_anthropic_deferred.pynew file mode 100644index 000000000..e48a272d5--- /dev/null+++ b/tests/agent_core/ai/test_anthropic_deferred.py@@ -0,0 +1,339 @@+"""Anthropic mixed parallel groups: append-only deferred completion (hosted-tools §4.3)."""++from dataclasses import replace+import json++import httpx+import pytest++from core.agent_core.ai._common import PIN_MODEL_HEADER, PIN_SOURCE_HEADER+from core.agent_core.ai.hosted import anthropic_hosted_block+from core.agent_core.ai.provider import Done+from core.agent_core.messages import (+ AssistantMessage, HostedSummary, HostedToolBlock, TextBlock, ToolCallBlock,+ ToolResultMessage, UserMessage, message_from_dict, message_to_dict,+)+from tests.agent_core.ai._wire import build_wire_request+from tests.agent_core.ai.test_hosted_pause_turn import (+ MODEL, SOURCE, RESULT, _request, _response, _served, _stream, _text,+)++USE = {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "avibe release"}}+CLIENT = {"type": "tool_use", "id": "toolu_client", "name": "read", "input": {"path": "a"}}+OTHER = "src_other000001"+SHAPES = ["SC", "CS", "SSC", "FSSCC"]+++def _blocks(shape):+ blocks = []+ for index, kind in enumerate(shape):+ if kind == "C":+ blocks.append({**CLIENT, "id": f"toolu_{index}"})+ else:+ use = {**USE, "id": f"srvtoolu_{index}"}+ blocks.append(use)+ if kind == "F":+ blocks.append({**RESULT, "tool_use_id": use["id"]})+ return blocks+++def _sse(blocks, *, stop="tool_use", searches=0):+ return _response(*[[{"type": "content_block_start", "content_block": block}] for block in blocks],+ stop_reason=stop, input_tokens=100, output_tokens=10, searches=searches)+++async def _paused(shape="SC"):+ request = _request()+ _, events = await _stream(lambda _: httpx.Response(200, headers=_served(), text=_sse(_blocks(shape))), request)+ assert isinstance(events[-1], Done)+ message = events[-1].message+ results = tuple(ToolResultMessage(call.id, call.name, (TextBlock("contents"),)) for call in message.tool_calls)+ return replace(request, messages=(*request.messages, message, *results)), message++[email protected]("shape", SHAPES)+async def test_mixed_pause_preserves_exact_assistant_and_result_only_user_group(shape):+ request, message = await _paused(shape)+ first = await build_wire_request(_request(), gateway=True)+ wire = await build_wire_request(request, gateway=True)+ assert wire.headers[PIN_SOURCE_HEADER] == SOURCE+ assert wire.headers[PIN_MODEL_HEADER] == MODEL+ assert wire.body["tools"] == first.body["tools"]+ assert wire.body["messages"][1] == {"role": "assistant", "content": _blocks(shape)}+ users = wire.body["messages"][2:]+ assert len(users) == 1+ assert users[0]["role"] == "user"+ assert [item["tool_use_id"] for item in users[0]["content"]] == [call.id for call in message.tool_calls]+ assert {item["type"] for item in users[0]["content"]} == {"tool_result"}+ assert "interrupted" not in json.dumps(wire.body)++[email protected]("shape", SHAPES)+async def test_orphan_result_finishes_prior_call_without_repeating_use_and_keeps_usage_here(shape):+ request, paused = await _paused(shape)+ pending = [b for b in paused.content if isinstance(b, HostedToolBlock) and b.record.status == "pending"]+ result_items = [{**RESULT, "tool_use_id": b.id} for b in pending]+ _, events = await _stream(lambda _: httpx.Response(200, headers=_served(),+ text=_sse(result_items + [{"type": "text", "text": "found"}], stop="end_turn", searches=len(pending))), request)+ assert isinstance(events[-1], Done)+ completed = events[-1].message+ calls = [b for b in completed.content if isinstance(b, HostedToolBlock)]+ assert [b.id for b in calls] == [b.id for b in pending]+ for before, after, item in zip(pending, calls, result_items):+ assert after.action == before.action and after.record.status == "completed"+ assert after.native.payload == (item,)+ assert [source.url for source in after.record.sources] == ["https://avibe.bot/r"]+ assert not paused.hosted_summary.counts+ assert completed.hosted_summary.counts == {"web_search_requests": len(pending)}+ assert message_from_dict(message_to_dict(completed)) == completed+++async def test_a_result_from_another_source_cannot_complete_the_previous_sources_call():+ request, _ = await _paused()+ request = replace(request, endpoint=replace(request.endpoint, source_id=OTHER))+ result = {**RESULT, "tool_use_id": "srvtoolu_0"}+ sent, events = await _stream(lambda _: httpx.Response(200, headers=_served(source=OTHER),+ text=_sse([result, {"type": "text", "text": "other"}], stop="end_turn", searches=1)), request)+ assert not any(isinstance(b, HostedToolBlock) for b in events[-1].message.content)+ assert "server_tool_use" not in json.dumps(json.loads(sent[0].content)["messages"])++[email protected]("reported", [0, 1])+async def test_deferred_completion_never_invents_a_charge_from_a_result_block(reported):+ request, _ = await _paused()+ result = {**RESULT, "tool_use_id": "srvtoolu_0"}+ _, events = await _stream(lambda _: httpx.Response(200, headers=_served(),+ text=_sse([result, {"type": "text", "text": "done"}], stop="end_turn", searches=reported)), request)+ message = events[-1].message+ assert message.hosted_summary.counts == ({"web_search_requests": 1} if reported else {})+ assert message.hosted_summary.cost is None+++async def test_deferred_result_then_pause_turn_keeps_the_native_exchange_without_replay_evidence():+ request, _ = await _paused()+ result = {**RESULT, "tool_use_id": "srvtoolu_0"}+ def answer(number):+ blocks = [result] if number == 1 else [{"type": "text", "text": "done"}]+ return httpx.Response(200, headers=_served(), text=_sse(blocks,+ stop="pause_turn" if number == 1 else "end_turn", searches=1 if number == 1 else 0))+ sent, events = await _stream(answer, request)+ assert len(sent) == 2 and isinstance(events[-1], Done)+ history = json.loads(sent[1].content)["messages"]+ assert history[1] == {"role": "assistant", "content": _blocks("SC")}+ assert history[3] == {"role": "assistant", "content": [result]}+ calls = [b for b in events[-1].message.content if isinstance(b, HostedToolBlock)]+ assert len(calls) == 1 and calls[0].native.payload == (result,)+ assert events[-1].message.hosted_summary.counts == {"web_search_requests": 1}+++async def test_a_steer_waits_until_the_deferred_result_and_never_enters_the_tool_result_user_message():+ from core.agent_core.agent.loop import Agent+ from core.agent_core.tools.base import ToolResult+ from tests.agent_core.ai.test_hosted_replay import _Hops, _hosted_tool+ from tests.agent_core.fakes import FakeTool, FakeJobHost, InMemoryTranscriptStore, input_row++ sent = []+ def gateway(wire):+ sent.append(json.loads(wire.content))+ if len(sent) == 1:+ blocks, stop = _blocks("SC"), "tool_use"+ elif len(sent) == 2:+ blocks, stop = [{**RESULT, "tool_use_id": "srvtoolu_0"}, {"type": "text", "text": "found"}], "end_turn"+ else:+ blocks, stop = [{"type": "text", "text": "steer answered"}], "end_turn"+ return httpx.Response(200, headers=_served(), text=_sse(blocks, stop=stop, searches=1 if len(sent) == 2 else 0))++ async def read(arguments, ctx):+ assert await agent.steer(input_row("steer", "extra user input"))+ return ToolResult((TextBlock("contents"),))++ store = InMemoryTranscriptStore()+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ agent = Agent(session_id="session", models=_Hops(client, (_request().endpoint,)),+ tools=(_hosted_tool("web_search"), FakeTool("read", execute=read)), hooks=(),+ store=store, jobs=FakeJobHost(), cwd="/test-owned")+ events = [e async for e in agent.run(input_row("input", "search"), turn_id="turn")]+ assert events[-1].reason == "completed" and len(sent) == 3+ assert {b["type"] for b in sent[1]["messages"][-1]["content"]} == {"tool_result"}+ assert sent[1]["tools"] == sent[0]["tools"]+ assert "extra user input" not in json.dumps(sent[1])+ assert "extra user input" in json.dumps(sent[2])++[email protected]("failures", [1, 2])[email protected]("native_history", [True, False])+async def test_partial_deferred_failure_retries_the_open_exchange_and_pairs_only_the_valid_result(failures, native_history):+ """A failed result fragment is not a new provider turn or evidence that its group ended.++ Unlike a clean continuation, this cut previously forced every unfinished call+ portable and prevented the next parser from recognizing any deferred result.+ """+ from core.agent_core.ai.provider import ProviderError++ request, original = await _paused("SSC")+ result = {**RESULT, "tool_use_id": "srvtoolu_0"}+ original_client_id = next(call.id for call in original.tool_calls if call.name == "read")+ failed_client_block = {**CLIENT, "id": original_client_id}+ partial_wire = _sse([result, failed_client_block], stop=None, searches=1).removesuffix('data: {"type": "message_stop"}\n\n')+ _, failed = await _stream(lambda _: httpx.Response(200, headers=_served(), text=partial_wire), request)+ failure = failed[-1]+ assert isinstance(failure, ProviderError) and failure.continuable+ partial = replace(+ failure.partial,+ content=(*failure.partial.content, ToolCallBlock(original_client_id, "read", {"path": "a"})),+ )+ assert partial.stop_reason == "error"+ assert partial.hosted_summary.counts == {"web_search_requests": 1}+ first = await build_wire_request(request, gateway=True)+ retry_messages = list(request.messages)+ for _ in range(failures):+ retry_messages.extend((partial, ToolResultMessage(original_client_id, "read", (TextBlock("contents"),))))+ retry = replace(request, messages=tuple(retry_messages))+ resent = await build_wire_request(retry, gateway=True)+ assert resent.body["messages"] == first.body["messages"]+ assert resent.body["tools"] == first.body["tools"]+ assert resent.headers[PIN_SOURCE_HEADER] == SOURCE and resent.headers[PIN_MODEL_HEADER] == MODEL++ results = [{**RESULT, "tool_use_id": f"srvtoolu_{index}"} for index in (0, 1)]+ _, events = await _stream(lambda _: httpx.Response(200, headers=_served(),+ text=_sse([*results, {"type": "text", "text": "found both"}], stop="end_turn", searches=2)), retry)+ assert isinstance(events[-1], Done)+ completed = events[-1].message+ assert [b.id for b in completed.content if isinstance(b, HostedToolBlock)] == ["srvtoolu_0", "srvtoolu_1"]+ assert completed.hosted_summary.counts == {"web_search_requests": 2}+ assert not original.hosted_summary.counts+ assert partial.hosted_summary.counts == {"web_search_requests": 1}+ endpoint = replace(request.endpoint, hosted_tools={+ "web_search": replace(request.endpoint.hosted_tools["web_search"], replay=native_history),+ })+ history = await build_wire_request(replace(retry, endpoint=endpoint,+ messages=(*retry.messages, completed, UserMessage((TextBlock("next"),)))), gateway=True)+ body = history.body["messages"]+ assert "interrupted" not in json.dumps(body)+ blocks = [b for m in body if isinstance(m["content"], list) for b in m["content"]]+ if native_history:+ assert [b for b in blocks if b["type"] == "web_search_tool_result"] == results+ assert sum(b["type"] == "server_tool_use" for b in blocks) == 2+ else:+ assert sum(b["type"] == "tool_use" and b["name"] == "web_search" for b in blocks) == 2+ assert sum(b["type"] == "tool_result" for b in blocks) == 3+++async def test_failed_attempt_does_not_suppress_a_reused_client_id_after_a_valid_response():+ from core.agent_core.hosted_continuations import effective_deferred_history++ request, paused = await _paused("SC")+ client_id = next(call.id for call in paused.tool_calls if call.name == "read")+ failed = replace(+ _completion(paused),+ content=(*_completion(paused).content, ToolCallBlock(client_id, "read", {"path": "a"})),+ stop_reason="error",+ )+ completed = replace(+ _completion(paused),+ content=(*_completion(paused).content, ToolCallBlock(client_id, "read", {"path": "a"})),+ stop_reason="tool_use",+ )+ failed_result = ToolResultMessage(client_id, "read", (TextBlock("failed"),))+ completed_result = ToolResultMessage(client_id, "read", (TextBlock("new-call-result"),))+ history = (*request.messages, failed, failed_result, completed, completed_result, UserMessage((TextBlock("next"),)))+ effective = effective_deferred_history(history)+ assert failed not in [message for _, message in effective]+ assert failed_result not in [message for _, message in effective]+ endpoint = replace(request.endpoint, hosted_tools={+ "web_search": replace(request.endpoint.hosted_tools["web_search"], replay=True),+ })+ wire = await build_wire_request(replace(request, endpoint=endpoint, messages=history), gateway=True)+ body = json.dumps(wire.body)+ assert "new-call-result" in body and "interrupted" not in body++[email protected]("boundary", ["user", "aborted", "origin", "identity", "ordinary_tools"])+async def test_failed_deferred_attempt_does_not_cross_a_closed_or_different_exchange(boundary):+ from core.agent_core.ai.transform import in_flight_position++ request, paused = await _paused("SSC")+ partial = replace(_completion(paused), stop_reason="error")+ if boundary == "aborted":+ partial = replace(partial, stop_reason="aborted")+ elif boundary == "origin":+ partial = replace(partial, origin=replace(partial.origin, model="another-model"))+ elif boundary == "identity":+ partial = replace(partial, source_identity="sha256:another-account")+ elif boundary == "ordinary_tools":+ paused = replace(paused, content=paused.tool_calls, hosted_summary=None)+ history = (request.messages[0], paused, *request.messages[2:], partial)+ if boundary == "user":+ history = (*history, UserMessage((TextBlock("next"),)))+ assert in_flight_position(history) is None+ wire = await build_wire_request(replace(request, messages=history), gateway=True)+ assert "server_tool_use" not in json.dumps(wire.body["messages"])+ assert "web_search_tool_result" not in json.dumps(wire.body["messages"])+ assert PIN_MODEL_HEADER not in wire.headers+++def _completion(paused):+ blocks = []+ for call in paused.content:+ if not isinstance(call, HostedToolBlock) or call.record.status != "pending":+ continue+ result = {**RESULT, "tool_use_id": call.id}+ completed = anthropic_hosted_block(call.native.payload[0], result, source_id=SOURCE)+ blocks.append(replace(completed, native=replace(completed.native, payload=(result,))))+ return AssistantMessage((*blocks, TextBlock("found")), paused.origin, "stop", hosted_summary=HostedSummary())++[email protected]("native", [True, False])[email protected]("shape", SHAPES)+async def test_later_replay_pairs_once_but_preserves_native_response_boundaries(native, shape):+ request, paused = await _paused(shape)+ completed = _completion(paused)+ endpoint = replace(request.endpoint, hosted_tools={+ "web_search": replace(request.endpoint.hosted_tools["web_search"], replay=native),+ })+ request = replace(request, endpoint=endpoint, messages=(*request.messages, completed, UserMessage((TextBlock("next"),))))+ wire = await build_wire_request(request, gateway=True)+ history = wire.body["messages"]+ assert "interrupted" not in json.dumps(history)+ if native:+ assert history[1] == {"role": "assistant", "content": _blocks(shape)}+ assert history[3]["content"][0] == completed.content[0].native.payload[0]+ assert sum(b.get("type") == "server_tool_use" for m in history if isinstance(m["content"], list) for b in m["content"]) == len(shape) - shape.count("C")+ else:+ assert {b["type"] for b in history[1]["content"]} == {"tool_use"}+ assert [b["name"] for b in history[1]["content"]] == ["read" if kind == "C" else "web_search" for kind in shape]+ results = history[2]["content"]+ assert len(results) == len(shape) and all(b["type"] == "tool_result" for b in results)+ assert "https://avibe.bot/r" in json.dumps(results)+ assert history[3] == {"role": "assistant", "content": [{"type": "text", "text": "found"}]}+++async def test_each_responses_cost_stays_on_a_card_that_ran_and_is_never_counted_again():+ from core.agent_core.messages import HostedCost+ from core.hosted_activity import native_activities+ request, paused = await _paused("FSC")+ paused = replace(paused, hosted_summary=HostedSummary(cost=HostedCost("list", usd=0.01)))+ completed = replace(_completion(paused), hosted_summary=HostedSummary(cost=HostedCost("list", usd=0.01)))+ first, second = native_activities(paused), native_activities(completed)+ assert len(first) == len(second) == 1+ assert first[0].cost.usd == 0.01+ assert second[0].cost.usd == 0.01+ assert sum(card.cost.usd for card in (*first, *second) if card.cost) == 0.02+ assert first[0].cost_calls == second[0].cost_calls == 1++[email protected]("cut", ["prior-summarized", "completion-aborted"])+async def test_a_missing_or_unreplayable_half_never_leaves_an_orphan_native_fragment(cut):+ request, paused = await _paused()+ completed = _completion(paused)+ endpoint = replace(request.endpoint, hosted_tools={+ "web_search": replace(request.endpoint.hosted_tools["web_search"], replay=True),+ })+ if cut == "prior-summarized":+ history = (_request().messages[0], completed)+ else:+ history = (*request.messages, replace(completed, stop_reason="aborted"))+ wire = await build_wire_request(replace(request, endpoint=endpoint, messages=history), gateway=True)+ body = json.dumps(wire.body["messages"])+ assert "server_tool_use" not in body and "web_search_tool_result" not in body+ assert "https://avibe.bot/r" in body and "interrupted" not in bodydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 0e88534d1..2878b0c14 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -437,7 +437,7 @@ scenarios:- 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+ name: Anthropic server-tool continuations carry pending calls by id; pause_turn stays one pinned response with bounded continuations, while a mixed client/server group appends a same-id completion after client results, replays once, and displays one completed card without rewriting context or charging twicestatus: coveredkind: contractlayer: contract@@ -447,6 +447,19 @@ scenarios:- 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- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_counter_past_the_bound_in_any_pause_stays_absent_and_the_response_completes+ - tests/agent_core/ai/test_anthropic_deferred.py::test_mixed_pause_preserves_exact_assistant_and_result_only_user_group+ - tests/agent_core/ai/test_anthropic_deferred.py::test_orphan_result_finishes_prior_call_without_repeating_use_and_keeps_usage_here+ - tests/agent_core/ai/test_anthropic_deferred.py::test_later_replay_pairs_once_but_preserves_native_response_boundaries+ - tests/agent_core/ai/test_anthropic_deferred.py::test_a_result_from_another_source_cannot_complete_the_previous_sources_call+ - tests/agent_core/ai/test_anthropic_deferred.py::test_deferred_completion_never_invents_a_charge_from_a_result_block+ - tests/agent_core/ai/test_anthropic_deferred.py::test_a_steer_waits_until_the_deferred_result_and_never_enters_the_tool_result_user_message+ - tests/agent_core/ai/test_anthropic_deferred.py::test_deferred_result_then_pause_turn_keeps_the_native_exchange_without_replay_evidence+ - tests/agent_core/ai/test_anthropic_deferred.py::test_partial_deferred_failure_retries_the_open_exchange_and_pairs_only_the_valid_result+ - tests/agent_core/ai/test_anthropic_deferred.py::test_failed_deferred_attempt_does_not_cross_a_closed_or_different_exchange+ - tests/test_vibey_agent.py::test_anthropic_deferred_search_shows_only_its_completion_live_and_on_reload+ - tests/test_vibey_agent.py::test_restart_defers_accepted_steer_until_native_search_continuation+ - tests/test_hosted_activity.py::test_deferred_search_has_no_card_or_share_of_an_earlier_search_cost+ - tests/test_agent_activity_service.py::test_reload_omits_only_old_deferred_search_cards- id: MH-HOSTED-VIBEY-007name: An image_generate call goes to the gateway's image endpoint with its arguments alone, after the turn's frozen models accept every argument and its reference images are read as read reads them; the images it returns are saved through the media sink and its record names those files; no base64 enters history, and a call that saved no file is a failed record with its codestatus: covereddiff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.pyindex 99af744b4..68bd14ec1 100644--- a/tests/test_agent_activity_service.py+++ b/tests/test_agent_activity_service.py@@ -346,6 +346,56 @@ def test_a_native_hosted_card_sorts_before_the_response_that_carried_it(isolatedassert [row["id"] for row in detail["rows"]] == ["evt_00063f0000000200cccccccc"][email protected]("stop_reason", ["tool_use", "error", "aborted"])+async def test_reload_omits_only_old_deferred_search_cards(isolated_state, stop_reason):+ """Released pending traces are hidden only for deferred calls, not cut-off streams.++ The completion with the same provider id stays at its own response. Previously+ every pending trace displayed as interrupted; ordinary card tests miss its cause.+ """+ from dataclasses import replace+ from core.agent_core.messages import message_to_dict+ from tests.agent_core.ai.test_anthropic_deferred import _paused++ _, paused = await _paused()+ engine = create_sqlite_engine()+ sid = "ses_old_deferred"+ with engine.begin() as conn:+ scope = _seed_session(conn, session_id=sid)+ _msg(conn, scope, sid, mid="m_user", mtype="user", author="user", created_at="2026-06-01T10:00:00Z", text="q", source="user")+ _msg(conn, scope, sid, mid="m_paused", mtype="assistant", author="agent", created_at="2026-06-01T10:00:02Z",+ content={"model": {"message": message_to_dict(replace(paused, stop_reason=stop_reason))}})+ _msg(conn, scope, sid, mid="m_completed", mtype="result", author="agent", created_at="2026-06-01T10:00:04Z", text="done")+ _evt(conn, scope, sid, eid="e_client", created_at="2026-06-01T10:00:03Z", text="client")+ for eid, status, response_id, when in (+ ("e_pending", "pending", "m_paused", "2026-06-01T10:00:02Z"),+ ("e_completed", "completed", "m_completed", "2026-06-01T10:00:04Z"),+ ):+ conn.execute(agent_events.insert().values(+ id=eid, scope_id=scope, session_id=sid, platform="avibe", event_type="tool_call", visibility="trace",+ content_text=status, content_json=json.dumps({"kind": "toolcall", "hosted": {+ "version": 1, "call_id": "srvtoolu_0", "tool": "web_search", "mode": "native",+ "status": status, "response_id": response_id,+ }}), metadata_json=json.dumps({"precedes_message_id": response_id}), source="agent",+ created_at=when, updated_at=when,+ ))+ with engine.connect() as conn:+ # The compatibility read seeks only the retained traces' owning message ids.+ plan = conn.exec_driver_sql(+ "EXPLAIN QUERY PLAN SELECT id, session_id, content_json FROM messages WHERE id IN (?)",+ ("m_paused",),+ ).all()+ assert any("SEARCH messages USING INDEX" in row[3] and "id=?" in row[3] for row in plan)+ assert not any("SCAN messages" in row[3] or "TEMP B-TREE" in row[3] for row in plan)+ groups = agent_activity_service.list_turn_groups(conn, session_id=sid)["groups"]+ rows = [row for group in groups for row in agent_activity_service.get_turn_group(+ conn, session_id=sid, group_id=group["id"]+ )["rows"]]+ assert [row["id"] for row in rows] == (+ ["e_client", "e_completed"] if stop_reason == "tool_use" else ["e_pending", "e_client", "e_completed"]+ )++def test_a_native_hosted_card_stays_with_its_response_at_the_scan_window_edge(isolated_state, monkeypatch):"""The card sorts just ahead of its response, but belongs to the window that response is in.diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.pyindex aa31e9d50..eb46885b7 100644--- a/tests/test_agent_transcript.py+++ b/tests/test_agent_transcript.py@@ -200,6 +200,7 @@ COMPACTION = { # the current C-9 ``Compaction`` shape (transcript-rows.schema.j}+async def test_every_kind_round_trips_in_one_order_attributed_to_the_turn(engine) -> None:with engine.begin() as conn:home = _scope(conn, "C-home")@@ -460,6 +461,36 @@ async def test_fork_chain_reads_the_ancestry_up_to_each_fork_point(engine) -> Noassert early.context_seq == 2+async def test_turn_context_load_ignores_long_fork_history(engine) -> None:+ with engine.begin() as conn:+ home = _scope(conn, "C-long-root")+ _session(conn, "ses_long_root", home)+ root_input = _accepted_turn(conn, "ses_long_root", home, "root", "turn_long_root")+ store = SQLiteTranscriptStore(engine)+ await store.consume_input("ses_long_root", root_input, _user("root"))+ for index in range(60):+ await store.append_response("ses_long_root", _assistant(f"root-{index}"), final=False, turn_id="turn_long_root")+ root_rows = list(await store.load("ses_long_root"))+ with engine.begin() as conn:+ _session(+ conn,+ "ses_long_child",+ home,+ {"fork_source_session_id": "ses_long_root", "fork_source_context_seq": root_rows[-1].context_seq},+ )+ child_input = _accepted_turn(conn, "ses_long_child", home, "child", "turn_long_child")+ await store.consume_input("ses_long_child", child_input, _user("child"))+ child_response = await store.append_response(+ "ses_long_child", _assistant("child done"), final=False, turn_id="turn_long_child"+ )++ full = list(await store.load("ses_long_child"))+ turn = list(await store.load_turn("ses_long_child", "turn_long_child"))+ assert len(full) == len(root_rows) + 2+ assert [entry.row_id for entry in turn] == [child_input, child_response.row_id]+ assert all(entry.session_id == "ses_long_child" for entry in turn)++async def test_a_cancelled_write_raises_only_after_its_commit_settled(engine) -> None:with engine.begin() as conn:home = _scope(conn, "C-home")@@ -662,6 +693,7 @@ async def test_the_restart_reads_of_a_turns_context_tail_stay_bounded(engine) ->cut_turn = message_deliveries.get_turn(conn, "turn_cut")assert restart_resume_plan(conn, cut_turn) == "rerun"assert committed_final(conn, "ses_cut", "turn_cut") is None+ assert [entry.kind for entry in await store.load_turn("ses_cut", "turn_cut")] == ["input", "response"]# The rerun's end, on the loop: the final's delivery.assert delivered_committed_row(rerun, final.row_id, outward=True) is Nonewith engine.begin() as conn:@@ -685,6 +717,10 @@ async def test_the_restart_reads_of_a_turns_context_tail_stay_bounded(engine) ->r"|session_id=\? AND context_seq>\?)\)")for (sql, _params), plan in zip(statements, plans):+ if sql.lstrip().upper() in {"BEGIN", "COMMIT"}:+ continue+ if "INDEXED BY ix_messages_turn_id" in sql or "INDEXED BY ix_agent_events_turn_sequence_id" in sql or "INDEXED BY ix_message_deliveries_turn" in sql:+ continuesearches = [step for step in plan if step.startswith(("SEARCH", "SCAN"))]if not searches and sql.lstrip().upper().startswith("UPDATE"):continue # a CAS write keyed by the row id, whose plan names no table read@@ -696,6 +732,18 @@ async def test_the_restart_reads_of_a_turns_context_tail_stay_bounded(engine) ->"current_target_turn_id" in sql and "steering" in str(params) and bounded.fullmatch(plan[0])for (sql, params), plan in zip(statements, plans))+ turn_queries = [+ (sql, plan)+ for (sql, _params), plan in zip(statements, plans)+ if "INDEXED BY ix_messages_turn_id" in sql+ or "INDEXED BY ix_agent_events_turn_sequence_id" in sql+ or "INDEXED BY ix_message_deliveries_turn" in sql+ ]+ assert len(turn_queries) == 3+ assert any("ix_messages_turn_id" in step for _, plan in turn_queries for step in plan)+ assert any("ix_agent_events_turn_sequence_id" in step for _, plan in turn_queries for step in plan)+ assert any("ix_message_deliveries_turn" in step for _, plan in turn_queries for step in plan)+ assert all(not step.startswith("SCAN") for _, plan in turn_queries for step in plan)async def test_a_call_instance_is_settled_once_whoever_writes(engine) -> None:diff --git a/tests/test_hosted_activity.py b/tests/test_hosted_activity.pyindex fdebb29e3..be2799644 100644--- a/tests/test_hosted_activity.py+++ b/tests/test_hosted_activity.py@@ -246,6 +246,28 @@ def test_a_source_no_browser_should_open_is_named_but_not_linked():][email protected]("stop_reason", ["tool_use", "error", "aborted"])+async def test_deferred_search_has_no_card_or_share_of_an_earlier_search_cost(stop_reason):+ """The producer omits only a deferred call; stream cuts keep interrupted cards.++ A response can also contain a finished search. Its summary must stay on that+ card, not disappear with the omitted use or be counted on a later completion.+ """+ from tests.agent_core.ai.test_anthropic_deferred import _paused++ _, message = await _paused("FSC")+ cost = HostedCost(basis="reported", usd=0.01)+ message = replace(message, stop_reason=stop_reason, hosted_summary=HostedSummary(cost=cost))+ activities = native_activities(message)+ assert [activity.call_id for activity in activities] == (+ ["srvtoolu_0"] if stop_reason == "tool_use" else ["srvtoolu_0", "srvtoolu_1"]+ )+ assert [activity.cost for activity in activities] == ([cost] if stop_reason == "tool_use" else [None, cost])+ assert all(activity.cost_calls == len(activities) for activity in activities)+ if stop_reason != "tool_use":+ assert activities[-1].status == "pending" and not activities[-1].completed++def test_a_response_scoped_summary_is_shown_once():"""The response's cost covers all its calls, and xAI's cited posts belong to its X search."""diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex f1ce6ead8..51bff40a4 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -2827,13 +2827,13 @@ async def test_a_restart_rerun_waits_for_its_surviving_command_as_the_live_call_if case in {"cancelled", "cancelled_at_shutdown"}:await _until(lambda: harness.agent._run_for(SESSION, cut_turn) is not None, "the rerun never ran")await asyncio.sleep(0.3)- harness.controller.shutdown_requested = case == "cancelled_at_shutdown"+ harness.controller.shutdown_requested = case.endswith("at_shutdown")# The Turn task is cancelled directly, without ``handle_stop``.resumed.cancel()with pytest.raises(asyncio.CancelledError):await asyncio.wait_for(resumed, timeout=20)results = [entry for entry in await harness.context_rows() if entry.kind == "tool_result"]- if case == "cancelled":+ if not harness.controller.shutdown_requested:assert "Stopped by the user" in results[0].message.content[0].textassert suite.jobs.status(job_id).state != "running"else:@@ -3359,6 +3359,229 @@ async def test_a_native_search_is_kept_as_one_hosted_call_and_replayed_next_turn[email protected]("platform", ["avibe", "telegram"])[email protected]("outcome", ["completed", "error", "stop"])+async def test_anthropic_deferred_search_shows_only_its_completion_live_and_on_reload(+ engine, session, tmp_path, published, outcome, platform, monkeypatch+):+ """The real parser, loop, immutable store, dispatcher and activity projection agree at every boundary."""+ import httpx+ from modules.agents.vibey.models import registry_providers+ from storage import agent_activity_service+ from tests.agent_core.ai.test_anthropic_deferred import USE, RESULT, _sse+ monkeypatch.setattr("core.message_mirror._activity_streaming_enabled", lambda: True)++ started, release, client_shown = asyncio.Event(), asyncio.Event(), asyncio.Event()+ async def client_tool(arguments, ctx):+ started.set()+ if outcome == "stop":+ await ctx.cancel.wait()+ else:+ await release.wait()+ return ToolResult((text("client result"),))++ sent = []+ served = {"provider": "test-provider", "api": "anthropic", "model": "test-model", "source": "src_served00001"}+ def gateway(request):+ sent.append(json.loads(request.content))+ if len(sent) == 1:+ body = _sse([USE, {"type": "tool_use", "id": "toolu_client", "name": "echo", "input": {}}])+ elif outcome == "error":+ return httpx.Response(400, json={"type": "error", "error": {"type": "invalid_request_error", "message": "test error"}})+ else:+ body = _sse([RESULT, {"type": "text", "text": "found"}], stop="end_turn", searches=1)+ return httpx.Response(200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(served)}, text=body)++ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ harness = _Harness(engine, tmp_path, platform, [], tools=[FakeTool("echo", execute=client_tool)],+ providers=registry_providers(media_loader=None, client=client))+ real_emit = harness.agent._emit_tool_line+ async def emit_client(*args, **kwargs):+ await real_emit(*args, **kwargs)+ client_shown.set()+ harness.agent._emit_tool_line = emit_client+ harness.controller.hub_source_id = "src_served00001"+ harness.controller.im_client.supports_message_editing = lambda context=None: False+ harness.controller.hub_hosted_tools = {"web_search": {+ "native": "assumed", "declaration": {"type": "web_search_20250305", "name": "web_search"},+ "include": [], "replay": "unsupported"+ }}+ request = harness.request("search")+ running = asyncio.create_task(harness.agent.handle_message(request))+ await asyncio.wait_for(started.wait(), timeout=5)+ await asyncio.wait_for(client_shown.wait(), timeout=5)+ before = await harness.context_rows()+ original = next(row for row in before if row.kind == "response")+ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=SESSION)["groups"]+ detail = agent_activity_service.get_turn_group(conn, session_id=SESSION, group_id=groups[-1]["id"])+ assert not any(row.get("hosted") for row in detail["rows"])+ assert not any("avibe release" in line for line in harness.controller.im_client.sent)+ if outcome == "stop":+ assert await harness.agent.handle_stop(AgentRequest(**{**request.__dict__, "message": "stop"}))+ else:+ release.set()+ await asyncio.wait_for(running, timeout=10)+ if outcome == "stop":+ with engine.begin() as conn:+ message_deliveries.terminalize_turn(+ conn, _turn(request.context), outcome="canceled", settled_by="test_stop", evidence_kind="test"+ )++ rows = await harness.context_rows()+ assert next(row for row in rows if row.row_id == original.row_id) == original+ with engine.connect() as conn:+ groups = agent_activity_service.list_turn_groups(conn, session_id=SESSION)["groups"]+ details = [agent_activity_service.get_turn_group(conn, session_id=SESSION, group_id=group["id"]) for group in groups]+ cards = [row["hosted"] for detail in details for row in detail["rows"] if row.get("hosted")]+ assert len(cards) == (1 if outcome == "completed" else 0)+ if outcome == "completed":+ [card] = cards+ assert card["response_id"] != original.row_id and card["status"] == "completed"+ # The client-tool activity comes first; the completed search stays at response 2.+ activity_rows = [row for detail in details for row in detail["rows"]]+ assert next(index for index, row in enumerate(activity_rows) if row.get("hosted")) > 0+ lines = [line for line in harness.controller.im_client.sent if "avibe release" in line]+ assert len(lines) == (1 if outcome == "completed" else 0)+ if platform == "avibe":+ live = [payload["content"]["hosted"] for name, payload in published+ if name == "message.new" and (payload.get("content") or {}).get("hosted")]+ assert live == cards+ if outcome == "completed":+ assert all("Cut off" not in line for line in lines) and len(card["sources"]) == 1+ assert sent[1]["tools"] == sent[0]["tools"]+ assert sent[1]["messages"][-1]["role"] == "user"+ assert {b["type"] for b in sent[1]["messages"][-1]["content"]} == {"tool_result"}+ responses = [row.message for row in rows if row.kind == "response"]+ assert not responses[0].hosted_summary.counts+ assert responses[1].hosted_summary.counts == {"web_search_requests": 1}+ else:+ assert not lines+++[email protected]("client_finished", [False, True])[email protected]("case", ["continue", "stopped", "preflight_failed", "partial_failure"])+async def test_restart_defers_accepted_steer_until_native_search_continuation(+ engine, session, tmp_path, published, client_finished, case, continuation_policy+):+ """T3 must not insert a recovered steer into the tool-result-only continuation.++ The old path consumes it before Agent.resume; an in-process steer test cannot+ see this. Seed the real parser's committed cut, discard the adapter, then run+ startup recovery twice and the durable Turn's actual transcript resume.+ """+ import httpx+ from dataclasses import replace+ from core.agent_core.ai._common import PIN_MODEL_HEADER, PIN_SOURCE_HEADER+ from modules.agents.vibey.models import registry_providers+ from tests.agent_core.ai.test_anthropic_deferred import _paused, _sse, RESULT+ from tests.agent_core.fakes import ORIGIN++ continuation_policy(initial_delay_s=0)+ sent = []+ def gateway(wire):+ sent.append(wire)+ complete_at = 2 if case == "partial_failure" else 1+ results = [{**RESULT, "tool_use_id": f"srvtoolu_{index}"} for index in (0, 1)]+ blocks = [*results, {"type": "text", "text": "found"}] if len(sent) <= complete_at else [+ {"type": "text", "text": "steer answered"}+ ]+ body = _sse(blocks, stop="end_turn", searches=2 if len(sent) == complete_at else 0)+ if case == "partial_failure" and len(sent) == 1:+ body = _sse(results[:1], stop=None, searches=1).removesuffix('data: {"type": "message_stop"}\n\n')+ served = {"provider": "test-provider", "api": "anthropic", "model": "test-model", "source": "src_served00001"}+ return httpx.Response(200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(served)},+ text=body)++ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ harness = _Harness(engine, tmp_path, "avibe", [], providers=registry_providers(media_loader=None, client=client))+ harness.controller.hub_source_id = "src_served00001"+ harness.controller.hub_hosted_tools = {"web_search": {+ "native": "assumed", "declaration": {"type": "web_search_20250305", "name": "web_search"},+ "include": [], "replay": "unsupported",+ }}+ request = harness.request("search")+ turn_id = _turn(request.context)+ harness.controller._native_start(request.context)+ harness.agent.store.bind_agent(SESSION, None, turn_id=turn_id)+ await harness.agent.store.consume_input(+ SESSION, request.context.platform_specific["delivery_id"], UserMessage((text("search"),))+ )+ paused_request, paused = await _paused("SSC")+ paused = replace(paused, origin=ORIGIN, source_identity="sha256:test-source-identity")+ original = await harness.agent.store.append_response(SESSION, paused, final=False)+ steer_id, attempt = harness.open_steer("and the docs", turn_id, harness.controller.started[-1])+ harness.accept_steer(steer_id, attempt, turn_id)+ if client_finished:+ await harness.agent.store.append_tool_result(SESSION, paused_request.messages[-1], details={})+ if case == "stopped":+ with engine.begin() as conn:+ message_deliveries.terminalize_turn(+ conn, turn_id, outcome="canceled", settled_by="test_stop", evidence_kind="test"+ )+ else:+ with engine.begin() as conn:+ turn = message_deliveries.get_turn(conn, turn_id)+ assert message_deliveries.rotate_restart_generation(+ conn, turn_id, expected_version=int(turn["version"]), streak=1, response_seq=original.context_seq+ )+ harness.new_agent()+ await harness.agent.recover_runtime_state()+ await harness.agent.recover_runtime_state()+ rows = await harness.context_rows()+ if case == "stopped":+ assert rows[-1].row_id == steer_id and not sent+ return+ assert all(row.row_id != steer_id for row in rows)+ context = _context("avibe", SESSION, turn_id=turn_id, delivery_id=request.context.platform_specific["delivery_id"])+ context.platform_specific.update({"vibey_resume": True, "vibey_source_turn_id": turn_id})+ scheduled = []+ if case == "preflight_failed":+ async def unavailable(*_args):+ raise RuntimeError("Source unavailable")+ harness.agent._preflight = unavailable+ harness.controller.vibey_recovery = SimpleNamespace(ensure=lambda: scheduled.append(True))+ await harness.agent.handle_message(AgentRequest(**{**request.__dict__, "context": context, "message": "", "user_message": ""}))+ if case == "preflight_failed":+ assert scheduled+ _owner_settled(engine, request)+ await harness.agent.recover_runtime_state()+ assert (await harness.context_rows())[-1].row_id == steer_id and not sent+ return++ assert len(sent) == (3 if case == "partial_failure" else 2)+ continuation, answered = json.loads(sent[0].content), json.loads(sent[-1].content)+ if case == "partial_failure":+ retried = json.loads(sent[1].content)+ assert retried["messages"] == continuation["messages"]+ assert retried["tools"] == continuation["tools"]+ assert sent[1].headers[PIN_SOURCE_HEADER] == "src_served00001"+ assert sent[1].headers[PIN_MODEL_HEADER] == "test-model"+ assert sent[0].headers[PIN_SOURCE_HEADER] == "src_served00001"+ assert sent[0].headers[PIN_MODEL_HEADER] == "test-model"+ assert continuation["messages"][-1]["role"] == "user"+ assert {block["type"] for block in continuation["messages"][-1]["content"]} == {"tool_result"}+ assert "and the docs" not in json.dumps(continuation)+ assert "and the docs" in json.dumps(answered)+ rows = await harness.context_rows()+ completion = next(row for row in rows if row.kind == "response" and row.row_id != original.row_id+ and row.message.stop_reason != "error")+ hosted = [block for block in completion.message.content if isinstance(block, HostedToolBlock)]+ assert [(block.id, block.record.status) for block in hosted] == [+ ("srvtoolu_0", "completed"), ("srvtoolu_1", "completed"),+ ]+ if case == "partial_failure":+ [partial] = [row for row in rows if row.kind == "response" and row.message.stop_reason == "error"]+ assert partial.message.hosted_summary.counts == {"web_search_requests": 1}+ assert completion.message.hosted_summary.counts == {"web_search_requests": 2}+ assert sum((row.message.hosted_summary.counts.get("web_search_requests", 0)+ if row.message.hosted_summary else 0) for row in rows if row.kind == "response") == 3+ [steer] = [row for row in rows if row.row_id == steer_id]+ assert completion.context_seq < steer.context_seq+ assert next(row for row in rows if row.row_id == original.row_id) == original++def _anthropic_reply(*blocks: str, stop_reason: str) -> str:"""An Anthropic stream of whole content blocks, each given as its ``content_block_start`` JSON."""events = ['data: {"type":"message_start","message":{"usage":{}}}\n\n']