Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agent-core): implement controllable agent loop and transcript projection (#2335)
Call White77c36056ff08
diff --git a/core/agent_core/agent/README.md b/core/agent_core/agent/README.mdnew file mode 100644index 000000000..0861a7e89--- /dev/null+++ b/core/agent_core/agent/README.md@@ -0,0 +1,187 @@+# Agent loop (P1)++The change contract is C-3 plus C-5 projection steps 1, 2, 5, and 6 from+`docs/plans/agent-core-contracts/`. Foundation types are unchanged.++## Integration++Import `Agent` from `agent.loop`, input/snapshot/hook types from `agent.hooks`,+`ModelRouter` and `ModelSelection` from `agent.models`, and the shared+`ModelCapabilities` from `ai.provider`.+The adapter supplies the Session id, working directory, explicit environment,+rebuilt system prompt, providers, transcript store, and job host.++```python+agent = Agent(+ session_id=session_id, models=router, tools=[], hooks=hooks,+ store=store, jobs=job_host, cwd=cwd, env=env, system=system,+)+# Job-backed tools receive this exact wrapper, not the unwrapped host.+agent.set_tools(build_tools(jobs=agent.jobs))+async for event in agent.run(AgentInput(message_id, rendered_input), turn_id=turn_id):+ await deliver(event)+# Return accepted but unconsumed inputs after an early end, abort, or error.+pending = await agent.take_pending_inputs()+```++`steer` and `follow_up` are async and return whether the active run accepted the+input. `False` means the adapter keeps the persisted input in the P3 queue.+An accepted input remains owned by the Agent until consumed or returned by+`take_pending_inputs()`. Early termination preserves those queues; the adapter+returns their durable rows to P3. A new run is refused until they are collected.+`abort`, `set_tools`, and `snapshot` are synchronous on the same event loop.+Only one run can use an Agent at a time. The adapter remains responsible for+excluding multiple Agent instances writing the same Session.++The router resolves endpoint and capabilities before each model attempt;+`provider_for(protocol)` selects transport after request hooks have run.+An explicitly tool-incapable route is refused during preflight, before hooks or+input consumption. The run yields a clear error and terminal event without a+provider request. Unknown tool support still sends tools. Unknown/false image+and reasoning support is disabled; reasoning also requires a declared effort.+The configured output budget defaults to 8,192 and is capped by the provider's+maximum (8,192 when unknown). `ModelSelection.context_window` exposes the C-9+budget (128,000 when unknown); context management itself remains P3.+The shared nullable source capabilities are not changed into guessed values.+Before-model rewrites affect a detached request only, including endpoint headers.+The router's cached selection is never mutated. Tools execute against the+registry captured for that request, restricted to its advertised names.+A before-run setup affects that run only; `set_tools` changes the configured+set as well as the next request of an active run.++Hooks subclass `Hooks`, override async methods, and mutate `RunContext.state`+with exact JSON data (string-keyed dicts, lists, JSON scalars, finite numbers).+Non-JSON Python values are hook errors, never silently coerced. Representation+comparison distinguishes booleans, integers and floats and avoids duplicate+state rows. Rewrites compose in registration order; the first `Deny` or+`End` stops that hook chain. State changes append versioned `agent_state` rows+at commit points. A snapshot describes committed context and committed state.+The store/adapter owns fork ancestry; the engine does not copy parent rows.++`AgentError.kind` is the adapter's stable error discriminator.+`AgentError.message` is engine/provider diagnostic detail, never display copy.+The adapter owns Session language, maps kinds to `vibe/i18n` messages, and tests+English/Chinese rendering at its delivery boundary. Model-facing tool result+text is separate from localized user-facing error delivery.+The stable `empty_response` kind means a tool-free final response had no+non-whitespace reply text (including thinking-only output); the adapter must+localize that error rather than deliver a silent success.++## Invariants and evidence++- Responses are committed before `MessageCommitted`, and tool results before+ `ToolFinished`. Hook state is written before the associated context entry, so+ a failed state write cannot hide a committed reply. A later input-write failure+ still announces prior committed rows. Event sequences start at zero per Turn+ and increase strictly; their identity field is `turn_id`.+- Finality is decided with input admission locked before inserting the response.+ A final response closes admission; a competing late steer is refused.+ A final refusal/safety stop retains the provider's text. Without a visible+ reply, it still commits a final result, then emits a typed error and ends.+ Other empty successful finals likewise stay committed, but emit+ `empty_response` and end as error. A received terminal is never retried.+ Empty non-final responses with queued inputs can still continue to a reply;+ tool calls, explicit hook end, and tool termination retain their contracts.+- A tool batch runs sequentially and commits results in call order. Steers+ enter after the whole batch. Follow-ups enter at natural termination after+ steers have been consumed. A terminating tool still finishes its batch.+ An `Exception` from `Tool.execute` becomes an error result (at most 500+ characters), with a logged traceback; the run continues. `BaseException`,+ including `CancelledError`, retains lifecycle semantics.+- Hook end commits the current step and records policy error results for+ unexecuted calls. `End` is a directive, not a primary outcome in the generic+ hook helper. The owning request/loop stage selects `ended_by_hook` only after+ its required state and step writes succeed; a failed required write ends in+ error, and abort around those writes retains the aborted outcome. Cleanup+ failures remain diagnostics. It makes no further model request.+- One explicit `RunScope` owns operation admission and joining on Python 3.10.+ Lazy factories prevent aborted runs from creating callback/store work.+ Abort cancels pending provider/tool/hook/backoff operations and waits for their+ cleanup. Admitted store commits finish before ownership is released; connected+ consumers still receive the committed-row event, and the run ends aborted.+ Cleanup runs in a separately joined task outside cancelled admission.+ Closing the event iterator also cleans up its worker.+ A dependency that independently raises cancellation produces an error and a+ terminal aborted event; it is not mistaken for a closed iterator.+- One outcome owner records the first primary cause. Stream closure, cleanup+ hooks and cleanup cancellation add diagnostics without overwriting that cause.+ The only exception is a foreground job that still cannot be killed, which+ upgrades completed to error. A received terminal is admitted and committed+ before closing its stream; close failure does not retry it or skip its tools.+ Every message-bearing write passes the projector's actual invariants through+ the pure `validate_message_append` helper before persistence. This covers+ initial/queued input consumption, full/partial responses, post-hook tool+ results (including terminating tools), and durable recovery results. Invalid+ candidates cannot poison resume: no unsupported message is appended/consumed,+ no committed-row event announces it, and prior valid entries remain intact.+ An invalid tool/hook result ends the run with an error; its call remains open+ for deterministic projection and T2 settlement. Recovery rejects invalid+ renderer output before append, so a corrected retry can finish settlement.+ The projector also rechecks every call's mutable arguments using the+ foundation's public `require_json_value`. Invalid JSON shapes raise+ `ProjectionError` with call and row context, before admission or replay;+ there is no separate loop-owned JSON argument validator.+- Every tool execution exit releases that `(Session, tool call)`'s remaining+ foreground handles, including success and failure. Final cleanup sweeps all+ remaining Session-owned handles on every terminal path. Handed-over jobs are+ never touched. Failed kills remain owned, other handles are still attempted,+ and an explicit cleanup error prevents a silently successful run.+- Transient retries have an attempt/time budget (at most 3 retries within 120+ seconds; default 2), exponential backoff, and honor Retry-After. An expired+ budget ends with the original error, including when delay or route resolution+ crosses the deadline. Route resolution precedes request admission: expiry is+ checked before route validation, projection, rehydration or hooks can run.+ Any streamed event or partial forbids retry. Overflow emits an error and ends+ as `context_exhausted`.+- Projection consumes store-resolved ancestry, sorts by sequence, restores hook+ state, and answers orphans with deterministic interrupted text. It has no job+ host or external settler. The caller supplies rebuilt system/state messages.+- Before resume, the adapter calls `agent.recovery.settle_open_calls` under its+ Session writer lock. It appends a governed result for each open call: exited+ output, a running job handed to Watch, or synthetic interrupted text.+ A call without job state (including `write` and `edit`) explicitly warns that+ it may or may not have completed and instructs the model to re-read the file+ before continuing. Each committed outcome is skipped on retry. Late settlement+ rows are projected alongside their original call; fork cuts only see included+ outcomes. After settlement the adapter marks the old Turn interrupted (T4);+ recovery never resumes the model or repeats the tool automatically.++`tests/agent_core/agent/` verifies C1, transient C2, C3, C4, C5, resume C6, and+C9 against the actual requests recorded by `tests/agent_core/fakes.py`.+It also covers each orphan job state, retry classification, cancellation during+job ownership transitions, settlement crash/retry windows, and event consumer+closure. One lifecycle table covers pre-start/storage abort, model/tool abort,+dependency cancellation, consumer closure, tool exceptions, normal completion,+and cleanup. Separate probes cover failed kills and cancellation during commit.+A primary-outcome/cleanup table checks reasons, durable rows, event order,+commit-before-close, tools after close failure, and cleanup diagnostics.+A hook-stage/required-commit table distinguishes successful end directives+from failed state/result writes and abort before, during, or after a commit.+The admission source matrix checks provider responses/partials, tools, result+rewrites, terminating tools, initial inputs and queued steer/follow-up inputs.+Recovery separately checks invalid renderer output after a prior good commit.+Both boundaries prove a fresh Agent can continue over the same store.+Valid-then-mutated argument cases cover Done and partial responses, with a+separate loaded-ancestry check. The final-reply table covers empty, whitespace,+thinking-only and visible replies across stop/length/refusal/safety and+pending-input continuation. The primary/cleanup table includes empty_response.+These are in-memory engine checks; production provider/store/Watch integration+is a later layer.++## Known by design++- No compaction, context edits, overflow recovery, or provider transport here.+ A P3 row raises `ProjectionError`; it is never silently ignored.+- Store operations remain separate transactions under the queue lock (approved+ for v1 by the orchestrator). A crash between a non-final response and input+ consumption leaves that input queued for adapter recovery.+- Input rendering/environment deltas, delivery outbox, actual Session forking,+ job-to-call lookup, Watch implementation, and output governance belong to the+ adapter or tools. Recovery's renderer receives `(call, job_id, status, watch_id)`+ and returns a governed `ToolResult`; job keys include the original Session.+ The adapter serializes recovery with active runs. `JobHost.hand_over` must+ reuse a job's existing Watch when recovery retries an interrupted commit.+- A stream error may persist its partial response as non-final evidence, but no+ partial tool call executes. A later projection settles missing results.+- This lane validates engine boundaries with fakes. No live service, credentials,+ network provider, production state, or user-facing integration is exercised.diff --git a/core/agent_core/agent/hooks.py b/core/agent_core/agent/hooks.pynew file mode 100644index 000000000..136280c47--- /dev/null+++ b/core/agent_core/agent/hooks.py@@ -0,0 +1,102 @@+"""C-3 lifecycle hooks.++Subclass Hooks and override only the needed methods. Hooks run in registration+order; replacement values compose, while the first Deny or End stops that hook+chain. Mutable JSON state belongs to RunContext and is persisted at commit points.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Mapping, Optional++from core.agent_core.agent.events import RunEndReason+from core.agent_core.ai.provider import ModelRequest+from core.agent_core.cancel import CancelToken+from core.agent_core.messages import AssistantMessage, ToolCallBlock, UserMessage+from core.agent_core.tools.base import Tool, ToolResult+++@dataclass(frozen=True)+class AgentInput:+ """An existing Avibe input row plus its already rendered model content."""++ message_id: str+ message: UserMessage++ def __post_init__(self) -> None:+ if not self.message_id:+ raise ValueError("an input needs its stored message row id")+++@dataclass(frozen=True)+class Snapshot:+ session_id: str+ context_seq: int+ state: Mapping[str, Any]+++@dataclass+class RunContext:+ session_id: str+ turn_id: str+ cancel: CancelToken+ state: dict[str, Any] = field(default_factory=dict)+++@dataclass(frozen=True)+class RunSetup:+ system: Optional[str] = None+ tools: Optional[tuple[Tool, ...]] = None+++@dataclass(frozen=True)+class End:+ """Finish after committing the current step."""+++@dataclass(frozen=True)+class SkipTools:+ """Settle every call in the response with a policy error."""+++@dataclass(frozen=True)+class Deny:+ reason: str+++@dataclass(frozen=True)+class AlterArgs:+ arguments: Mapping[str, Any]+++@dataclass(frozen=True)+class AlterResult:+ result: ToolResult+++@dataclass(frozen=True)+class RunOutcome:+ turn_id: str+ reason: RunEndReason+ snapshot: Snapshot+++class Hooks:+ async def before_run(self, input: AgentInput, ctx: RunContext) -> Optional[RunSetup]:+ return None++ async def before_model(self, request: ModelRequest, ctx: RunContext) -> ModelRequest | End | None:+ return None++ async def after_model(self, message: AssistantMessage, ctx: RunContext) -> SkipTools | End | None:+ return None++ async def before_tool(self, call: ToolCallBlock, ctx: RunContext) -> Deny | AlterArgs | End | None:+ return None++ async def after_tool(self, call: ToolCallBlock, result: ToolResult, ctx: RunContext) -> AlterResult | End | None:+ return None++ async def after_run(self, outcome: RunOutcome, ctx: RunContext) -> None:+ return Nonediff --git a/core/agent_core/agent/jobs.py b/core/agent_core/agent/jobs.pynew file mode 100644index 000000000..192125182--- /dev/null+++ b/core/agent_core/agent/jobs.py@@ -0,0 +1,104 @@+"""Loop ownership of foreground jobs using only the C-7 JobHost protocol."""++from __future__ import annotations++import asyncio+from typing import Mapping, Optional++from core.agent_core.tools.base import JobHost, JobStatus+++class ForegroundCleanupError(RuntimeError):+ """Every owned handle was attempted, but some could not be released."""+++class TrackingJobHost:+ """Pass this same host to job-backed tools and their owning Agent.++ A successful handover removes a handle from foreground ownership. Shielding+ start/handover lets their ownership transition finish before cancellation+ cleanup decides which jobs it must kill.+ """++ def __init__(self, host: JobHost) -> None:+ self.host = host+ self._foreground: dict[str, tuple[str, str]] = {}++ async def start(+ self,+ command: str,+ *,+ cwd: str,+ env: Mapping[str, str],+ timeout_s: Optional[float],+ session_id: str,+ tool_call_id: str,+ ) -> str:+ task = asyncio.create_task(+ self.host.start(+ command,+ cwd=cwd,+ env=env,+ timeout_s=timeout_s,+ session_id=session_id,+ tool_call_id=tool_call_id,+ )+ )+ try:+ job_id = await asyncio.shield(task)+ except asyncio.CancelledError:+ job_id = await task+ self._foreground[job_id] = (session_id, tool_call_id)+ raise+ self._foreground[job_id] = (session_id, tool_call_id)+ return job_id++ def status(self, job_id: str) -> JobStatus:+ status = self.host.status(job_id)+ if status.state != "running":+ self._foreground.pop(job_id, None)+ return status++ async def wait(self, job_id: str, *, deadline_s: Optional[float]) -> JobStatus:+ status = await self.host.wait(job_id, deadline_s=deadline_s)+ if status.state != "running":+ self._foreground.pop(job_id, None)+ return status++ def output(self, job_id: str, since: int = 0) -> tuple[bytes, int]:+ return self.host.output(job_id, since)++ def output_path(self, job_id: str) -> str:+ return self.host.output_path(job_id)++ async def kill(self, job_id: str) -> None:+ await self.host.kill(job_id)+ self._foreground.pop(job_id, None)++ async def hand_over(self, job_id: str) -> str:+ task = asyncio.create_task(self.host.hand_over(job_id))+ try:+ watch_id = await asyncio.shield(task)+ except asyncio.CancelledError:+ await task+ self._foreground.pop(job_id, None)+ raise+ self._foreground.pop(job_id, None)+ return watch_id++ async def kill_foreground(self, session_id: str, *, tool_call_id: Optional[str] = None) -> None:+ failures = []+ for job_id, (owner, call) in list(self._foreground.items()):+ if owner != session_id or (tool_call_id is not None and call != tool_call_id):+ continue+ try:+ if self.status(job_id).state == "running":+ await self.kill(job_id)+ else:+ self._foreground.pop(job_id, None)+ except (Exception, asyncio.CancelledError) as error:+ # Keep failed handles owned for the final run sweep, and do+ # not let one failed kill prevent release of the other jobs.+ failures.append(f"{job_id}: {type(error).__name__}: {error}")+ if failures:+ raise ForegroundCleanupError("Failed to release foreground jobs: " + "; ".join(failures))diff --git a/core/agent_core/agent/lifecycle.py b/core/agent_core/agent/lifecycle.pynew file mode 100644index 000000000..7bf35abb1--- /dev/null+++ b/core/agent_core/agent/lifecycle.py@@ -0,0 +1,80 @@+"""One run's admission and child-operation ownership (Python 3.10 asyncio).++Factories, never pre-created awaitables, cross this boundary. Interruptible work+is cancelled and joined before it leaves the scope. Once admitted, a store+transaction is joined without interruption so its caller receives the commit.+Cleanup runs outside this scope, after admission has closed.+"""++from __future__ import annotations++import asyncio+from typing import Awaitable, Callable, TypeVar++from core.agent_core.cancel import CancelToken++T = TypeVar("T")+++class RunAborted(Exception):+ """The run no longer admits ordinary work."""+++class RunScope:+ def __init__(self, cancel: CancelToken) -> None:+ self.cancel = cancel+ self._closed = False+ self._operations: dict[asyncio.Future, bool] = {}++ def check(self) -> None:+ if self._closed or self.cancel.cancelled:+ raise RunAborted()++ def stop(self) -> None:+ self._closed = True++ async def call(self, factory: Callable[[], Awaitable[T]], *, interruptible: bool = True) -> T:+ self.check()++ async def invoke() -> T:+ # Cancellation may arrive between admission and task scheduling.+ self.check()+ return await factory()++ operation = asyncio.create_task(invoke())+ self._operations[operation] = interruptible+ cancelled = None+ try:+ if not interruptible:+ # A consumer closing during a commit still waits for the+ # transaction's outcome; the next admission sees cancellation.+ try:+ return await asyncio.shield(operation)+ except asyncio.CancelledError:+ return await operation+ cancelled = asyncio.create_task(self.cancel.wait())+ ready, _ = await asyncio.wait({operation, cancelled}, return_when=asyncio.FIRST_COMPLETED)+ if cancelled in ready:+ raise RunAborted()+ return await operation+ finally:+ if interruptible and not operation.done():+ operation.cancel()+ if cancelled is not None and not cancelled.done():+ cancelled.cancel()+ joined = asyncio.gather(operation, *([cancelled] if cancelled is not None else []), return_exceptions=True)+ try:+ await asyncio.shield(joined)+ except asyncio.CancelledError:+ await joined+ raise+ finally:+ self._operations.pop(operation, None)++ async def close(self) -> None:+ self.stop()+ for task, interruptible in tuple(self._operations.items()):+ if interruptible and not task.done():+ task.cancel()+ if self._operations:+ await asyncio.gather(*self._operations, return_exceptions=True)diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pynew file mode 100644index 000000000..42b7125a7--- /dev/null+++ b/core/agent_core/agent/loop.py@@ -0,0 +1,712 @@+"""C-3 in-process agent loop; persistence precedes every committed-row event.++Queue semantics informed by Pi (MIT), packages/agent/src/agent-loop.ts, and the+bare-loop control experiment. This is an Avibe implementation, not a port.+"""++from __future__ import annotations++import asyncio+import json+import logging+import time+from collections import deque+from contextlib import asynccontextmanager, suppress+from copy import deepcopy+from dataclasses import replace+from typing import Any, AsyncIterator, Awaitable, Callable, Mapping, Optional, Sequence, TypeVar++from core.agent_core.agent.events import (+ AgentError,+ AgentEvent,+ AssistantTextDelta,+ AssistantThinkingDelta,+ MessageCommitted,+ RunEnded,+ RunEndReason,+ RunStarted,+ SteerApplied,+ ToolFinished,+ ToolProgress,+ ToolStarted,+)+from core.agent_core.agent.hooks import (+ AgentInput,+ AlterArgs,+ AlterResult,+ Deny,+ End,+ Hooks,+ RunContext,+ RunOutcome,+ SkipTools,+ Snapshot,+)+from core.agent_core.agent.jobs import TrackingJobHost+from core.agent_core.agent.lifecycle import RunAborted as _Aborted, RunScope+from core.agent_core.agent.models import DEFAULT_MAX_OUTPUT_TOKENS, ModelRouter, ModelSelection, RetryPolicy+from core.agent_core.agent.outcome import OutcomeOwner+from core.agent_core.agent.state import HookStateError, state_representation+from core.agent_core.ai.provider import (+ Done,+ ModelRequest,+ ProviderError,+ TextDelta,+ ThinkingDelta,+)+from core.agent_core.cancel import CancelToken+from core.agent_core.harness.projection import ProjectionError, project, validate_message_append+from core.agent_core.harness.store import ContextEntry, TranscriptStore+from core.agent_core.messages import AssistantMessage, Message, TextBlock, ToolCallBlock, ToolResultMessage, text+from core.agent_core.tools.base import JobHost, Tool, ToolContext, ToolResult++T = TypeVar("T")+logger = logging.getLogger(__name__)+++class _Ended(Exception):+ pass+++class ProviderProtocolViolation(ValueError):+ """A model response cannot be admitted to the canonical transcript."""+++class UnsupportedModelRoute(ValueError):+ """The selected model cannot provide the tools required by the agent."""+++class Agent:+ """One Session's single writer. All methods run on the same asyncio loop.++ ``turn_id`` is the Avibe Turn id. ``steer``/``follow_up`` return False after+ finality closes admission, allowing the adapter to retain the input in P3.+ Tools that launch jobs must use ``agent.jobs`` (or pass one TrackingJobHost+ both here and to the tools) so abort owns every foreground handle.+ """++ def __init__(+ self,+ *,+ session_id: str,+ models: ModelRouter,+ tools: Sequence[Tool],+ hooks: Sequence[Hooks],+ store: TranscriptStore,+ jobs: JobHost,+ cwd: str,+ env: Optional[Mapping[str, str]] = None,+ system: str = "",+ max_tokens: int = DEFAULT_MAX_OUTPUT_TOKENS,+ reasoning_effort: Optional[str] = None,+ retry: RetryPolicy = RetryPolicy(),+ rehydrate: Optional[Callable[[Mapping[str, Any]], Sequence[Message]]] = None,+ ) -> None:+ self.session_id = session_id+ self.models = models+ self.store = store+ self.jobs = jobs if isinstance(jobs, TrackingJobHost) else TrackingJobHost(jobs)+ self.hooks = tuple(hooks)+ self.cwd, self.env = cwd, dict(env or {})+ self.system = system+ if max_tokens <= 0:+ raise ValueError("max_tokens must be positive")+ self.max_tokens, self.reasoning_effort = max_tokens, reasoning_effort+ self.retry = retry+ self.rehydrate = rehydrate+ self._tools: dict[str, Tool] = {}+ self._run_tools: Optional[dict[str, Tool]] = None+ self.set_tools(tools)+ self._lock = asyncio.Lock()+ self._steers: deque[AgentInput] = deque()+ self._follow_ups: deque[AgentInput] = deque()+ self._running = False+ self._open = False+ self._consumer_closed = False+ self._ctx = RunContext(session_id, "", CancelToken())+ self._scope = RunScope(self._ctx.cancel)+ self._outcome = OutcomeOwner()+ self._rows: list[ContextEntry] = []+ self._committed_state: dict[str, Any] = {}+ self._committed_state_json = "{}"+ self._seq = 0++ def set_tools(self, tools: Sequence[Tool]) -> None:+ names = [tool.spec.name for tool in tools]+ if len(names) != len(set(names)):+ raise ValueError("tool names must be unique")+ self._tools = dict(zip(names, tools))+ if self._run_tools is not None:+ self._run_tools = dict(self._tools)++ async def steer(self, input: AgentInput) -> bool:+ async with self._lock:+ if not self._open or self._ctx.cancel.cancelled:+ return False+ self._steers.append(deepcopy(input))+ return True++ async def follow_up(self, input: AgentInput) -> bool:+ async with self._lock:+ if not self._open or self._ctx.cancel.cancelled:+ return False+ self._follow_ups.append(deepcopy(input))+ return True++ async def take_pending_inputs(self) -> tuple[AgentInput, ...]:+ """Return accepted but unconsumed inputs to the adapter's P3 queue.++ Call after the run closes admission (normally after RunEnded). The+ adapter still has the original durable rows; this transfers admission+ ownership back in steer/follow-up priority order, exactly once.+ """+ async with self._lock:+ if self._open:+ raise RuntimeError("cannot return pending inputs while admission is open")+ pending = tuple(deepcopy([*self._steers, *self._follow_ups]))+ self._steers.clear()+ self._follow_ups.clear()+ return pending++ def abort(self, reason: str = "aborted") -> None:+ if self._running:+ self._outcome.primary("aborted")+ self._ctx.cancel.cancel(reason)++ def snapshot(self) -> Snapshot:+ """A committed cut, including only state that can be restored there."""+ seq = self._rows[-1].context_seq if self._rows else 0+ return Snapshot(self.session_id, seq, deepcopy(self._committed_state))++ async def run(self, input: AgentInput, *, turn_id: str) -> AsyncIterator[AgentEvent]:+ async with self._lock:+ if self._running:+ 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._running = self._open = True+ self._consumer_closed = False+ self._ctx = RunContext(self.session_id, turn_id, CancelToken())+ self._scope = RunScope(self._ctx.cancel)+ self._outcome = OutcomeOwner()+ self._seq = 0++ # Bounded delivery applies backpressure to provider streaming. No emit+ # awaits this queue while holding the input-admission lock.+ events: asyncio.Queue[AgentEvent] = asyncio.Queue(maxsize=64)++ async def emit(event_type: Any, **fields: Any) -> None:+ if self._consumer_closed:+ return+ event = event_type(turn_id=turn_id, seq=self._seq, **fields)+ self._seq += 1+ await events.put(event)++ worker = asyncio.create_task(self._drive(deepcopy(input), emit))+ receive: Optional[asyncio.Task] = None+ try:+ while True:+ if worker.done() and events.empty():+ await worker+ break+ receive = asyncio.create_task(events.get())+ ready, _ = await asyncio.wait({worker, receive}, return_when=asyncio.FIRST_COMPLETED)+ if receive in ready:+ yield receive.result()+ receive = None+ elif worker.done() and events.empty():+ receive.cancel()+ with suppress(asyncio.CancelledError):+ await receive+ receive = None+ await worker+ break+ else:+ yield await receive+ receive = None+ finally:+ if receive is not None:+ receive.cancel()+ with suppress(asyncio.CancelledError):+ await receive+ if not worker.done():+ self._consumer_closed = True+ self.abort("event consumer closed")+ worker.cancel()+ try:+ with suppress(asyncio.CancelledError):+ await worker+ finally:+ async with self._lock:+ self._running = self._open = False+ self._run_tools = None++ async def _save_state(self, *, cleanup: bool = False) -> None:+ representation = state_representation(self._ctx.state)+ if representation == self._committed_state_json:+ return+ state = deepcopy(self._ctx.state)++ async def persist() -> ContextEntry:+ return await self.store.append_payload(self.session_id, "agent_state", {"version": 1, "state": state})++ row = await persist() if cleanup else await self._scope.call(persist, interruptible=False)+ self._rows.append(row)+ self._committed_state = deepcopy(state)+ self._committed_state_json = representation++ async def _hook(self, factory: Callable[[], Awaitable[T]], *, cleanup: bool = False) -> T:+ result = await factory() if cleanup else await self._scope.call(factory)+ state_representation(self._ctx.state)+ # End is a directive; its owning stage selects the outcome only after+ # the required state and step commits have succeeded.+ return result++ async def _consume(self, input: AgentInput) -> None:+ validate_message_append(self._rows, session_id=self.session_id, kind="input", message=input.message)+ await self._save_state()+ row = await self._scope.call(+ lambda: self.store.consume_input(self.session_id, input.message_id, deepcopy(input.message)),+ interruptible=False,+ )+ self._rows.append(row)++ def _validate_response(self, message: AssistantMessage) -> None:+ try:+ validate_message_append(self._rows, session_id=self.session_id, kind="response", message=message)+ except ProjectionError as error:+ raise ProviderProtocolViolation(f"Provider protocol violation: {error}") from error++ async def _response(self, message: AssistantMessage, *, final: bool) -> ContextEntry:+ self._validate_response(message)+ await self._save_state()+ row = await self._scope.call(+ lambda: self.store.append_response(self.session_id, deepcopy(message), final=final),+ interruptible=False,+ )+ self._rows.append(row)+ return row++ async def _drive(self, input: AgentInput, emit: Callable[..., Awaitable[None]]) -> None:+ loaded = False+ try:+ try:+ await emit(RunStarted)+ # Preflight before hooks or input consumption. Reuse the selection+ # for the first request; later attempts resolve the route afresh.+ selected = await self._scope.call(self.models.resolve)+ self._check_model_route(selected)+ self._rows = list(await self._scope.call(lambda: self.store.load(self.session_id)))+ projection = project(self._rows)+ self._ctx.state = deepcopy(dict(projection.state))+ self._committed_state_json = state_representation(self._ctx.state)+ self._committed_state = deepcopy(self._ctx.state)+ loaded = True+ system = self.system+ self._run_tools = dict(self._tools)+ for hook in self.hooks:+ setup = await self._hook(lambda: hook.before_run(deepcopy(input), self._ctx))+ if setup is not None:+ if setup.system is not None:+ system = setup.system+ if setup.tools is not None:+ names = [tool.spec.name for tool in setup.tools]+ if len(names) != len(set(names)):+ raise ValueError("tool names must be unique")+ self._run_tools = dict(zip(names, setup.tools))+ await self._consume(input)+ self._outcome.primary(await self._loop(system, emit, selected))+ except _Ended:+ self._outcome.primary("ended_by_hook")+ except _Aborted:+ self._outcome.primary("aborted")+ except asyncio.CancelledError:+ self._outcome.primary("aborted")+ self._ctx.cancel.cancel("event consumer closed" if self._consumer_closed else "dependency cancelled")+ if not self._consumer_closed:+ await emit(AgentError, kind="dependency_cancelled", message="An agent dependency was cancelled.")+ except Exception as error:+ self._outcome.primary("error")+ if isinstance(error, HookStateError):+ self._ctx.state = deepcopy(self._committed_state)+ await emit(AgentError, kind=type(error).__name__, message=str(error))+ finally:+ # If an external cancellation interrupted an exception handler,+ # admission still records its first cause before cleanup starts.+ self._outcome.primary("aborted" if self._ctx.cancel.cancelled else "error")+ self._scope.stop()+ # Cleanup is a separate joined task, outside cancelled admission.+ # Consumer closure cannot interrupt commit/job ownership release.+ cleanup = asyncio.create_task(self._finish(loaded, emit))+ try:+ await asyncio.shield(cleanup)+ except asyncio.CancelledError:+ await cleanup+ if self._consumer_closed:+ raise asyncio.CancelledError()+ await emit(RunEnded, reason=self._outcome.reason)++ async def _flush_diagnostics(self, emit: Callable[..., Awaitable[None]]) -> None:+ while self._outcome.diagnostics:+ kind, message = self._outcome.diagnostics[0]+ await emit(AgentError, kind=kind, message=message)+ self._outcome.diagnostics.popleft()++ async def _cleanup(self, factory: Callable[[], Awaitable[Any]], *, stream: bool = False) -> None:+ try:+ await factory()+ except (Exception, asyncio.CancelledError) as error:+ if isinstance(error, HookStateError):+ self._ctx.state = deepcopy(self._committed_state)+ kind = (+ "stream_cleanup"+ if stream+ else ("dependency_cancelled" if isinstance(error, asyncio.CancelledError) else type(error).__name__)+ )+ self._outcome.diagnostic(kind, f"Cleanup failed: {type(error).__name__}: {error}")++ async def _finish(self, loaded: bool, emit: Callable[..., Awaitable[None]]) -> None:+ async with self._lock:+ self._open = False+ await self._scope.close()+ await self._flush_diagnostics(emit)+ try:+ if loaded:+ await self._cleanup(lambda: self._save_state(cleanup=True))+ outcome = RunOutcome(self._ctx.turn_id, self._outcome.reason, self.snapshot())+ for hook in self.hooks:+ await self._cleanup(lambda: self._hook(lambda: hook.after_run(outcome, self._ctx), cleanup=True))+ await self._cleanup(lambda: self._save_state(cleanup=True))+ finally:+ # Sweep on every terminal path, including failed tool cleanup and+ # cleanup hooks. Handed-over handles are no longer foreground.+ try:+ await self.jobs.kill_foreground(self.session_id)+ except Exception as error:+ self._outcome.foreground_leaked()+ if self._consumer_closed:+ raise+ self._outcome.diagnostic(type(error).__name__, str(error))+ await self._flush_diagnostics(emit)++ @staticmethod+ def _check_model_route(selected: ModelSelection) -> None:+ if selected.capabilities.supports_tools is False:+ raise UnsupportedModelRoute("The selected model does not support tools; the agent requires tool support.")++ async def _request(self, system: str, selected: ModelSelection) -> tuple[ModelRequest, dict[str, Tool]]:+ self._check_model_route(selected)+ capabilities = selected.capabilities+ tools = dict(self._run_tools if self._run_tools is not None else self._tools)+ context = project(+ self._rows,+ system=system,+ rehydrated=self.rehydrate(deepcopy(self._ctx.state)) if self.rehydrate else (),+ )+ request = ModelRequest(+ endpoint=deepcopy(selected.endpoint),+ system=context.system,+ messages=context.messages,+ tools=tuple(deepcopy(tool.spec) for tool in tools.values()),+ max_tokens=min(self.max_tokens, selected.max_output_tokens),+ reasoning_effort=(+ self.reasoning_effort+ if capabilities.supports_reasoning is True and self.reasoning_effort in capabilities.reasoning_efforts+ else None+ ),+ supports_images=capabilities.supports_images is True,+ )+ for hook in self.hooks:+ decision = await self._hook(lambda: hook.before_model(request, self._ctx))+ if isinstance(decision, End):+ await self._save_state()+ raise _Ended()+ if decision is not None:+ request = decision+ allowed = {spec.name for spec in request.tools}+ return request, {name: tool for name, tool in tools.items() if name in allowed}++ @asynccontextmanager+ async def _model(+ self, system: str, emit: Callable[..., Awaitable[None]], selected: Optional[ModelSelection] = None+ ) -> AsyncIterator[tuple[Done | ProviderError, dict[str, Tool]]]:+ retries = 0+ started = time.monotonic()+ retry_error: Optional[ProviderError] = None+ while True:+ self._scope.check()+ if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:+ yield retry_error, {}+ return+ if selected is None:+ selected = await self._scope.call(self.models.resolve)+ # Resolution is the last async stage before request admission.+ # Expiry wins before route validation, projection, rehydration or+ # hooks can replace the original error or persist new side effects.+ if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:+ yield retry_error, {}+ return+ request, tools = await self._request(system, selected)+ selected = None+ if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:+ yield retry_error, tools+ return+ self._scope.check()+ stream = self.models.provider_for(request.endpoint.protocol).stream(request, self._ctx.cancel)+ streamed = False+ terminal = None+ try:+ while True:+ try:+ event = await self._scope.call(lambda: anext(stream))+ except StopAsyncIteration:+ break+ if isinstance(event, (Done, ProviderError)):+ terminal = event+ break+ streamed = True+ if isinstance(event, TextDelta):+ await emit(AssistantTextDelta, delta=event.delta)+ elif isinstance(event, ThinkingDelta):+ await emit(AssistantThinkingDelta, delta=event.delta)+ if terminal is None:+ terminal = ProviderError("unknown", "Provider stream ended without a terminal event.", False)+ delay = (+ self.retry.delay(terminal, retries=retries, streamed=streamed, elapsed_s=time.monotonic() - started)+ if isinstance(terminal, ProviderError)+ else None+ )+ if delay is None:+ # The caller admits and commits this terminal inside the+ # scope, BEFORE aclose. Never retry an accepted terminal.+ yield terminal, tools+ return+ finally:+ close = getattr(stream, "aclose", None)+ if close is not None:+ await self._cleanup(close, stream=True)+ retry_error = terminal+ retries += 1+ await self._scope.call(lambda: asyncio.sleep(delay))++ async def _commit_model_message(self, message: AssistantMessage, emit: Callable[..., Awaitable[None]]) -> bool:+ """Finality and queued-input admission share one lock with the commit."""+ pending: list[tuple[AgentInput, bool]] = []+ consumed: list[tuple[AgentInput, bool]] = []+ failed = message.stop_reason in {"error", "aborted"}+ row = None+ try:+ async with self._lock:+ if not message.tool_calls and not failed:+ pending = [(item, True) for item in self._steers]+ if not pending:+ pending = [(item, False) for item in self._follow_ups]+ final = not message.tool_calls and not pending and not failed+ if final or failed:+ self._open = False+ row = await self._response(message, final=final)+ for item, is_steer in pending:+ await self._consume(item)+ (self._steers if is_steer else self._follow_ups).popleft()+ consumed.append((item, is_steer))+ finally:+ if row is not None and not self._consumer_closed:+ await emit(MessageCommitted, message_id=row.row_id, context_seq=row.context_seq, final=final)+ for item, is_steer in consumed:+ if is_steer:+ await emit(SteerApplied, message_id=item.message_id)+ return final++ async def _loop(self, system: str, emit: Callable[..., Awaitable[None]], selected: ModelSelection) -> RunEndReason:+ first_selection: Optional[ModelSelection] = selected+ while True:+ async with self._model(system, emit, first_selection) as (terminal, tools):+ first_selection = None+ if isinstance(terminal, ProviderError):+ if terminal.partial is not None:+ self._validate_response(terminal.partial)+ reason = (+ "context_exhausted"+ if terminal.kind == "overflow"+ else "aborted"+ if terminal.kind == "aborted"+ else "error"+ )+ self._outcome.primary(reason)+ await emit(AgentError, kind=terminal.kind, message=terminal.message)+ if terminal.partial is not None:+ row = await self._response(terminal.partial, final=False)+ await emit(MessageCommitted, message_id=row.row_id, context_seq=row.context_seq, final=False)+ return reason+ message = terminal.message+ self._validate_response(message)+ failed = message.stop_reason in {"error", "aborted"}+ if failed:+ self._outcome.primary("aborted" if message.stop_reason == "aborted" else "error")+ await emit(+ AgentError,+ kind=message.stop_reason,+ message=message.error_message or f"Model stopped with {message.stop_reason}.",+ )+ final = await self._commit_model_message(message, emit)+ empty_reply = final and not any(+ isinstance(block, TextBlock) and block.text and block.text.strip() for block in message.content+ )+ if empty_reply:+ self._outcome.primary("error")+ await emit(+ AgentError,+ kind=message.stop_reason if message.stop_reason in {"refusal", "safety"} else "empty_response",+ message=message.error_message or f"Model stopped with {message.stop_reason} without a reply.",+ )+ # aclose failures are diagnostics, never a reason to discard the+ # committed response or skip its tools. Primary errors precede them.+ await self._flush_diagnostics(emit)+ end, skip = False, False+ for hook in self.hooks:+ decision = await self._hook(lambda: hook.after_model(deepcopy(message), self._ctx))+ if isinstance(decision, End):+ end = True+ break+ skip = skip or isinstance(decision, SkipTools)+ if failed:+ return "aborted" if message.stop_reason == "aborted" else "error"+ if not message.tool_calls:+ await self._save_state()+ if empty_reply:+ return "error"+ if end:+ return "ended_by_hook"+ if final:+ return "completed"+ continue++ terminate = False+ for call in message.tool_calls:+ self._scope.check()+ result, step_end = await self._tool(call, tools, skip or end, emit)+ terminate = terminate or result.terminate+ end = end or step_end+ if end:+ return "ended_by_hook"+ if terminate:+ return "completed"+ applied = []+ try:+ async with self._lock:+ while self._steers:+ item = self._steers[0]+ await self._consume(item)+ self._steers.popleft()+ applied.append(item)+ finally:+ if not self._consumer_closed:+ for item in applied:+ await emit(SteerApplied, message_id=item.message_id)++ async def _tool(+ self,+ original: ToolCallBlock,+ tools: Mapping[str, Tool],+ skip: bool,+ emit: Callable[..., Awaitable[None]],+ ) -> tuple[ToolResult, bool]:+ call = deepcopy(original)+ end = False+ result = None+ if skip:+ result = ToolResult((text("[skipped by policy]"),), is_error=True)+ else:+ for hook in self.hooks:+ decision = await self._hook(lambda: hook.before_tool(call, self._ctx))+ if isinstance(decision, Deny):+ result = ToolResult((text(decision.reason),), is_error=True)+ break+ if isinstance(decision, End):+ result = ToolResult((text("[skipped by policy]"),), is_error=True)+ end = True+ break+ if isinstance(decision, AlterArgs):+ call = replace(call, arguments=deepcopy(decision.arguments))+ await emit(+ ToolStarted,+ tool_call_id=call.id,+ name=call.name,+ preview=json.dumps(call.arguments, ensure_ascii=False)[:500],+ )+ if result is None:+ tool = tools.get(call.name)+ if tool is None:+ result = ToolResult((text(f"Tool {call.name} is not available."),), is_error=True)+ else:+ result = await self._execute(tool, call, emit)+ if not end and not skip:+ for hook in self.hooks:+ decision = await self._hook(lambda: hook.after_tool(call, result, self._ctx))+ if isinstance(decision, End):+ end = True+ break+ if isinstance(decision, AlterResult):+ result = decision.result+ message = ToolResultMessage(call.id, call.name, result.content, result.is_error)+ validate_message_append(self._rows, session_id=self.session_id, kind="tool_result", message=message)+ await self._save_state()+ row = await self._scope.call(+ lambda: self.store.append_tool_result(self.session_id, deepcopy(message), details=deepcopy(result.details)),+ interruptible=False,+ )+ self._rows.append(row)+ await emit(+ ToolFinished,+ tool_call_id=call.id,+ event_id=row.row_id,+ is_error=result.is_error,+ watch_id=result.details.get("watch_id"),+ )+ return result, end++ async def _execute(self, tool: Tool, call: ToolCallBlock, emit: Callable[..., Awaitable[None]]) -> ToolResult:+ # Progress is a latest-tail value, not an unbounded buffer of tool output.+ updates: asyncio.Queue[str] = asyncio.Queue(maxsize=1)++ def progress(tail: str) -> None:+ if updates.full():+ updates.get_nowait()+ updates.put_nowait(tail)++ ctx = ToolContext(+ self.session_id,+ call.id,+ self.cwd,+ dict(self.env),+ self._ctx.cancel,+ on_progress=progress,+ )+ execution = asyncio.create_task(self._scope.call(lambda: tool.execute(call.arguments, ctx)))+ update = None+ try:+ while not execution.done() or not updates.empty():+ update = asyncio.create_task(updates.get())+ ready, _ = await asyncio.wait({execution, update}, return_when=asyncio.FIRST_COMPLETED)+ if update in ready:+ await emit(ToolProgress, tool_call_id=call.id, tail=update.result())+ update = None+ elif execution.done():+ break+ return await execution+ except (_Aborted, asyncio.CancelledError):+ raise+ except Exception as error:+ # Tools are an explicit failure boundary; preserve the error as a+ # model-visible result so the next call can correct its arguments.+ logger.exception("Tool execution failed: %s", call.name)+ message = str(error) or f"{type(error).__name__}: tool execution failed."+ return ToolResult((text(message[:500]),), is_error=True)+ finally:+ for task in (update, execution):+ if task is not None and not task.done():+ task.cancel()+ await asyncio.gather(*(task for task in (update, execution) if task is not None), return_exceptions=True)+ # Release failure is supplementary to a tool's cancellation or+ # result. The final sweep alone arbitrates a still-leaked process.+ await self._cleanup(lambda: self.jobs.kill_foreground(self.session_id, tool_call_id=call.id))diff --git a/core/agent_core/agent/models.py b/core/agent_core/agent/models.pynew file mode 100644index 000000000..c8f13d558--- /dev/null+++ b/core/agent_core/agent/models.py@@ -0,0 +1,79 @@+"""Model selection and retry policy owned by the loop, not a provider."""++from __future__ import annotations++from dataclasses import dataclass+from math import isfinite+from typing import Optional, Protocol++from core.agent_core.ai.provider import (+ RETRYABLE_ERROR_KINDS,+ ModelCapabilities,+ ModelEndpoint,+ ProviderAdapter,+ ProviderError,+)+from core.agent_core.messages import ProtocolName++DEFAULT_CONTEXT_WINDOW = 128_000+DEFAULT_MAX_OUTPUT_TOKENS = 8_192+++@dataclass(frozen=True)+class ModelSelection:+ endpoint: ModelEndpoint+ capabilities: ModelCapabilities++ @property+ def context_window(self) -> int:+ """Effective C-9 budget; preserve nullable source capabilities."""+ value = self.capabilities.context_window+ return DEFAULT_CONTEXT_WINDOW if value is None else value++ @property+ def max_output_tokens(self) -> int:+ value = self.capabilities.max_output_tokens+ return DEFAULT_MAX_OUTPUT_TOKENS if value is None else value+++class ModelRouter(Protocol):+ async def resolve(self) -> ModelSelection:+ """Resolve the next call, including a fresh resolution after a retry."""+ ...++ def provider_for(self, protocol: ProtocolName) -> ProviderAdapter:+ """Select transport after before_model has had a chance to change it."""+ ...+++@dataclass(frozen=True)+class RetryPolicy:+ """C-2: at most three extra attempts within 120 s; Retry-After is a floor."""++ max_retries: int = 2+ initial_delay_s: float = 0.5+ max_delay_s: float = 8.0+ max_elapsed_s: float = 120.0++ def __post_init__(self) -> None:+ if type(self.max_retries) is not int or not 0 <= self.max_retries <= 3:+ raise ValueError("max_retries must be an integer between 0 and 3")+ if any(+ not isfinite(value) or value < 0 for value in (self.initial_delay_s, self.max_delay_s, self.max_elapsed_s)+ ):+ raise ValueError("retry delays and budget must be finite and nonnegative")+ if self.max_elapsed_s > 120:+ raise ValueError("max_elapsed_s cannot exceed 120 seconds")++ def delay(self, error: ProviderError, *, retries: int, streamed: bool, elapsed_s: float = 0) -> Optional[float]:+ if (+ retries >= self.max_retries+ or streamed+ or error.partial is not None+ or not error.retryable+ or error.kind not in RETRYABLE_ERROR_KINDS+ ):+ return None+ backoff = min(self.max_delay_s, self.initial_delay_s * 2**retries)+ delay = max(backoff, error.retry_after_s or 0.0)+ return delay if elapsed_s + delay < self.max_elapsed_s else Nonediff --git a/core/agent_core/agent/outcome.py b/core/agent_core/agent/outcome.pynew file mode 100644index 000000000..22e88d5a7--- /dev/null+++ b/core/agent_core/agent/outcome.py@@ -0,0 +1,30 @@+"""One owner for the first primary run cause and supplementary diagnostics."""++from collections import deque+from typing import Optional++from core.agent_core.agent.events import RunEndReason+++class OutcomeOwner:+ def __init__(self) -> None:+ self._reason: Optional[RunEndReason] = None+ self.diagnostics: deque[tuple[str, str]] = deque()++ def primary(self, reason: RunEndReason) -> None:+ if self._reason is None:+ self._reason = reason++ @property+ def reason(self) -> RunEndReason:+ if self._reason is None:+ raise RuntimeError("the run has no primary outcome")+ return self._reason++ def foreground_leaked(self) -> None:+ # The sole cleanup exception to first-cause ownership.+ if self._reason == "completed":+ self._reason = "error"++ def diagnostic(self, kind: str, message: str) -> None:+ self.diagnostics.append((kind, message))diff --git a/core/agent_core/agent/recovery.py b/core/agent_core/agent/recovery.pynew file mode 100644index 000000000..6e2eb21de--- /dev/null+++ b/core/agent_core/agent/recovery.py@@ -0,0 +1,71 @@+"""Durable tool-call settlement before resume (C-5/C-7 recovery.md).++The adapter calls this under its Session writer lock, before Agent.run or any+projection. A restarted call loads committed results again and skips them; each+remaining result is appended immediately. It never executes a tool/command.+"""++from __future__ import annotations++from copy import deepcopy+from typing import Callable, Mapping, Optional++from core.agent_core.harness.projection import interrupted_result, open_tool_calls, validate_message_append+from core.agent_core.harness.store import ContextEntry, TranscriptStore+from core.agent_core.messages import ToolCallBlock, ToolResultMessage, text+from core.agent_core.tools.base import JobHost, JobStatus, ToolResult++RecoveryRenderer = Callable[[ToolCallBlock, str, JobStatus, Optional[str]], ToolResult]++# recovery.md T2: no job evidence can establish whether a file mutation ran.+UNRECORDED_EFFECT = "[tool call interrupted; it may or may not have completed; re-read the file before continuing]"+++async def settle_open_calls(+ *,+ session_id: str,+ store: TranscriptStore,+ jobs: JobHost,+ job_ids: Mapping[tuple[str, str], str],+ render_result: RecoveryRenderer,+) -> tuple[ContextEntry, ...]:+ """Commit one result per open call, using original-owner job lookup.++ ``job_ids`` is keyed by (response's session_id, tool_call_id), so a fork can+ find an inherited call's job. The adapter supplies bash's output-governance+ renderer; it receives (call, job_id, status, watch_id). ``JobHost.hand_over``+ must reuse a job's existing Watch when recovery retries after an interrupted+ commit. The job host owns the launch-handshake reconciliation behind status.++ Store writes remain under the caller's single-writer ownership. A concurrent+ second recovery or Agent.run for that Session is not permitted.+ Without job state, the result explicitly leaves the effect uncertain.+ The adapter settles the interrupted Turn after this step; no tool or model+ is invoked and only a new user input starts another Turn (T4).+ """+ committed: list[ContextEntry] = []+ rows = list(await store.load(session_id))+ for owner, call in open_tool_calls(rows):+ job_id = job_ids.get((owner.session_id, call.id))+ message = interrupted_result(call)+ details = {}+ if job_id is None:+ message = ToolResultMessage(call.id, call.name, (text(UNRECORDED_EFFECT),), is_error=True)+ else:+ status = jobs.status(job_id)+ details["job_id"] = job_id+ if status.state in {"running", "exited"}:+ watch_id = await jobs.hand_over(job_id) if status.state == "running" else None+ result = render_result(deepcopy(call), job_id, status, watch_id)+ message = ToolResultMessage(call.id, call.name, result.content, result.is_error)+ details.update(deepcopy(dict(result.details)))+ details["job_id"] = job_id+ if watch_id is not None:+ details["watch_id"] = watch_id+ if status.state == "exited":+ details["exit_code"] = status.exit_code+ validate_message_append(rows, session_id=session_id, kind="tool_result", message=message)+ row = await store.append_tool_result(session_id, deepcopy(message), details=details)+ rows.append(row)+ committed.append(row)+ return tuple(committed)diff --git a/core/agent_core/agent/state.py b/core/agent_core/agent/state.pynew file mode 100644index 000000000..e46bd9ea7--- /dev/null+++ b/core/agent_core/agent/state.py@@ -0,0 +1,46 @@+"""Hook-state JSON identity, without Python-to-JSON coercion."""++from __future__ import annotations++import json+import math+from typing import Any+++class HookStateError(ValueError):+ """A hook supplied a value outside the exact JSON state contract."""+++def state_representation(state: Any) -> str:+ """Validate before comparison; bool, int and float remain distinct."""+ active: set[int] = set()++ def validate(value: Any) -> None:+ kind = type(value)+ if kind in (str, int, bool, type(None)):+ return+ if kind is float:+ if not math.isfinite(value):+ raise HookStateError("Hook state numbers must be finite.")+ return+ if kind not in (dict, list):+ raise HookStateError(f"Hook state requires exact JSON types, not {kind.__name__}.")+ if id(value) in active:+ raise HookStateError("Hook state must not contain cycles.")+ active.add(id(value))+ try:+ if kind is dict:+ for key, item in value.items():+ if type(key) is not str:+ raise HookStateError("Hook state object keys must be strings.")+ validate(item)+ else:+ for item in value:+ validate(item)+ finally:+ active.remove(id(value))++ if type(state) is not dict:+ raise HookStateError("Hook state must be a JSON object.")+ validate(state)+ return json.dumps(state, allow_nan=False, sort_keys=True, separators=(",", ":"))diff --git a/core/agent_core/harness/projection.py b/core/agent_core/harness/projection.pynew file mode 100644index 000000000..dc769dbef--- /dev/null+++ b/core/agent_core/harness/projection.py@@ -0,0 +1,165 @@+"""C-5 projection before P3 context management.++The store supplies rows including fork ancestry. Projection sorts and copies+them, restores hook state, and repairs orphan calls without executing tools or+writing rows. System text and rehydrated messages are supplied by the caller.+No job host or external settler is consulted. Resume settlement is the separate+write step in ``agent.recovery``; any remaining orphan gets deterministic text.+"""++from __future__ import annotations++from copy import deepcopy+from dataclasses import dataclass, field+from typing import Any, Literal, Mapping, Optional, Sequence++from core.agent_core.harness.store import ContextEntry+from core.agent_core.messages import (+ AssistantMessage,+ Message,+ TextBlock,+ ToolCallBlock,+ ToolResultMessage,+ require_json_value,+ text,+)++# C-1 cross-provider.md; also Pi (MIT), packages/ai/src/utils/transform-messages.ts.+INTERRUPTED = "[tool call interrupted; no result recorded]"+++class ProjectionError(ValueError):+ """The rows cannot be represented by this projection version."""+++@dataclass(frozen=True)+class Projection:+ system: str+ messages: tuple[Message, ...]+ context_seq: int+ state: Mapping[str, Any] = field(default_factory=dict)+++def interrupted_result(call: ToolCallBlock) -> ToolResultMessage:+ return ToolResultMessage(call.id, call.name, (text(INTERRUPTED),), is_error=True)+++def _ordered(entries: Sequence[ContextEntry], fork_point: Optional[int] = None) -> list[ContextEntry]:+ rows = sorted(+ (entry for entry in entries if fork_point is None or entry.context_seq <= fork_point),+ key=lambda entry: entry.context_seq,+ )+ previous_seq = -1+ for row in rows:+ if row.context_seq <= previous_seq:+ raise ProjectionError(f"duplicate context_seq: {row.context_seq}")+ previous_seq = row.context_seq+ if row.kind in {"compaction", "context_edit"}:+ raise ProjectionError(f"{row.kind} requires P3 context management (row {row.row_id})")+ if row.kind == "agent_state":+ if row.payload.get("version") != 1 or not isinstance(row.payload.get("state"), dict):+ raise ProjectionError(f"unsupported agent_state payload (row {row.row_id})")+ elif row.message is None:+ raise ProjectionError(f"{row.kind} has no message (row {row.row_id})")+ if row.message is not None and any(+ isinstance(block, TextBlock) and block.ref is not None for block in row.message.content+ ):+ raise ProjectionError(f"large-content references are not supported (row {row.row_id})")+ if isinstance(row.message, AssistantMessage):+ for call in row.message.tool_calls:+ try:+ # Arguments remain mutable on a frozen block. Reuse the+ # foundation's value invariant at admission and load time.+ require_json_value(call.arguments, "arguments")+ except (ValueError, RecursionError) as error:+ raise ProjectionError(+ f"invalid arguments for tool call {call.id} (row {row.row_id}): {error}"+ ) from error+ return rows+++def _index_results(+ rows: Sequence[ContextEntry],+) -> tuple[dict[tuple[int, str], ToolResultMessage], dict[str, tuple[ContextEntry, ToolCallBlock]]]:+ """Associate late recovery rows with their original response, in row order."""+ pending: dict[str, tuple[ContextEntry, ToolCallBlock]] = {}+ results: dict[tuple[int, str], ToolResultMessage] = {}+ seen: set[str] = set()++ for row in rows:+ if row.kind == "agent_state":+ continue+ message = row.message+ if isinstance(message, ToolResultMessage):+ owner = pending.pop(message.tool_call_id, None)+ if owner is None:+ if message.tool_call_id in seen:+ raise ProjectionError(f"duplicate tool result: {message.tool_call_id}")+ raise ProjectionError(f"tool result has no preceding call: {message.tool_call_id}")+ response, call = owner+ if message.tool_name != call.name:+ raise ProjectionError(f"result identity does not match call {call.id}")+ results[response.context_seq, call.id] = message+ elif isinstance(message, AssistantMessage):+ for call in message.tool_calls:+ if call.id in pending:+ raise ProjectionError(f"duplicate open tool call id: {call.id}")+ seen.add(call.id)+ pending[call.id] = (row, call)+ return results, pending+++def open_tool_calls(entries: Sequence[ContextEntry]) -> tuple[tuple[ContextEntry, ToolCallBlock], ...]:+ """Return uncommitted outcomes in call order for the resume writer."""+ _, pending = _index_results(_ordered(entries))+ return tuple(deepcopy(list(pending.values())))+++def project(+ entries: Sequence[ContextEntry],+ *,+ system: str = "",+ rehydrated: Sequence[Message] = (),+ fork_point: Optional[int] = None,+) -> Projection:+ """Project committed ancestry, with an optional inclusive fork cut.++ Results (including late recovery rows) are placed immediately after their+ response in call order. A missing result always gets INTERRUPTED. Neither+ projection nor the returned detached objects can change persisted rows.+ """+ rows = _ordered(entries, fork_point)+ results, _ = _index_results(rows)+ messages: list[Message] = list(rehydrated)+ state: Mapping[str, Any] = {}+ for row in rows:+ if row.kind == "agent_state":+ state = row.payload["state"]+ continue+ message = row.message+ if isinstance(message, ToolResultMessage):+ continue+ if message is not None:+ messages.append(message)+ if isinstance(message, AssistantMessage):+ for call in message.tool_calls:+ messages.append(results.get((row.context_seq, call.id), interrupted_result(call)))+ return Projection(system, tuple(deepcopy(messages)), rows[-1].context_seq if rows else 0, deepcopy(state))+++def validate_message_append(+ entries: Sequence[ContextEntry],+ *,+ session_id: str,+ kind: Literal["input", "response", "tool_result"],+ message: Message,+) -> None:+ """Reject a candidate before persistence using the actual projection rules.++ Every message-bearing writer uses this boundary, including resume+ settlement. The caller owns serialization with other writers; neither+ the candidate nor the supplied entries are mutated or committed here.+ """+ seq = max((entry.context_seq for entry in entries), default=0) + 1+ candidate = ContextEntry(session_id, seq, kind, f"uncommitted-{kind}", message)+ project([*entries, candidate])diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.pynew file mode 100644index 000000000..c25e7e708--- /dev/null+++ b/tests/agent_core/agent/test_loop.py@@ -0,0 +1,1220 @@+"""C1-C6/C9 through the recording provider, not private loop state.++Foundation coverage only round-trips messages. These tests protect execution+boundaries absent there: per-request tools, durable-vs-transient context, hook+policy, queue finality, fork/resume state, cancellation, and commit/event order.+Gates use Events instead of timing assumptions.+"""++from __future__ import annotations++import asyncio+from dataclasses import replace++import pytest++from core.agent_core.agent.events import (+ AgentError,+ AssistantTextDelta,+ AssistantThinkingDelta,+ MessageCommitted,+ RunEnded,+ RunStarted,+ SteerApplied,+ ToolFinished,+ ToolProgress,+ ToolStarted,+)+from core.agent_core.agent.hooks import (+ AlterArgs,+ AlterResult,+ Deny,+ End,+ Hooks,+ RunSetup,+ SkipTools,+)+from core.agent_core.agent.loop import Agent+from core.agent_core.agent.models import RetryPolicy+from core.agent_core.ai.provider import Done, ModelCapabilities, ProviderError, TextDelta, ThinkingDelta, ToolCallStart+from core.agent_core.agent.models import ModelSelection+from core.agent_core.harness.projection import project+from core.agent_core.messages import ThinkingBlock, ToolCallBlock, ToolResultMessage, UserMessage, text+from core.agent_core.tools.base import ToolResult+from tests.agent_core.fakes import (+ FakeJobHost,+ FakeModelRouter,+ FakeTool,+ InMemoryTranscriptStore,+ ScriptedProvider,+ ENDPOINT,+ assistant,+ input_row,+ user,+)+++def make_agent(provider, *, store=None, session_id="session", tools=(), hooks=(), jobs=None, **options):+ return Agent(+ session_id=session_id,+ models=FakeModelRouter(provider),+ tools=tools,+ hooks=hooks,+ store=store or InMemoryTranscriptStore(),+ jobs=jobs or FakeJobHost(),+ cwd="/test-owned",+ **options,+ )+++async def collect(agent, row_id="input", value="hello", turn_id="turn"):+ return [event async for event in agent.run(input_row(row_id, value), turn_id=turn_id)]+++def user_texts(request):+ return [message.content[0].text for message in request.messages if isinstance(message, UserMessage)]+++async def test_C1_tool_set_is_captured_per_request_and_unavailable_calls_are_errors():+ old, new = FakeTool("old"), FakeTool("new")+ entered, release = asyncio.Event(), asyncio.Event()++ async def first(request, cancel):+ entered.set()+ await release.wait()+ yield Done(assistant(calls=[ToolCallBlock("a", "old"), ToolCallBlock("b", "new")]))++ provider = ScriptedProvider(+ [+ first,+ [Done(assistant(calls=[ToolCallBlock("c", "new"), ToolCallBlock("d", "old")]))],+ [Done(assistant())],+ ]+ )+ agent = make_agent(provider, tools=[old])+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ agent.set_tools([new])+ release.set()+ await run+ assert [[spec.name for spec in request.tools] for request in provider.requests] == [["old"], ["new"], ["new"]]+ assert [ctx.tool_call_id for _, ctx in old.calls] == ["a"]+ assert [ctx.tool_call_id for _, ctx in new.calls] == ["c"]+ results = [row.message for row in await agent.store.load("session") if row.kind == "tool_result"]+ assert [result.tool_call_id for result in results] == ["a", "b", "c", "d"]+ assert [(result.is_error, result.content[0].text) for result in (results[1], results[3])] == [+ (True, "Tool new is not available."),+ (True, "Tool old is not available."),+ ]+++async def test_C2_rewrites_compose_on_detached_requests_and_select_rewritten_transport():+ class Rewrite(Hooks):+ async def before_run(self, input, ctx):+ return RunSetup(system="base")++ async def before_model(self, request, ctx):+ # Nested ToolCallBlock.arguments is mutable despite frozen dataclasses.+ for message in request.messages:+ for call in getattr(message, "tool_calls", ()):+ call.arguments["secret"] = "request only"+ return replace(+ request,+ system=request.system + "/one",+ messages=request.messages + (user("transient"),),+ tools=(),+ endpoint=replace(request.endpoint, protocol="google"),+ max_tokens=99,+ )++ class Second(Hooks):+ async def before_model(self, request, ctx):+ assert request.system == "base/one"+ return replace(request, system=request.system + "/two")++ store = InMemoryTranscriptStore()+ await store.append_response(+ "session", assistant(calls=[ToolCallBlock("past", "echo", {"secret": "stored"})]), final=False+ )+ await store.append_tool_result("session", ToolResultMessage("past", "echo", (text("old result"),)), details={})+ provider = ScriptedProvider([[Done(assistant())]])+ agent = make_agent(provider, store=store, hooks=[Rewrite(), Second()], tools=[FakeTool()])+ await collect(agent)+ request = provider.requests[0]+ assert (request.system, request.max_tokens, request.tools) == ("base/one/two", 99, ())+ assert user_texts(request) == ["hello", "transient"]+ assert agent.models.protocols == ["google"]+ rows = await store.load("session")+ assert rows[0].message.tool_calls[0].arguments == {"secret": "stored"}+ assert [row.message for row in rows if row.kind == "input"] == [user("hello")]+++async def test_C3_deny_and_argument_result_rewrites_compose_in_registration_order():+ order = []++ class First(Hooks):+ async def before_tool(self, call, ctx):+ order.append(("first", call.id))+ if call.id == "denied":+ return Deny("policy reason")+ return AlterArgs({"value": 2})++ async def after_tool(self, call, result, ctx):+ return AlterResult(replace(result, content=(text(result.content[0].text + "/first"),)))++ class Second(Hooks):+ async def before_tool(self, call, ctx):+ order.append(("second", call.id))+ return AlterArgs({"value": call.arguments["value"] + 3})++ async def after_tool(self, call, result, ctx):+ return AlterResult(replace(result, content=(text(result.content[0].text + "/second"),)))++ tool = FakeTool()+ provider = ScriptedProvider(+ [+ [Done(assistant(calls=[ToolCallBlock("denied", "echo"), ToolCallBlock("allowed", "echo")]))],+ [Done(assistant())],+ ]+ )+ agent = make_agent(provider, tools=[tool], hooks=[First(), Second()])+ await collect(agent)+ assert order == [("first", "denied"), ("first", "allowed"), ("second", "allowed")]+ assert [args for args, _ in tool.calls] == [{"value": 5}]+ results = [m for m in provider.requests[1].messages if isinstance(m, ToolResultMessage)]+ assert [m.content[0].text for m in results] == ["policy reason/first/second", "tool result/first/second"]+ assert results[0].is_error++[email protected]("where", ["before_model", "after_model", "before_tool", "after_tool"])+async def test_C3_end_commits_the_step_settles_unexecuted_calls_and_stops_hook_chain(where):+ hooks_seen = []++ class Stop(Hooks):+ async def before_model(self, request, ctx):+ if where == "before_model":+ ctx.state["stopped"] = True+ return End()++ async def after_model(self, message, ctx):+ if where == "after_model":+ return End()++ async def before_tool(self, call, ctx):+ if where == "before_tool":+ return End()++ async def after_tool(self, call, result, ctx):+ if where == "after_tool":+ return End()++ class Later(Hooks):+ async def before_model(self, request, ctx):+ hooks_seen.append("before_model")++ async def after_model(self, message, ctx):+ hooks_seen.append("after_model")++ async def before_tool(self, call, ctx):+ hooks_seen.append("before_tool")++ async def after_tool(self, call, result, ctx):+ hooks_seen.append("after_tool")++ tool = FakeTool()+ provider = ScriptedProvider([[Done(assistant(calls=[ToolCallBlock("a", "echo"), ToolCallBlock("b", "echo")]))]])+ agent = make_agent(provider, tools=[tool], hooks=[Stop(), Later()])+ events = await collect(agent)+ assert events[-1].reason == "ended_by_hook"+ assert where not in hooks_seen+ assert len(tool.calls) == (1 if where == "after_tool" else 0)+ rows = await agent.store.load("session")+ assert len([row for row in rows if row.kind == "tool_result"]) == (0 if where == "before_model" else 2)+ if where == "before_model":+ assert agent.snapshot().state == {"stopped": True}+++async def test_C3_skip_tools_and_terminate_have_distinct_batch_semantics():+ class Skip(Hooks):+ async def after_model(self, message, ctx):+ return SkipTools()++ tool = FakeTool(result=ToolResult((text("terminate"),), terminate=True))+ response = assistant(calls=[ToolCallBlock("a", "echo"), ToolCallBlock("b", "echo")])+ skipped = ScriptedProvider([[Done(response)], [Done(assistant())]])+ await collect(make_agent(skipped, tools=[tool], hooks=[Skip()]))+ assert tool.calls == []+ assert [m.content[0].text for m in skipped.requests[1].messages if isinstance(m, ToolResultMessage)] == [+ "[skipped by policy]",+ "[skipped by policy]",+ ]+ provider = ScriptedProvider([[Done(response)]])+ agent = make_agent(provider, tools=[tool])+ events = await collect(agent)+ assert len(tool.calls) == 2+ assert events[-1].reason == "completed"+ assert len([row for row in await agent.store.load("session") if row.kind == "tool_result"]) == 2+++async def test_C4_steer_waits_for_the_batch_and_follow_up_waits_for_natural_end():+ entered, release = asyncio.Event(), asyncio.Event()++ async def execute(arguments, ctx):+ if ctx.tool_call_id == "a":+ entered.set()+ await release.wait()+ return ToolResult((text(ctx.tool_call_id),))++ provider = ScriptedProvider(+ [+ [Done(assistant(calls=[ToolCallBlock("a", "echo"), ToolCallBlock("b", "echo")]))],+ [Done(assistant("intermediate"))],+ [Done(assistant("final"))],+ ]+ )+ agent = make_agent(provider, tools=[FakeTool(execute=execute)])+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ assert await agent.steer(input_row("steer", "改变方向"))+ assert await agent.follow_up(input_row("follow", "then follow up"))+ assert [row.kind for row in await agent.store.load("session")] == ["input", "response"]+ release.set()+ events = await run+ assert [user_texts(request) for request in provider.requests] == [+ ["hello"],+ ["hello", "改变方向"],+ ["hello", "改变方向", "then follow up"],+ ]+ rows = await agent.store.load("session")+ assert [row.kind for row in rows] == [+ "input",+ "response",+ "tool_result",+ "tool_result",+ "input",+ "response",+ "input",+ "response",+ ]+ assert [event.message_id for event in events if isinstance(event, SteerApplied)] == ["steer"]+ assert [agent.store.final[row.row_id] for row in rows if row.kind == "response"] == [False, False, True]+++async def test_C4_pending_steer_prevents_finality_and_late_steer_is_refused_during_commit():+ class PausingStore(InMemoryTranscriptStore):+ def __init__(self):+ super().__init__()+ self.final_entered, self.final_release = asyncio.Event(), asyncio.Event()++ async def append_response(self, session_id, message, *, final):+ if final:+ self.final_entered.set()+ await self.final_release.wait()+ return await super().append_response(session_id, message, final=final)++ entered, release = asyncio.Event(), asyncio.Event()++ async def first(request, cancel):+ entered.set()+ await release.wait()+ yield Done(assistant("first"))++ store = PausingStore()+ provider = ScriptedProvider([first, [Done(assistant("last"))]])+ agent = make_agent(provider, store=store)+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ assert await agent.steer(input_row("pending", "one more"))+ release.set()+ await store.final_entered.wait()+ late = asyncio.create_task(agent.steer(input_row("late", "too late")))+ store.final_release.set()+ assert await late is False+ await run+ assert [user_texts(request) for request in provider.requests] == [["hello"], ["hello", "one more"]]+ assert [+ (row.message.content[0].text, store.final[row.row_id])+ for row in await store.load("session")+ if row.kind == "response"+ ] == [("first", False), ("last", True)]+ assert await agent.follow_up(input_row("late-follow", "later")) is False+++async def test_C4_follow_up_stays_pending_while_a_steer_extends_a_tool_free_run():+ entered, release = asyncio.Event(), asyncio.Event()++ async def first(request, cancel):+ entered.set()+ await release.wait()+ yield Done(assistant())++ provider = ScriptedProvider([first, [Done(assistant())], [Done(assistant())]])+ agent = make_agent(provider)+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ assert await agent.follow_up(input_row("follow", "follow"))+ assert await agent.steer(input_row("steer", "steer"))+ release.set()+ await run+ assert [user_texts(request) for request in provider.requests] == [+ ["hello"],+ ["hello", "steer"],+ ["hello", "steer", "follow"],+ ]+++async def test_before_run_setup_applies_to_one_run_and_after_run_state_is_durable():+ outcomes = []++ class Setup(Hooks):+ async def before_run(self, input, ctx):+ if input.message_id == "first":+ return RunSetup(system="first system", tools=(FakeTool("first"),))++ async def after_run(self, outcome, ctx):+ outcomes.append(outcome)+ ctx.state["finished"] = outcome.turn_id++ provider = ScriptedProvider([[Done(assistant())], [Done(assistant())]])+ agent = make_agent(provider, hooks=[Setup()], tools=[FakeTool("base")], system="base system")+ await collect(agent, "first", turn_id="first-turn")+ assert agent.snapshot().state == {"finished": "first-turn"}+ await collect(agent, "second", turn_id="second-turn")+ assert [(r.system, [t.name for t in r.tools]) for r in provider.requests] == [+ ("first system", ["first"]),+ ("base system", ["base"]),+ ]+ assert [outcome.reason for outcome in outcomes] == ["completed", "completed"]+ assert project(await agent.store.load("session")).state == {"finished": "second-turn"}+++async def test_C5_fork_and_C6_resume_restore_persisted_state_without_shared_mutable_context():+ class State(Hooks):+ async def before_run(self, input, ctx):+ ctx.state.setdefault("history", []).append(input.message_id)++ async def before_model(self, request, ctx):+ return replace(request, system="/".join(ctx.state["history"]))++ store = InMemoryTranscriptStore()+ original = make_agent(ScriptedProvider([[Done(assistant("root"))]]), store=store, hooks=[State()])+ await collect(original, "root-input")+ snapshot = original.snapshot()+ for child in ("left", "right"):+ store.fork(snapshot, session_id=child)+ snapshot.state["history"].append("outside mutation")+ # Parent changes after the anchor must not leak into either child.+ await store.consume_input("session", "later-parent", user("parent only"))+ providers = {name: ScriptedProvider([[Done(assistant(name))]]) for name in ("left", "right")}+ await asyncio.gather(+ *(+ collect(make_agent(provider, store=store, session_id=name, hooks=[State()]), name, name)+ for name, provider in providers.items()+ )+ )+ for name, provider in providers.items():+ assert user_texts(provider.requests[0]) == ["hello", name]+ assert provider.requests[0].system == f"root-input/{name}"+ left_rows = await store.load("left")+ assert project(left_rows).state == {"history": ["root-input", "left"]}+ resumed_provider = ScriptedProvider([[Done(assistant("resumed"))]])+ resumed = make_agent(resumed_provider, store=store, session_id="left", hooks=[State()])+ await collect(resumed, "resume", "resume text")+ assert resumed_provider.requests[0].messages[:-1] == project(left_rows).messages+ assert resumed_provider.requests[0].system == "root-input/left/resume"+++async def test_C9_events_reference_committed_rows_and_progress_precedes_tool_finish():+ async def execute(arguments, ctx):+ ctx.on_progress("working")+ return ToolResult((text("ready"),))++ provider = ScriptedProvider(+ [+ [+ ThinkingDelta(0, "think"),+ TextDelta(1, "text"),+ Done(assistant(calls=[ToolCallBlock("a", "echo", {"path": "文件"})])),+ ],+ [Done(assistant())],+ ]+ )+ agent = make_agent(provider, tools=[FakeTool(execute=execute)])+ events = []+ async for event in agent.run(input_row("input", "hello"), turn_id="the-turn-id"):+ rows = await agent.store.load("session")+ if isinstance(event, MessageCommitted):+ assert any(row.row_id == event.message_id and row.context_seq == event.context_seq for row in rows)+ if isinstance(event, ToolFinished):+ assert any(row.row_id == event.event_id for row in rows)+ events.append(event)+ assert [type(event) for event in events] == [+ RunStarted,+ AssistantThinkingDelta,+ AssistantTextDelta,+ MessageCommitted,+ ToolStarted,+ ToolProgress,+ ToolFinished,+ MessageCommitted,+ RunEnded,+ ]+ assert [event.seq for event in events] == list(range(len(events)))+ assert {event.turn_id for event in events} == {"the-turn-id"}+ assert len(next(event for event in events if isinstance(event, ToolStarted)).preview) <= 500++[email protected]("streamed", [False, "text", "tool", "partial"])+async def test_retry_only_before_output_and_re_resolves_the_route(streamed, monkeypatch):+ sleeps = []+ real_sleep = asyncio.sleep++ async def sleep(delay):+ sleeps.append(delay)+ await real_sleep(0)++ monkeypatch.setattr("core.agent_core.agent.loop.asyncio.sleep", sleep)+ error = ProviderError(+ "rate_limit",+ "busy",+ True,+ retry_after_s=3.0,+ partial=assistant("partial", stop_reason="error") if streamed == "partial" else None,+ )+ prefix = (+ [TextDelta(0, "x")] if streamed == "text" else [ToolCallStart(0, "a", "echo")] if streamed == "tool" else []+ )+ provider = ScriptedProvider([prefix + [error], [Done(assistant())]])+ agent = make_agent(provider)+ events = await collect(agent)+ if streamed:+ assert len(provider.requests) == 1+ assert events[-1].reason == "error"+ assert sleeps == []+ else:+ assert len(provider.requests) == agent.models.resolutions == 2+ assert sleeps == [3.0]+ assert events[-1].reason == "completed"+++ "kind,retryable,reason,count",+ [+ ("server", True, "error", 3),+ ("unknown", True, "error", 1),+ ("auth", False, "error", 1),+ ("overflow", False, "context_exhausted", 1),+ ("aborted", False, "aborted", 1),+ ],+)+async def test_retry_budget_and_terminal_error_taxonomy(kind, retryable, reason, count):+ provider = ScriptedProvider([[ProviderError(kind, "clear error", retryable)]] * 4)+ agent = make_agent(provider, retry=RetryPolicy(initial_delay_s=0))+ events = await collect(agent)+ assert len(provider.requests) == count+ assert events[-1].reason == reason+ assert [(event.kind, event.message) for event in events if isinstance(event, AgentError)] == [(kind, "clear error")]+++async def test_abort_closes_provider_stream_and_allows_a_new_turn():+ entered = asyncio.Event()++ async def blocked(request, cancel):+ entered.set()+ await asyncio.Event().wait()+ yield Done(assistant())++ provider = ScriptedProvider([blocked, [Done(assistant("new"))]])+ agent = make_agent(provider)+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ agent.abort("stop")+ events = await asyncio.wait_for(run, 1)+ assert events[-1].reason == "aborted"+ assert provider.closed_streams == 1+ assert [row.kind for row in await agent.store.load("session")] == ["input"]+ next_events = await collect(agent, "next", turn_id="next-turn")+ assert next_events[0].seq == 0+ assert next_events[-1].reason == "completed"+++async def test_abort_kills_foreground_through_JobHost_but_preserves_handed_over_jobs():+ host = FakeJobHost()+ entered = asyncio.Event()+ provider = ScriptedProvider([[Done(assistant(calls=[ToolCallBlock("bg", "bash"), ToolCallBlock("fg", "bash")]))]])+ agent = make_agent(provider, jobs=host)++ async def execute(arguments, ctx):+ job = await agent.jobs.start(+ "test", cwd=ctx.cwd, env=ctx.env, timeout_s=None, session_id=ctx.session_id, tool_call_id=ctx.tool_call_id+ )+ if ctx.tool_call_id == "bg":+ watch = await agent.jobs.hand_over(job)+ return ToolResult((text("watch"),), details={"watch_id": watch, "job_id": job})+ entered.set()+ await agent.jobs.wait(job, deadline_s=None)+ return ToolResult((text("foreground finished"),))++ agent.set_tools([FakeTool("bash", execute=execute)])+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ agent.abort()+ events = await asyncio.wait_for(run, 1)+ assert events[-1].reason == "aborted"+ assert host.killed == ["job_2"]+ assert host.status("job_1").state == "running"+ assert [row.message.tool_call_id for row in await agent.store.load("session") if row.kind == "tool_result"] == [+ "bg"+ ]++[email protected]("transition", ["start", "hand_over"])+async def test_abort_during_job_ownership_transition_waits_then_kills_only_foreground(transition):+ entered, release = asyncio.Event(), asyncio.Event()++ class Host(FakeJobHost):+ async def start(self, *args, **kwargs):+ job = await super().start(*args, **kwargs)+ if transition == "start":+ entered.set()+ await release.wait()+ return job++ async def hand_over(self, job_id):+ watch = await super().hand_over(job_id)+ entered.set()+ await release.wait()+ return watch++ host = Host()+ provider = ScriptedProvider([[Done(assistant(calls=[ToolCallBlock("a", "bash")]))]])+ agent = make_agent(provider, jobs=host)++ async def execute(arguments, ctx):+ job = await agent.jobs.start(+ "test", cwd=ctx.cwd, env=ctx.env, timeout_s=None, session_id=ctx.session_id, tool_call_id=ctx.tool_call_id+ )+ if transition == "hand_over":+ await agent.jobs.hand_over(job)+ await asyncio.Event().wait()++ agent.set_tools([FakeTool("bash", execute=execute)])+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ agent.abort()+ release.set()+ events = await asyncio.wait_for(run, 1)+ assert events[-1].reason == "aborted"+ assert len(host.starts) == 1+ assert host.killed == (["job_1"] if transition == "start" else [])+++async def test_abort_interrupts_retry_backoff_without_an_extra_provider_request(monkeypatch):+ entered = asyncio.Event()++ async def backoff(delay):+ entered.set()+ await asyncio.Event().wait()++ monkeypatch.setattr("core.agent_core.agent.loop.asyncio.sleep", backoff)+ provider = ScriptedProvider([[ProviderError("server", "temporary", True)]])+ agent = make_agent(provider)+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ agent.abort()+ assert (await asyncio.wait_for(run, 1))[-1].reason == "aborted"+ assert len(provider.requests) == 1+++async def test_closing_event_consumer_cancels_work_and_releases_run_ownership():+ provider = ScriptedProvider([[Done(assistant())]])+ agent = make_agent(provider)+ stream = agent.run(input_row("input", "hello"), turn_id="turn")+ assert isinstance(await anext(stream), RunStarted)+ await stream.aclose()+ assert await agent.steer(input_row("late", "no")) is False+++async def test_concurrent_run_is_refused_without_interrupting_the_owner():+ entered, release = asyncio.Event(), asyncio.Event()++ async def blocked(request, cancel):+ entered.set()+ await release.wait()+ yield Done(assistant())++ agent = make_agent(ScriptedProvider([blocked]))+ run = asyncio.create_task(collect(agent))+ await entered.wait()+ with pytest.raises(RuntimeError, match="active run"):+ await collect(agent, "other", turn_id="other")+ release.set()+ assert (await run)[-1].reason == "completed"++[email protected]("capability", [None, False, True])+async def test_resolved_nullable_capabilities_gate_each_request(capability):+ provider = ScriptedProvider([[Done(assistant())]])+ agent = make_agent(provider, tools=[FakeTool()], reasoning_effort="high", max_tokens=2000)+ agent.models = FakeModelRouter(+ provider,+ [+ ModelSelection(+ ENDPOINT,+ ModelCapabilities(+ supports_tools=None,+ supports_images=capability,+ supports_reasoning=capability,+ max_output_tokens=1000 if capability is True else None,+ reasoning_efforts=("low", "high"),+ ),+ )+ ],+ )+ await collect(agent)+ request = provider.requests[0]+ assert request.supports_images is (capability is True)+ assert [spec.name for spec in request.tools] == ["echo"]+ assert request.reasoning_effort == ("high" if capability is True else None)+ assert request.max_tokens == (1000 if capability is True else 2000)++[email protected]("initial", [True, False])+async def test_tool_incapable_route_is_refused_before_execution_or_any_request(initial):+ hooks = []++ class RecordHook(Hooks):+ async def before_run(self, input, ctx):+ hooks.append("before_run")++ provider = ScriptedProvider([[Done(assistant(calls=[ToolCallBlock("a", "echo")]))]])+ tool = FakeTool()+ agent = make_agent(provider, tools=[tool], hooks=[RecordHook()])+ denied = ModelSelection(ENDPOINT, ModelCapabilities(supports_tools=False))+ agent.models = FakeModelRouter(+ provider,+ [denied] if initial else [ModelSelection(ENDPOINT, ModelCapabilities(supports_tools=True)), denied],+ )+ events = await collect(agent)+ assert events[-1].reason == "error"+ assert [(event.kind, event.message) for event in events if isinstance(event, AgentError)] == [+ ("UnsupportedModelRoute", "The selected model does not support tools; the agent requires tool support.")+ ]+ assert len(provider.requests) == (0 if initial else 1)+ if initial:+ assert hooks == tool.calls == []+ assert await agent.store.load("session") == []+ else:+ assert len(tool.calls) == 1+++ "configured,maximum,expected",+ [(None, None, 8192), (20000, None, 8192), (1000, None, 1000), (20000, 16000, 16000)],+)+async def test_output_budget_uses_configured_budget_and_known_or_default_provider_limit(configured, maximum, expected):+ provider = ScriptedProvider([[Done(assistant())]])+ agent = make_agent(provider, **({"max_tokens": configured} if configured is not None else {}))+ agent.models = FakeModelRouter(provider, [ModelSelection(ENDPOINT, ModelCapabilities(max_output_tokens=maximum))])+ await collect(agent)+ assert provider.requests[0].max_tokens == expected++[email protected]("window,expected", [(None, 128000), (32000, 32000)])+def test_router_selection_exposes_effective_context_budget_without_forging_capabilities(window, expected):+ selection = ModelSelection(ENDPOINT, ModelCapabilities(context_window=window))+ assert selection.context_window == expected+ assert selection.capabilities.context_window == window+++async def test_reasoning_effort_must_be_declared_by_the_route():+ provider = ScriptedProvider([[Done(assistant())]])+ agent = make_agent(provider, reasoning_effort="high")+ agent.models = FakeModelRouter(+ provider,+ [+ ModelSelection(+ ENDPOINT,+ ModelCapabilities(supports_reasoning=True, reasoning_efforts=("low",)),+ )+ ],+ )+ await collect(agent)+ assert provider.requests[0].reasoning_effort is None++[email protected]("stop_reason", ["stop", "length", "refusal", "safety"])[email protected]("shape", ["empty", "whitespace", "thinking", "visible"])[email protected]("continuation", ["final", "steer", "follow_up"])+async def test_tool_free_final_reply_is_committed_and_empty_success_is_an_error(stop_reason, shape, continuation):+ # The old refusal/safety-only table missed empty successful finals.+ # Pending-input responses are non-final and must still be allowed to continue.+ content = {+ "empty": (),+ "whitespace": (text(" \n"),),+ "thinking": (ThinkingBlock("private reasoning"),),+ "visible": (ThinkingBlock("private reasoning"), text("visible reply")),+ }[shape]+ message = replace(assistant(stop_reason=stop_reason), content=content)++ async def first(request, cancel):+ if continuation != "final":+ assert await getattr(agent, continuation)(input_row("pending", "continue"))+ yield Done(message)++ provider = ScriptedProvider([first, [Done(assistant("next visible reply"))]])+ agent = make_agent(provider)+ events = await collect(agent)+ rows = await agent.store.load("session")+ responses = [row for row in rows if row.kind == "response"]+ assert responses[0].message == message+ committed = [event for event in events if isinstance(event, MessageCommitted)]+ expected_finals = [True] if continuation == "final" else [False, True]+ assert [agent.store.final[row.row_id] for row in responses] == expected_finals+ assert [event.final for event in committed] == expected_finals+ assert [event.message_id for event in committed] == [row.row_id for row in responses]+ assert len(provider.requests) == provider.closed_streams == len(expected_finals)+ assert [row.row_id for row in rows if row.kind == "input"] == (+ ["input"] if continuation == "final" else ["input", "pending"]+ )+ errors = [event for event in events if isinstance(event, AgentError)]+ if shape == "visible" or continuation != "final":+ assert errors == []+ assert events[-1].reason == "completed"+ else:+ assert len(errors) == 1+ assert errors[0].kind == (stop_reason if stop_reason in {"refusal", "safety"} else "empty_response")+ assert errors[0].message+ assert committed[0].seq < errors[0].seq < events[-1].seq+ assert events[-1].reason == "error"+ project(rows)++[email protected]("source", ["provider", "tool", "before_model", "after_run"])+async def test_dependency_cancelled_error_emits_a_terminal_event_and_preserves_consumer(source):+ class CancelHook(Hooks):+ async def before_model(self, request, ctx):+ if source == "before_model":+ raise asyncio.CancelledError()++ async def after_run(self, outcome, ctx):+ if source == "after_run":+ raise asyncio.CancelledError()++ async def stream(request, cancel):+ if source == "provider":+ raise asyncio.CancelledError()+ yield Done(assistant(calls=[ToolCallBlock("a", "echo")] if source == "tool" else []))++ async def execute(arguments, ctx):+ raise asyncio.CancelledError()++ agent = make_agent(ScriptedProvider([stream]), hooks=[CancelHook()], tools=[FakeTool(execute=execute)])+ events = await collect(agent)+ assert isinstance(events[-1], RunEnded)+ assert events[-1].reason == ("completed" if source == "after_run" else "aborted")+ assert any(isinstance(event, AgentError) and event.kind == "dependency_cancelled" for event in events)++[email protected]("step", ["response", "tool_result"])+async def test_every_committed_output_is_announced_even_when_hook_state_cannot_be_saved(step):+ class FailingStore(InMemoryTranscriptStore):+ async def append_payload(self, session_id, kind, payload):+ raise OSError("state persistence unavailable")++ class DirtyState(Hooks):+ async def before_model(self, request, ctx):+ if step == "response":+ ctx.state["dirty"] = True++ async def after_tool(self, call, result, ctx):+ if step == "tool_result":+ ctx.state["dirty"] = True++ store = FailingStore()+ provider = ScriptedProvider([[Done(assistant(calls=[ToolCallBlock("a", "echo")]))]])+ agent = make_agent(provider, store=store, hooks=[DirtyState()], tools=[FakeTool()])+ events = await collect(agent)+ committed = [row for row in await store.load("session") if row.kind in {"response", "tool_result"}]+ announced = [+ event.message_id if isinstance(event, MessageCommitted) else event.event_id+ for event in events+ if isinstance(event, (MessageCommitted, ToolFinished))+ ]+ assert [row.row_id for row in committed] == announced+ assert events[-1].reason == "error"++[email protected]("termination", ["terminate", "hook", "abort", "provider_error"])+async def test_early_termination_returns_accepted_unconsumed_inputs_to_adapter(termination):+ class StopHook(Hooks):+ async def after_tool(self, call, result, ctx):+ if termination == "hook":+ return End()++ async def accept():+ assert await agent.steer(input_row("steer", "steer"))+ assert await agent.follow_up(input_row("follow", "follow"))++ async def stream(request, cancel):+ if termination == "provider_error":+ await accept()+ yield ProviderError("auth", "denied", False)+ else:+ yield Done(assistant(calls=[ToolCallBlock("a", "echo")]))++ async def execute(arguments, ctx):+ await accept()+ if termination == "abort":+ agent.abort()+ await ctx.cancel.wait()+ return ToolResult((text("done"),), terminate=termination == "terminate")++ agent = make_agent(ScriptedProvider([stream]), tools=[FakeTool(execute=execute)], hooks=[StopHook()])+ await collect(agent)+ with pytest.raises(RuntimeError, match="unconsumed"):+ await collect(agent, "new")+ pending = await agent.take_pending_inputs()+ assert [item.message_id for item in pending] == ["steer", "follow"]+ assert await agent.take_pending_inputs() == ()+ assert [row.row_id for row in await agent.store.load("session") if row.kind == "input"] == ["input"]+++async def test_failed_queued_input_commit_keeps_pending_input_and_announces_prior_commits():+ class Store(InMemoryTranscriptStore):+ async def consume_input(self, session_id, message_id, message):+ if message_id == "second":+ raise OSError("input unavailable")+ return await super().consume_input(session_id, message_id, message)++ async def stream(request, cancel):+ assert await agent.steer(input_row("first", "first"))+ assert await agent.steer(input_row("second", "second"))+ yield Done(assistant())++ store = Store()+ agent = make_agent(ScriptedProvider([stream]), store=store)+ events = await collect(agent)+ durable_response = next(row for row in await store.load("session") if row.kind == "response")+ assert [event.message_id for event in events if isinstance(event, MessageCommitted)] == [durable_response.row_id]+ assert [event.message_id for event in events if isinstance(event, SteerApplied)] == ["first"]+ assert [item.message_id for item in await agent.take_pending_inputs()] == ["second"]+++async def test_partial_response_commit_failure_still_emits_a_terminal_error():+ class Store(InMemoryTranscriptStore):+ async def append_response(self, session_id, message, *, final):+ raise OSError("response persistence unavailable")++ provider = ScriptedProvider(+ [+ [+ ProviderError("server", "stream failed", False, partial=assistant("partial", stop_reason="error")),+ ]+ ]+ )+ events = await collect(make_agent(provider, store=Store()))+ assert events[-1].reason == "error"+ assert any(+ isinstance(event, AgentError) and event.message == "response persistence unavailable" for event in events+ )+++ "phase,reason",+ [+ ("before_start", "aborted"),+ ("before_store", "aborted"),+ ("model", "aborted"),+ ("tool", "aborted"),+ ("dependency", "aborted"),+ ("consumer", "aborted"),+ ("tool_exception", "completed"),+ ("tool_overflow", "completed"),+ ("completed", "completed"),+ ("cleanup", "completed"),+ ],+)+async def test_run_lifecycle_owns_admission_and_releases_every_foreground_job(phase, reason):+ """A single lifecycle table covers admission, cancellation and release.++ Earlier tests checked cancellation outcomes individually but missed work+ admitted after abort and jobs abandoned on non-abort execution exits.+ """+ entered, release = asyncio.Event(), asyncio.Event()+ host = FakeJobHost()+ hook_calls, outcomes, events, store_writes = [], [], [], []++ class Store(InMemoryTranscriptStore):+ async def load(self, session_id):+ if phase == "before_start":+ entered.set()+ await release.wait()+ return await super().load(session_id)++ async def consume_input(self, *args):+ store_writes.append("input")+ return await super().consume_input(*args)++ class Observe(Hooks):+ async def before_run(self, input, ctx):+ hook_calls.append("before_run")+ if phase == "before_store":+ ctx.cancel.cancel("abort before storage")++ async def after_run(self, outcome, ctx):+ outcomes.append(outcome.reason)+ if phase == "cleanup":+ await agent.jobs.start(+ "cleanup",+ cwd="/test-owned",+ env={},+ timeout_s=None,+ session_id=ctx.session_id,+ tool_call_id="cleanup",+ )++ async def stream(request, cancel):+ if phase == "model":+ entered.set()+ await release.wait()+ yield Done(assistant(calls=[ToolCallBlock("a", "bash")]))++ async def execute(arguments, ctx):+ watched = await agent.jobs.start(+ "watched",+ cwd=ctx.cwd,+ env=ctx.env,+ timeout_s=None,+ session_id=ctx.session_id,+ tool_call_id=ctx.tool_call_id,+ )+ await agent.jobs.hand_over(watched)+ await agent.jobs.start(+ "foreground",+ cwd=ctx.cwd,+ env=ctx.env,+ timeout_s=None,+ session_id=ctx.session_id,+ tool_call_id=ctx.tool_call_id,+ )+ if phase == "dependency":+ raise asyncio.CancelledError()+ if phase == "tool_exception":+ raise ValueError("output parsing failed")+ if phase == "tool_overflow":+ raise OverflowError("tool argument too large")+ if phase in {"tool", "consumer"}:+ entered.set()+ ctx.on_progress("working")+ await release.wait()+ return ToolResult((text("done"),))++ provider = ScriptedProvider([stream, [Done(assistant())]])+ agent = make_agent(provider, store=Store(), hooks=[Observe()], tools=[FakeTool("bash", execute=execute)], jobs=host)+ iterator = agent.run(input_row("input", "hello"), turn_id="turn")++ async def consume():+ try:+ async for event in iterator:+ events.append(event)+ if phase == "consumer" and isinstance(event, ToolProgress):+ break+ finally:+ await iterator.aclose()++ run = asyncio.create_task(consume())+ if phase in {"before_start", "model", "tool"}:+ await asyncio.wait_for(entered.wait(), 1)+ agent.abort("test cancellation")+ release.set()+ await asyncio.wait_for(run, 1)+ if phase == "consumer":+ assert not any(isinstance(event, RunEnded) for event in events)+ assert outcomes == [reason]+ else:+ assert isinstance(events[-1], RunEnded)+ assert events[-1].reason == reason+ if phase == "before_start":+ assert hook_calls == []+ if phase in {"before_start", "before_store"}:+ assert provider.requests == []+ assert store_writes == []+ for job_id in host.states:+ assert host.status(job_id).state == ("running" if job_id in host.watches else "gone")+ assert not set(host.killed) & host.watches.keys()+ assert await agent.steer(input_row("late", "late")) is False++[email protected]("bad_state", [{1: "value"}, {"value": ("item",)}, {"value": float("nan")}, {"value": {1}}])+async def test_hook_state_rejects_non_json_shapes_without_coercion(bad_state):+ class Invalid(Hooks):+ async def before_run(self, input, ctx):+ ctx.state = bad_state++ agent = make_agent(ScriptedProvider([[Done(assistant())]]), hooks=[Invalid()])+ events = await collect(agent)+ assert events[-1].reason == "error"+ assert any(isinstance(event, AgentError) and event.kind == "HookStateError" for event in events)+ assert await agent.store.load("session") == []+ assert agent.snapshot().state == {}+++async def test_hook_state_representation_distinguishes_bool_int_and_survives_resume():+ seen = []++ class Update(Hooks):+ async def before_run(self, input, ctx):+ ctx.state["value"] = 1++ async def after_model(self, message, ctx):+ ctx.state["value"] = True++ async def after_run(self, outcome, ctx):+ seen.append(ctx.state.copy())++ agent = make_agent(ScriptedProvider([[Done(assistant())]]), hooks=[Update()])+ await collect(agent)+ assert type(agent.snapshot().state["value"]) is bool+ rows = await agent.store.load("session")+ states = [row.payload["state"] for row in rows if row.kind == "agent_state"]+ assert len(states) == 2+ assert type(states[0]["value"]) is int+ assert type(states[1]["value"]) is bool++ class Resume(Hooks):+ async def before_run(self, input, ctx):+ seen.append(ctx.state.copy())++ resumed = make_agent(ScriptedProvider([[Done(assistant())]]), store=agent.store, hooks=[Resume()])+ await collect(resumed, "next")+ assert all(type(state["value"]) is bool for state in seen)+ assert len([row for row in await agent.store.load("session") if row.kind == "agent_state"]) == 2+++async def test_invalid_cleanup_hook_state_is_diagnostic_without_overwriting_abort():+ class InvalidCleanup(Hooks):+ async def before_model(self, request, ctx):+ ctx.cancel.cancel()++ async def after_run(self, outcome, ctx):+ ctx.state["invalid"] = ("tuple",)++ agent = make_agent(ScriptedProvider([]), hooks=[InvalidCleanup()])+ events = await collect(agent)+ assert events[-1].reason == "aborted"+ assert any(isinstance(event, AgentError) and event.kind == "HookStateError" for event in events)+ assert agent.snapshot().state == {}+++async def test_request_headers_are_detached_from_router_selection_across_turns():+ class Rewrite(Hooks):+ first = True++ async def before_model(self, request, ctx):+ if self.first:+ request.endpoint.request_headers["X-Transient"] = "only this request"+ self.first = False++ endpoint = replace(ENDPOINT, request_headers={"X-Base": "stable"})+ selection = ModelSelection(endpoint, ModelCapabilities())+ provider = ScriptedProvider([[Done(assistant())], [Done(assistant())]])+ agent = make_agent(provider, hooks=[Rewrite()])+ agent.models = FakeModelRouter(provider, [selection])+ await collect(agent)+ await collect(agent, "next")+ assert provider.requests[0].endpoint.request_headers == {"X-Base": "stable", "X-Transient": "only this request"}+ assert provider.requests[1].endpoint.request_headers == {"X-Base": "stable"}+ assert endpoint.request_headers == {"X-Base": "stable"}++[email protected]("cause", ["tool_error", "dependency", "abort"])+async def test_failed_foreground_kill_is_reported_and_does_not_skip_other_handles(cause):+ class Host(FakeJobHost):+ def __init__(self):+ super().__init__()+ self.attempts = []++ async def kill(self, job_id):+ self.attempts.append(job_id)+ if job_id == "job_2":+ raise OSError("kill denied")+ await super().kill(job_id)++ host = Host()+ provider = ScriptedProvider([[Done(assistant(calls=[ToolCallBlock("a", "bash")]))], [Done(assistant())]])+ agent = make_agent(provider, jobs=host)++ async def execute(arguments, ctx):+ for index in range(3):+ job = await agent.jobs.start(+ "fake",+ cwd=ctx.cwd,+ env=ctx.env,+ timeout_s=None,+ session_id=ctx.session_id,+ tool_call_id=ctx.tool_call_id,+ )+ if index == 0:+ await agent.jobs.hand_over(job)+ if cause == "dependency":+ raise asyncio.CancelledError()+ if cause == "abort":+ agent.abort()+ await asyncio.Event().wait()+ raise ValueError("tool failed")++ agent.set_tools([FakeTool("bash", execute=execute)])+ events = await collect(agent)+ assert events[-1].reason == ("error" if cause == "tool_error" else "aborted")+ assert any(+ isinstance(event, AgentError) and event.kind == "ForegroundCleanupError" and "kill denied" in event.message+ for event in events+ )+ assert host.attempts == ["job_2", "job_3", "job_2"]+ assert host.status("job_1").state == host.status("job_2").state == "running"+ assert host.status("job_3").state == "gone"+ assert len(provider.requests) == (2 if cause == "tool_error" else 1)+ if cause == "dependency":+ errors = [event.kind for event in events if isinstance(event, AgentError)]+ assert errors[0] == "dependency_cancelled"++[email protected]("phase", ["abort", "consumer"])+async def test_admitted_commit_finishes_before_cancellation_releases_run_ownership(phase):+ entered, release = asyncio.Event(), asyncio.Event()+ interrupted = []++ class Store(InMemoryTranscriptStore):+ async def append_response(self, *args, **kwargs):+ entered.set()+ try:+ await release.wait()+ except asyncio.CancelledError:+ interrupted.append(True)+ raise+ return await super().append_response(*args, **kwargs)++ agent = make_agent(ScriptedProvider([[Done(assistant())]]), store=Store())+ task = asyncio.create_task(collect(agent))+ await entered.wait()+ if phase == "abort":+ agent.abort()+ else:+ task.cancel()+ # Let generator closure reach its worker; no wall-clock timing.+ for _ in range(3):+ await asyncio.sleep(0)+ release.set()+ if phase == "consumer":+ with pytest.raises(asyncio.CancelledError):+ await task+ else:+ events = await task+ assert events[-1].reason == "aborted"+ assert any(isinstance(event, MessageCommitted) for event in events)+ assert interrupted == []+ rows = await agent.store.load("session")+ assert rows[-1].kind == "response"+ assert agent.snapshot().context_seq == rows[-1].context_seq+ assert await agent.steer(input_row("late", "late")) is Falsediff --git a/tests/agent_core/agent/test_outcomes.py b/tests/agent_core/agent/test_outcomes.pynew file mode 100644index 000000000..07a941e44--- /dev/null+++ b/tests/agent_core/agent/test_outcomes.py@@ -0,0 +1,507 @@+"""Primary outcomes survive independent cleanup; bad output stays uncommitted.++Previous lifecycle tests covered admission/release, not the primary x cleanup+cross product or the gap between receiving a terminal and committing it.+"""++import asyncio+from dataclasses import replace+from types import SimpleNamespace++import pytest++from core.agent_core.agent.events import AgentError, MessageCommitted, RunEnded, ToolFinished+from core.agent_core.agent.hooks import AgentInput, AlterResult, End, Hooks+from core.agent_core.agent.loop import Agent+from core.agent_core.agent.models import RetryPolicy+from core.agent_core.ai.provider import Done, ProviderError+from core.agent_core.harness.projection import project+from core.agent_core.messages import LargeRef, TextBlock, ToolCallBlock, UserMessage, text+from core.agent_core.tools.base import ToolResult+from tests.agent_core.fakes import (+ FakeJobHost,+ FakeModelRouter,+ FakeTool,+ InMemoryTranscriptStore,+ ScriptedProvider,+ assistant,+ input_row,+)+++def agent_for(provider, *, hooks=(), store=None, tools=()):+ return Agent(+ session_id="session",+ models=FakeModelRouter(provider),+ tools=tools,+ hooks=hooks,+ store=store or InMemoryTranscriptStore(),+ jobs=FakeJobHost(),+ cwd="/test-owned",+ )+++async def collect(agent, row="input"):+ return [event async for event in agent.run(input_row(row, "hello"), turn_id=row)]+++ "primary,reason,error_kind",+ [+ ("done", "completed", None),+ ("done_tools", "completed", None),+ ("tool_value", "completed", None),+ ("tool_overflow", "completed", None),+ ("tool_runtime", "completed", None),+ ("provider_error", "error", "auth"),+ ("partial", "error", "server"),+ ("overflow", "context_exhausted", "overflow"),+ ("abort", "aborted", None),+ ("hook_end", "ended_by_hook", None),+ ("refusal", "error", "refusal"),+ ("safety", "error", "safety"),+ ("empty_response", "error", "empty_response"),+ ],+)[email protected]("cleanup", ["clean", "aclose", "after_run", "cancelled", "aclose_cancelled", "kill"])+async def test_primary_outcome_cross_cleanup_keeps_reason_rows_and_event_order(+ primary, reason, error_kind, cleanup, caplog+):+ store = InMemoryTranscriptStore()+ closed_rows, hook_outcomes = [], []+ has_tools = primary == "done_tools" or primary.startswith("tool_")++ class Observe(Hooks):+ async def after_model(self, message, ctx):+ if primary == "hook_end":+ return End()++ async def after_run(self, outcome, ctx):+ hook_outcomes.append(outcome.reason)+ if cleanup == "kill":+ await agent.jobs.start(+ "test-owned",+ cwd="/test-owned",+ env={},+ timeout_s=None,+ session_id=ctx.session_id,+ tool_call_id="cleanup",+ )+ if cleanup == "after_run":+ raise RuntimeError("after_run failed")+ if cleanup == "cancelled":+ raise asyncio.CancelledError()++ class Stream:+ def __init__(self, terminal):+ self.terminal = terminal++ def __aiter__(self):+ return self++ async def __anext__(self):+ if primary == "abort":+ agent.abort("user abort")+ await asyncio.Event().wait()+ if self.terminal is None:+ raise StopAsyncIteration+ terminal, self.terminal = self.terminal, None+ return terminal++ async def aclose(self):+ closed_rows.append([row.kind for row in await store.load("session")])+ if cleanup == "aclose":+ raise OSError("stream close failed")+ if cleanup == "aclose_cancelled":+ raise asyncio.CancelledError()++ class Provider:+ protocol = "anthropic"+ calls = 0++ def stream(self, request, cancel):+ self.calls += 1+ terminal = Done(assistant())+ if has_tools and self.calls == 1:+ terminal = Done(assistant(calls=[ToolCallBlock("a", "echo")]))+ elif primary == "provider_error":+ terminal = ProviderError("auth", "primary error", False)+ elif primary == "partial":+ terminal = ProviderError(+ "server", "primary error", False, partial=assistant("partial", stop_reason="error")+ )+ elif primary == "overflow":+ terminal = ProviderError("overflow", "primary error", False)+ elif primary in {"refusal", "safety"}:+ terminal = Done(assistant("", stop_reason=primary))+ elif primary == "empty_response":+ terminal = Done(assistant(""))+ return Stream(terminal)++ async def execute(arguments, ctx):+ errors = {"tool_value": ValueError, "tool_overflow": OverflowError, "tool_runtime": RuntimeError}+ raise errors[primary]("tool failed: " + "x" * 1000)++ provider, tool = Provider(), FakeTool(execute=execute if primary.startswith("tool_") else None)+ agent = agent_for(provider, store=store, hooks=[Observe()], tools=[tool])++ class UnkillableHost(FakeJobHost):+ async def kill(self, job_id):+ raise OSError("kill failed")++ if cleanup == "kill":+ agent.jobs.host = UnkillableHost()+ events = await collect(agent)+ assert isinstance(events[-1], RunEnded)+ assert events[-1].reason == ("error" if cleanup == "kill" and reason == "completed" else reason)+ assert hook_outcomes == [reason]+ assert [event.seq for event in events] == list(range(len(events)))+ rows = await store.load("session")+ expected_rows = ["input"]+ if primary not in {"abort", "provider_error", "overflow"}:+ expected_rows.append("response")+ if has_tools:+ expected_rows.extend(["tool_result", "response"])+ assert [row.kind for row in rows] == expected_rows+ expected_closes = [["input", "response"], expected_rows] if has_tools else [expected_rows]+ assert closed_rows == expected_closes # Received terminal is committed BEFORE aclose.+ committed = [event for event in events if isinstance(event, MessageCommitted)]+ responses = [row for row in rows if row.kind == "response"]+ assert [event.message_id for event in committed] == [row.row_id for row in responses]+ assert [event.final for event in committed] == (+ [False, True] if has_tools else [primary != "partial"] if responses else []+ )+ assert len(tool.calls) == (1 if has_tools else 0)+ assert provider.calls == (2 if has_tools else 1)+ if primary.startswith("tool_"):+ result = next(row.message for row in rows if row.kind == "tool_result")+ assert result.is_error+ assert result.content[0].text.startswith("tool failed: ")+ assert len(result.content[0].text) <= 500+ assert any(record.exc_info is not None for record in caplog.records)+ errors = [event for event in events if isinstance(event, AgentError)]+ expected_kinds = [error_kind] if error_kind else []+ if cleanup in {"aclose", "aclose_cancelled"}:+ expected_kinds.extend(["stream_cleanup"] * provider.calls)+ elif cleanup == "after_run":+ expected_kinds.append("RuntimeError")+ elif cleanup == "cancelled":+ expected_kinds.append("dependency_cancelled")+ elif cleanup == "kill":+ expected_kinds.append("ForegroundCleanupError")+ assert [event.kind for event in errors] == expected_kinds+ if has_tools and cleanup in {"aclose", "aclose_cancelled"}:+ assert committed[0].seq < errors[0].seq < next(event.seq for event in events if isinstance(event, ToolFinished))+ project(rows)+++ "stage,fault",+ [+ (stage, fault)+ for stage in ("before_model", "after_model_text", "after_model_tools", "before_tool", "after_tool")+ for fault in ("clean", "state_fail", "result_fail", "abort_before", "abort_during", "abort_after")+ if fault != "result_fail" or stage in {"after_model_tools", "before_tool", "after_tool"}+ ],+)+async def test_hook_end_is_a_directive_until_required_commits_succeed(stage, fault):+ """Required commit failures precede outcome selection, unlike cleanup.++ The primary/cleanup table above cannot reach this gap: its End hook does+ not dirty state or require tool results after requesting termination.+ """+ has_tools = stage in {"after_model_tools", "before_tool", "after_tool"}+ hook_outcomes = []++ class Store(InMemoryTranscriptStore):+ async def append_payload(self, session_id, kind, payload):+ if fault == "state_fail":+ raise OSError("required state write failed")+ if not has_tools and fault == "abort_during":+ agent.abort("abort during state commit")+ row = await super().append_payload(session_id, kind, payload)+ if not has_tools and fault == "abort_after":+ agent.abort("abort after state commit")+ return row++ async def append_tool_result(self, session_id, message, *, details):+ if fault == "result_fail":+ raise OSError("required tool-result write failed")+ if fault == "abort_during":+ agent.abort("abort during result commit")+ row = await super().append_tool_result(session_id, message, details=details)+ if fault == "abort_after":+ agent.abort("abort after result commit")+ return row++ class Hook(Hooks):+ def end(self, ctx):+ ctx.state["ended_at"] = stage+ if fault == "abort_before":+ agent.abort("abort before required commit")+ return End()++ async def before_model(self, request, ctx):+ if stage == "before_model":+ return self.end(ctx)++ async def after_model(self, message, ctx):+ if stage in {"after_model_text", "after_model_tools"}:+ return self.end(ctx)++ async def before_tool(self, call, ctx):+ if stage == "before_tool":+ return self.end(ctx)++ async def after_tool(self, call, result, ctx):+ if stage == "after_tool":+ return self.end(ctx)++ async def after_run(self, outcome, ctx):+ hook_outcomes.append(outcome.reason)++ calls = [ToolCallBlock("a", "echo"), ToolCallBlock("b", "echo")] if has_tools else []+ provider = ScriptedProvider([[Done(assistant(calls=calls))]])+ tool = FakeTool()+ agent = agent_for(provider, hooks=[Hook()], store=Store(), tools=[tool])+ events = await collect(agent)+ reason = "ended_by_hook" if fault == "clean" else "aborted" if fault.startswith("abort_") else "error"+ assert events[-1].reason == reason+ assert hook_outcomes == [reason]+ errors = [event for event in events if isinstance(event, AgentError)]+ if fault in {"state_fail", "result_fail"}:+ assert errors[0].kind == "OSError"+ assert (+ errors[0].message+ == {"state_fail": "required state write failed", "result_fail": "required tool-result write failed"}[fault]+ )+ else:+ assert errors == []+ rows = await agent.store.load("session")+ # Cleanup may save valid dirty state after abort, but it must not commit the+ # still-unexecuted tool results or report a successful hook-end outcome.+ expected_rows = ["input"]+ if stage != "before_model":+ expected_rows.append("response")+ if fault != "state_fail":+ expected_rows.append("agent_state")+ result_count = 0+ if has_tools:+ result_count = 2 if fault == "clean" else 1 if fault in {"abort_during", "abort_after"} else 0+ expected_rows.extend(["tool_result"] * result_count)+ assert [row.kind for row in rows] == expected_rows+ assert agent.snapshot().state == ({} if fault == "state_fail" else {"ended_at": stage})+ assert [event.event_id for event in events if isinstance(event, ToolFinished)] == [+ row.row_id for row in rows if row.kind == "tool_result"+ ]+ assert len(provider.requests) == (0 if stage == "before_model" else 1)+ assert len(tool.calls) == (1 if stage == "after_tool" else 0)+ project(rows)+++ "source,invalid",+ [+ (source, invalid)+ for source in ("response", "partial")+ for invalid in (+ "duplicate_calls",+ "large_ref",+ "arguments_key",+ "arguments_tuple",+ "arguments_nonfinite",+ "arguments_nested",+ )+ ]+ + [(source, "large_ref") for source in ("tool", "after_tool", "terminating_tool", "input", "steer", "follow_up")],+)+async def test_message_admission_matches_projection_and_a_fresh_agent_can_resume(source, invalid):+ """Every writer rejects projection poison before the durable write.++ The old response-only table missed tools, hook rewrites and consumed+ inputs; each could persist a schema-valid ref that blocks every fresh run.+ """+ store = InMemoryTranscriptStore()+ await store.consume_input("session", "prior", UserMessage((text("preserved history"),)))+ baseline = await store.load("session")+ content = (TextBlock(ref=LargeRef("sha256:" + "a" * 64, 1)),)+ bad_input = AgentInput("bad-input", UserMessage(content))+ message = assistant(calls=[ToolCallBlock("same", "echo"), ToolCallBlock("same", "echo")])+ if invalid == "large_ref":+ message = replace(message, content=content)+ elif invalid.startswith("arguments_"):+ # Shallow-frozen blocks still expose mutable arguments. Construct a+ # valid value first so this remains a boundary test after foundation sync.+ call = ToolCallBlock("bad", "echo")+ call.arguments["nested"] = {+ "arguments_key": {1: "value"},+ "arguments_tuple": (1, 2),+ "arguments_nonfinite": float("inf"),+ "arguments_nested": [{"value": b"not JSON"}],+ }[invalid]+ message = assistant(calls=[call])+ bad_result = ToolResult(content, terminate=source == "terminating_tool")+ has_tools = source in {"tool", "after_tool", "terminating_tool"}+ queued = source in {"steer", "follow_up"}++ async def execute(arguments, ctx):+ if has_tools and ctx.tool_call_id == "bad" and source != "after_tool":+ return bad_result+ return ToolResult((text(ctx.tool_call_id),))++ class Override(Hooks):+ async def after_tool(self, call, result, ctx):+ if source == "after_tool" and call.id == "bad":+ return AlterResult(bad_result)++ async def queue_input(request, cancel):+ assert await getattr(agent, source)(bad_input)+ yield Done(assistant())++ if has_tools:+ scripts = [+ [Done(assistant(calls=[ToolCallBlock(name, "echo") for name in ("good", "bad", "later")]))],+ [Done(assistant())],+ ]+ elif queued:+ scripts = [queue_input, [Done(assistant())]]+ else:+ terminal = (+ ProviderError("server", "partial error", False, partial=message) if source == "partial" else Done(message)+ )+ scripts = [[terminal], [Done(assistant())]]+ provider, tool = ScriptedProvider(scripts), FakeTool(execute=execute)+ agent = agent_for(provider, store=store, tools=[tool], hooks=[Override()])+ incoming = bad_input if source == "input" else input_row("input", "hello")+ events = [event async for event in agent.run(incoming, turn_id="turn")]+ assert events[-1].reason == "error"+ expected_kind = "ProviderProtocolViolation" if source in {"response", "partial"} else "ProjectionError"+ assert [event.kind for event in events if isinstance(event, AgentError)] == [expected_kind]+ rows = await store.load("session")+ assert rows[: len(baseline)] == baseline+ expected_kinds = ["input"]+ if source != "input":+ expected_kinds.append("input")+ if has_tools or queued:+ expected_kinds.append("response")+ if has_tools:+ expected_kinds.append("tool_result")+ assert [row.kind for row in rows] == expected_kinds+ assert [ctx.tool_call_id for _, ctx in tool.calls] == (["good", "bad"] if has_tools else [])+ assert [event.message_id for event in events if isinstance(event, MessageCommitted)] == [+ row.row_id for row in rows if row.kind == "response"+ ]+ assert [event.event_id for event in events if isinstance(event, ToolFinished)] == [+ row.row_id for row in rows if row.kind == "tool_result"+ ]+ assert len(provider.requests) == (0 if source == "input" else 1)+ assert await agent.take_pending_inputs() == ((bad_input,) if queued else ())+ project(rows)+ fresh = agent_for(ScriptedProvider([[Done(assistant())]]), store=agent.store)+ assert (await collect(fresh, "next"))[-1].reason == "completed"+++ "elapsed,retries,retry_after,expected",+ [+ (0, 0, None, 0.5),+ (0, 2, None, 2),+ (0, 3, None, None),+ (119, 0, 2, None),+ (118, 0, 1, 1),+ (120, 0, None, None),+ ],+)+def test_retry_policy_enforces_c2_count_and_elapsed_bounds(elapsed, retries, retry_after, expected):+ # Existing retry tests only bounded the count; Retry-After could exceed the+ # entire C-2 elapsed budget. No wall clock or network is used here.+ policy = RetryPolicy(max_retries=3)+ error = ProviderError("rate_limit", "busy", True, retry_after_s=retry_after)+ assert policy.delay(error, retries=retries, streamed=False, elapsed_s=elapsed) == expected++[email protected]("kwargs", [{"max_retries": 4}, {"max_elapsed_s": 121}, {"max_elapsed_s": float("nan")}])+def test_retry_policy_configuration_cannot_weaken_contract(kwargs):+ with pytest.raises(ValueError):+ RetryPolicy(**kwargs)+++ "expiration,elapsed",+ [+ ("retry_after", 121),+ ("sleep", 119),+ ("sleep", 120),+ ("sleep", 121),+ ("route", 119),+ ("route", 120),+ ("route", 121),+ ],+)[email protected]("hook_action", ["end", "raise", "mutate"])+async def test_retry_deadline_owns_admission_before_rehydration_and_hooks(+ monkeypatch, expiration, elapsed, hook_action+):+ # Provider-count-only assertions missed callbacks and persisted side effects+ # after a slow route resolution had already exhausted the retry budget.+ now = [0.0]+ sleeps = []+ hook_times = []+ rehydration_times = []+ real_sleep = asyncio.sleep++ async def sleep(delay):+ sleeps.append(delay)+ if expiration == "sleep":+ now[0] = elapsed+ await real_sleep(0)++ class Router(FakeModelRouter):+ async def resolve(self):+ result = await super().resolve()+ if expiration == "route" and self.resolutions == 2:+ now[0] = elapsed+ return result++ class Hook(Hooks):+ async def before_model(self, request, ctx):+ hook_times.append(now[0])+ if len(hook_times) == 2:+ ctx.state["retry_hook"] = True+ if hook_action == "end":+ return End()+ if hook_action == "raise":+ raise ValueError("retry hook failure")++ def rehydrate(state):+ rehydration_times.append(now[0])+ return ()++ monkeypatch.setattr("core.agent_core.agent.loop.time", SimpleNamespace(monotonic=lambda: now[0]))+ monkeypatch.setattr("core.agent_core.agent.loop.asyncio.sleep", sleep)+ error = ProviderError(+ "rate_limit", "original busy error", True, retry_after_s=121 if expiration == "retry_after" else 1+ )+ provider = ScriptedProvider([[error], [Done(assistant())]])+ agent = agent_for(provider, hooks=[Hook()])+ agent.models = Router(provider)+ agent.rehydrate = rehydrate+ events = await collect(agent)+ expired = expiration == "retry_after" or elapsed >= 120+ if expired:+ assert events[-1].reason == "error"+ assert [(e.kind, e.message) for e in events if isinstance(e, AgentError)] == [+ ("rate_limit", "original busy error")+ ]+ assert hook_times == rehydration_times == [0]+ assert agent.snapshot().state == {}+ assert [row.kind for row in await agent.store.load("session")] == ["input"]+ else:+ assert hook_times == rehydration_times == [0, elapsed]+ assert agent.snapshot().state == {"retry_hook": True}+ assert events[-1].reason == {"end": "ended_by_hook", "raise": "error", "mutate": "completed"}[hook_action]+ assert [(e.kind, e.message) for e in events if isinstance(e, AgentError)] == (+ [("ValueError", "retry hook failure")] if hook_action == "raise" else []+ )+ assert len(provider.requests) == (2 if not expired and hook_action == "mutate" else 1)+ assert sleeps == ([] if expiration == "retry_after" else [1])diff --git a/tests/agent_core/agent/test_projection.py b/tests/agent_core/agent/test_projection.pynew file mode 100644index 000000000..2ae7eb2b7--- /dev/null+++ b/tests/agent_core/agent/test_projection.py@@ -0,0 +1,71 @@+"""C-5 orphan/ancestry projection risks not covered by message serialization."""++from copy import deepcopy++import pytest++from core.agent_core.harness.projection import INTERRUPTED, ProjectionError, project+from core.agent_core.harness.store import ContextEntry+from core.agent_core.messages import ToolCallBlock, ToolResultMessage, text+from tests.agent_core.fakes import assistant, user+++def test_unsettled_projection_is_deterministic_and_preserves_signed_calls():+ call = ToolCallBlock("call", "bash", signature="opaque Gemini signature")+ owner = ContextEntry("parent", 1, "response", "response", assistant(calls=[call]))+ rows = [owner]+ before = deepcopy(rows)+ projected = project(rows)+ assert projected == project(rows)+ assert projected.messages[0].tool_calls[0].signature == "opaque Gemini signature"+ assert projected.messages[1].content[0].text == INTERRUPTED+ assert projected.messages[1].is_error+ assert rows == before+++def test_projection_sorts_rows_cuts_at_fork_restores_state_and_places_results_in_call_order():+ calls = [ToolCallBlock("a", "echo"), ToolCallBlock("b", "echo")]+ rows = [+ ContextEntry("parent", 1, "input", "input", user("start")),+ ContextEntry("parent", 2, "response", "response", assistant(calls=calls)),+ ContextEntry("parent", 3, "tool_result", "result-b", ToolResultMessage("b", "echo", (text("b"),))),+ ContextEntry("parent", 4, "agent_state", "state", payload={"version": 1, "state": {"counter": [1]}}),+ ContextEntry("child", 5, "input", "child-input", user("child")),+ ContextEntry("parent", 6, "context_edit", "later-edit", payload={}),+ ]+ output = project(list(reversed(rows)), fork_point=5, system="rebuilt system", rehydrated=[user("rehydrated")])+ assert output.system == "rebuilt system"+ assert output.context_seq == 5+ assert [getattr(message, "tool_call_id", None) for message in output.messages] == [None, None, None, "a", "b", None]+ assert output.messages[3].content[0].text == INTERRUPTED+ assert output.messages[4].content[0].text == "b"+ output.state["counter"].append(2)+ assert rows[3].payload["state"] == {"counter": [1]}++[email protected]("kind", ["compaction", "context_edit"])+def test_P3_context_rows_fail_explicitly_instead_of_silently_replaying_old_context(kind):+ with pytest.raises(ProjectionError, match=f"{kind} requires P3"):+ project([ContextEntry("session", 1, kind, "unsupported", payload={})])+++def test_malformed_or_duplicate_results_are_not_silently_dropped():+ result = ContextEntry("session", 2, "tool_result", "result", ToolResultMessage("a", "echo", (text("a"),)))+ with pytest.raises(ProjectionError, match="no preceding call"):+ project([result])+ response = ContextEntry("session", 1, "response", "response", assistant(calls=[ToolCallBlock("a", "echo")]))+ with pytest.raises(ProjectionError, match="duplicate tool result"):+ project([response, result, ContextEntry("session", 3, "tool_result", "duplicate", result.message)])++[email protected]("arguments", [{"nested": {1: "value"}}, {"nested": (1, 2)}])+def test_projection_revalidates_mutable_arguments_in_loaded_ancestry(arguments):+ # Admission cannot protect rows supplied by a store/fork loader from later+ # mutation. Projection must reject them without normalizing the input.+ call = ToolCallBlock("call", "echo")+ call.arguments.update(arguments)+ rows = [ContextEntry("parent", 1, "response", "response", assistant(calls=[call]))]+ original = deepcopy(rows)+ with pytest.raises(ProjectionError, match="call.*response"):+ project(rows)+ assert rows == originaldiff --git a/tests/agent_core/agent/test_recovery.py b/tests/agent_core/agent/test_recovery.pynew file mode 100644index 000000000..debf90bed--- /dev/null+++ b/tests/agent_core/agent/test_recovery.py@@ -0,0 +1,273 @@+"""Recovery owns durable settlement; projection cannot observe live jobs.++These cover the crash windows and fork invariance absent from the old live-job+projection tests: a retry must skip committed outcomes, a partial settlement+must resume in call order, and later job changes cannot rewrite model history.+"""++import pytest++from core.agent_core.agent.hooks import Snapshot+from core.agent_core.agent.jobs import TrackingJobHost+from core.agent_core.agent.loop import Agent+from core.agent_core.agent.recovery import settle_open_calls+from core.agent_core.ai.provider import Done+from core.agent_core.harness.projection import INTERRUPTED, ProjectionError, project+from core.agent_core.messages import LargeRef, TextBlock, ToolCallBlock, ToolResultMessage, text+from core.agent_core.tools.base import JobStatus, ToolResult+from tests.agent_core.fakes import (+ FakeJobHost,+ FakeModelRouter,+ InMemoryTranscriptStore,+ ScriptedProvider,+ assistant,+ input_row,+ user,+)+++def renderer(jobs):+ def render(call, job_id, status, watch_id):+ output, _ = jobs.output(job_id)+ content = (+ f"still running, now Watch {watch_id}"+ if watch_id is not None+ else f"{output.decode()}; exit={status.exit_code}"+ )+ return ToolResult(+ (text(content),),+ is_error=status.state == "exited" and status.exit_code != 0,+ details={"full_output_path": jobs.output_path(job_id)},+ )++ return render+++ "tool_name,state",+ [+ ("bash", "missing"),+ ("write", "missing"),+ ("edit", "missing"),+ ("bash", "never-ran"),+ ("bash", "running"),+ ("bash", "exited"),+ ("bash", "gone"),+ ],+)+async def test_resume_settles_each_job_state_once_and_projection_never_rechecks_it(tool_name, state):+ # T2 requires uncertainty, not an implied absence of effects, for calls+ # without job state. The previous bash-only table missed write/edit wording.+ store, jobs = InMemoryTranscriptStore(), FakeJobHost()+ call = ToolCallBlock("call", tool_name)+ await store.append_response("session", assistant(calls=[call]), final=False)+ job_ids = {}+ if state != "missing":+ job_ids[("session", "call")] = "job_1"+ jobs.states["job_1"] = JobStatus(+ "gone" if state == "never-ran" else state, exit_code=7 if state == "exited" else None+ )+ jobs.outputs["job_1"] = b"final output"++ committed = await settle_open_calls(+ session_id="session",+ store=store,+ jobs=jobs,+ job_ids=job_ids,+ render_result=(+ renderer(jobs)+ if state in {"running", "exited"}+ else lambda *args: pytest.fail("missing/gone jobs must not invoke the renderer")+ ),+ )+ assert len(committed) == 1+ assert (+ committed[0].message.content[0].text+ == {+ "missing": (+ "[tool call interrupted; it may or may not have completed; re-read the file before continuing]"+ ),+ "never-ran": INTERRUPTED,+ "gone": INTERRUPTED,+ "running": "still running, now Watch watch_job_1",+ "exited": "final output; exit=7",+ }[state]+ )+ assert committed[0].message.is_error == (state != "running")+ assert bool(jobs.watches) == (state == "running")+ assert jobs.starts == jobs.killed == []+ projected = project(await store.load("session"))+ jobs.states["job_1"] = JobStatus("exited", exit_code=0)+ jobs.outputs["job_1"] = b"later output"+ assert (+ await settle_open_calls(+ session_id="session",+ store=store,+ jobs=jobs,+ job_ids=job_ids,+ render_result=renderer(jobs),+ )+ == ()+ )+ assert project(await store.load("session")) == projected++[email protected]("failure", ["store_write", "unsupported_result"])+async def test_settlement_resume_after_partial_commit_skips_done_calls_and_keeps_call_order(failure):+ # A schema-valid but unsupported renderer result must fail before its+ # append. The prior store-failure-only case could not detect poisoned rows.+ class InterruptedStore(InMemoryTranscriptStore):+ fail = True++ async def append_tool_result(self, session_id, message, *, details):+ if failure == "store_write" and self.fail and message.tool_call_id == "b":+ raise OSError("crashed before the second result commit")+ return await super().append_tool_result(session_id, message, details=details)++ store, jobs = InterruptedStore(), FakeJobHost()+ await store.append_response(+ "session",+ assistant(+ calls=[+ ToolCallBlock("a", "bash"),+ ToolCallBlock("b", "bash"),+ ]+ ),+ final=False,+ )+ for name in ("a", "b"):+ jobs.states[name] = JobStatus("exited", exit_code=0)+ jobs.outputs[name] = name.encode()+ ids = {("session", name): name for name in ("a", "b")}++ def render(call, job_id, status, watch_id):+ if failure == "unsupported_result" and store.fail and call.id == "b":+ return ToolResult((TextBlock(ref=LargeRef("sha256:" + "a" * 64, 1)),))+ return renderer(jobs)(call, job_id, status, watch_id)++ error_type, error_message = (+ (OSError, "second result") if failure == "store_write" else (ProjectionError, "large-content references")+ )+ with pytest.raises(error_type, match=error_message):+ await settle_open_calls(session_id="session", store=store, jobs=jobs, job_ids=ids, render_result=render)+ assert [row.message.tool_call_id for row in await store.load("session") if row.kind == "tool_result"] == ["a"]+ before_retry = project(await store.load("session"))+ assert before_retry.messages[-1].content[0].text == "[tool call interrupted; no result recorded]"+ jobs.outputs["a"] = b"must not replace committed output"+ store.fail = False+ new_rows = await settle_open_calls(session_id="session", store=store, jobs=jobs, job_ids=ids, render_result=render)+ assert [row.message.tool_call_id for row in new_rows] == ["b"]+ results = [m for m in project(await store.load("session")).messages if isinstance(m, ToolResultMessage)]+ assert [m.content[0].text for m in results] == ["a; exit=0", "b; exit=0"]+ assert (+ await settle_open_calls(session_id="session", store=store, jobs=jobs, job_ids=ids, render_result=render) == ()+ )+ fresh = Agent(+ session_id="session",+ models=FakeModelRouter(ScriptedProvider([[Done(assistant())]])),+ tools=[],+ hooks=[],+ store=store,+ jobs=jobs,+ cwd="/test-owned",+ )+ events = [event async for event in fresh.run(input_row("next", "continue"), turn_id="next")]+ assert events[-1].reason == "completed"+++async def test_fork_settlement_uses_parent_job_identity_and_late_rows_project_at_the_call():+ store, jobs = InMemoryTranscriptStore(), FakeJobHost()+ response = await store.append_response("parent", assistant(calls=[ToolCallBlock("a", "bash")]), final=False)+ store.fork(Snapshot("parent", response.context_seq, {}), session_id="child")+ # A prior interrupted runtime may already have admitted another input.+ await store.consume_input("child", "later", user("after the call"))+ jobs.states["job_a"] = JobStatus("exited", exit_code=0)+ jobs.outputs["job_a"] = b"old output"+ await settle_open_calls(+ session_id="child",+ store=store,+ jobs=jobs,+ job_ids={("parent", "a"): "job_a"},+ render_result=renderer(jobs),+ )+ child = project(await store.load("child"))+ assert [m.role for m in child.messages] == ["assistant", "tool_result", "user"]+ assert child.messages[1].content[0].text == "old output; exit=0"+ assert project(await store.load("parent")).messages[1].content[0].text == INTERRUPTED+ store.fork(Snapshot("child", child.context_seq, {}), session_id="grandchild")+ jobs.outputs["job_a"] = b"new output"+ assert project(await store.load("grandchild")) == child+++async def test_retry_after_handover_commit_failure_reuses_job_identity_without_starting_a_command():+ class InterruptedStore(InMemoryTranscriptStore):+ fail = True++ async def append_tool_result(self, session_id, message, *, details):+ if self.fail:+ raise OSError("commit interrupted")+ return await super().append_tool_result(session_id, message, details=details)++ class Host(FakeJobHost):+ def __init__(self):+ super().__init__()+ self.handovers = []++ async def hand_over(self, job_id):+ self.handovers.append(job_id)+ return await super().hand_over(job_id)++ store, jobs = InterruptedStore(), Host()+ await store.append_response("session", assistant(calls=[ToolCallBlock("a", "bash")]), final=False)+ jobs.states["job_a"] = JobStatus("running")+ jobs.outputs["job_a"] = b""+ with pytest.raises(OSError, match="commit interrupted"):+ await settle_open_calls(+ session_id="session",+ store=store,+ jobs=jobs,+ job_ids={("session", "a"): "job_a"},+ render_result=renderer(jobs),+ )+ watch = jobs.watches["job_a"]+ store.fail = False+ rows = await settle_open_calls(+ session_id="session",+ store=store,+ jobs=jobs,+ job_ids={("session", "a"): "job_a"},+ render_result=renderer(jobs),+ )+ assert len(rows) == 1+ assert rows[0].payload["details"]["watch_id"] == watch+ # Actual Watch deduplication belongs to JobHost, not this fake-backed test.+ assert jobs.handovers == ["job_a", "job_a"]+ assert jobs.starts == []+++async def test_tracking_host_forwards_the_full_output_path_and_relative_deadline():+ class Host(FakeJobHost):+ async def wait(self, job_id, *, deadline_s):+ assert (job_id, deadline_s) == ("job_a", 0.25)+ return JobStatus("running")++ host = Host()+ tracked = TrackingJobHost(host)+ assert tracked.output_path("job_a") == "/test-owned/jobs/job_a/output.log"+ assert await tracked.wait("job_a", deadline_s=0.25) == JobStatus("running")+++async def test_foreground_release_is_scoped_to_call_then_session_and_never_watch():+ # A single Agent's sequential batch cannot reach shared-host cross-Session+ # ownership; protect that distinct boundary directly on the real wrapper.+ host = FakeJobHost()+ tracked = TrackingJobHost(host)+ for session, call in [("one", "a"), ("one", "b"), ("two", "a"), ("one", "a")]:+ await tracked.start("fake", cwd="/test-owned", env={}, timeout_s=None, session_id=session, tool_call_id=call)+ await tracked.hand_over("job_4")+ await tracked.kill_foreground("one", tool_call_id="a")+ assert host.killed == ["job_1"]+ assert host.status("job_2").state == host.status("job_3").state == host.status("job_4").state == "running"+ await tracked.kill_foreground("one")+ assert host.killed == ["job_1", "job_2"]+ assert host.status("job_3").state == host.status("job_4").state == "running"diff --git a/tests/agent_core/fakes.py b/tests/agent_core/fakes.pynew file mode 100644index 000000000..1be732ab8--- /dev/null+++ b/tests/agent_core/fakes.py@@ -0,0 +1,195 @@+"""Small hermetic C-2/C-5/C-7 fakes shared by agent-core lanes.++The provider records detached requests before running each script. The store+implements only committed entries and fork ancestry, not loop/projection logic.+Jobs have explicit test-controlled state and never spawn processes.+"""++from __future__ import annotations++import asyncio+from collections import deque+from copy import deepcopy+from typing import AsyncIterator, Callable, Mapping, Optional, Sequence++from core.agent_core.agent.hooks import AgentInput, Snapshot+from core.agent_core.agent.models import ModelSelection+from core.agent_core.ai.provider import ModelCapabilities, ModelEndpoint, ModelRequest, ProviderEvent+from core.agent_core.cancel import CancelToken+from core.agent_core.harness.store import ContextEntry+from core.agent_core.messages import AssistantMessage, Origin, ToolResultMessage, UserMessage, text+from core.agent_core.tools.base import JobStatus, ToolContext, ToolResult, ToolSpec++ORIGIN = Origin("test-provider", "anthropic", "test-model")+ENDPOINT = ModelEndpoint("anthropic", "http://model.invalid", "test-model", "", provider="test-provider")+SELECTION = ModelSelection(+ ENDPOINT, ModelCapabilities(context_window=32000, max_output_tokens=4096, supports_tools=True, supports_images=True)+)+Script = Sequence[ProviderEvent] | Callable[[ModelRequest, CancelToken], AsyncIterator[ProviderEvent]]+++def user(value: str) -> UserMessage:+ return UserMessage((text(value),))+++def input_row(row_id: str, value: str) -> AgentInput:+ return AgentInput(row_id, user(value))+++def assistant(value: str = "done", *, calls=(), stop_reason=None) -> AssistantMessage:+ content = ((text(value),) if value else ()) + tuple(calls)+ return AssistantMessage(content, ORIGIN, stop_reason or ("tool_use" if calls else "stop"))+++class ScriptedProvider:+ protocol = "anthropic"++ def __init__(self, scripts: Sequence[Script]) -> None:+ self.scripts = deque(scripts)+ self.requests: list[ModelRequest] = []+ self.closed_streams = 0++ async def stream(self, request: ModelRequest, cancel: CancelToken) -> AsyncIterator[ProviderEvent]:+ self.requests.append(deepcopy(request))+ if not self.scripts:+ raise AssertionError("the loop made an unscripted provider call")+ script = self.scripts.popleft()+ try:+ if callable(script):+ async for event in script(request, cancel):+ yield event+ else:+ for event in script:+ yield deepcopy(event)+ finally:+ self.closed_streams += 1+++class FakeModelRouter:+ def __init__(self, provider: ScriptedProvider, selections: Sequence[ModelSelection] = (SELECTION,)) -> None:+ self.provider = provider+ self.selections = tuple(selections)+ self.resolutions = 0+ self.protocols: list[str] = []++ async def resolve(self) -> ModelSelection:+ index = min(self.resolutions, len(self.selections) - 1)+ self.resolutions += 1+ return self.selections[index]++ def provider_for(self, protocol):+ self.protocols.append(protocol)+ return self.provider+++class InMemoryTranscriptStore:+ def __init__(self) -> None:+ self.rows: dict[str, list[ContextEntry]] = {}+ self.forks: dict[str, Snapshot] = {}+ self.final: dict[str, bool] = {}+ self._next_id = 0++ def fork(self, snapshot: Snapshot, *, session_id: str) -> None:+ if session_id in self.rows or session_id in self.forks:+ raise ValueError("child already exists")+ self.forks[session_id] = deepcopy(snapshot)++ async def load(self, session_id: str) -> Sequence[ContextEntry]:+ prefix = []+ anchor = self.forks.get(session_id)+ if anchor is not None:+ prefix = [row for row in await self.load(anchor.session_id) if row.context_seq <= anchor.context_seq]+ return deepcopy(prefix + self.rows.get(session_id, []))++ async def _append(self, session_id, kind, *, message=None, payload=None, row_id=None) -> ContextEntry:+ entries = await self.load(session_id)+ seq = max((entry.context_seq for entry in entries), default=0) + 1+ if row_id is None:+ self._next_id += 1+ row_id = f"row_{self._next_id}"+ if any(entry.row_id == row_id for entry in entries):+ raise ValueError(f"input already consumed: {row_id}")+ row = ContextEntry(session_id, seq, kind, row_id, deepcopy(message), deepcopy(payload or {}))+ self.rows.setdefault(session_id, []).append(row)+ return deepcopy(row)++ async def consume_input(self, session_id, message_id, message: UserMessage) -> ContextEntry:+ return await self._append(session_id, "input", row_id=message_id, message=message)++ async def append_response(self, session_id, message: AssistantMessage, *, final: bool) -> ContextEntry:+ row = await self._append(session_id, "response", message=message)+ self.final[row.row_id] = final+ return row++ async def append_tool_result(self, session_id, message: ToolResultMessage, *, details: Mapping) -> ContextEntry:+ return await self._append(session_id, "tool_result", message=message, payload={"details": dict(details)})++ async def append_payload(self, session_id, kind, payload: Mapping) -> ContextEntry:+ return await self._append(session_id, kind, payload=payload)+++class FakeTool:+ def __init__(self, name="echo", execute=None, result: Optional[ToolResult] = None) -> None:+ self.spec = ToolSpec(name, "Test tool", {"type": "object"})+ self.calls: list[tuple[dict, ToolContext]] = []+ self._execute = execute+ self.result = result or ToolResult((text("tool result"),))++ async def execute(self, arguments, ctx: ToolContext) -> ToolResult:+ self.calls.append((deepcopy(dict(arguments)), ctx))+ if self._execute is not None:+ return await self._execute(arguments, ctx)+ return deepcopy(self.result)+++class FakeJobHost:+ def __init__(self) -> None:+ self.states: dict[str, JobStatus] = {}+ self.outputs: dict[str, bytes] = {}+ self.starts: list[dict] = []+ self.killed: list[str] = []+ self.watches: dict[str, str] = {}+ self.changed = asyncio.Event()++ async def start(self, command, *, cwd, env, timeout_s, session_id, tool_call_id) -> str:+ job_id = f"job_{len(self.starts) + 1}"+ self.starts.append(+ dict(+ command=command,+ cwd=cwd,+ env=dict(env),+ timeout_s=timeout_s,+ session_id=session_id,+ tool_call_id=tool_call_id,+ job_id=job_id,+ )+ )+ self.states[job_id] = JobStatus("running")+ self.outputs[job_id] = b""+ return job_id++ def status(self, job_id) -> JobStatus:+ return self.states.get(job_id, JobStatus("gone"))++ async def wait(self, job_id, *, deadline_s) -> JobStatus:+ while self.status(job_id).state == "running":+ self.changed.clear()+ await self.changed.wait()+ return self.status(job_id)++ def output(self, job_id, since=0) -> tuple[bytes, int]:+ output = self.outputs[job_id]+ return output[since:], len(output)++ def output_path(self, job_id) -> str:+ return f"/test-owned/jobs/{job_id}/output.log"++ async def kill(self, job_id) -> None:+ self.killed.append(job_id)+ self.states[job_id] = JobStatus("gone")+ self.changed.set()++ async def hand_over(self, job_id) -> str:+ watch_id = f"watch_{job_id}"+ self.watches[job_id] = watch_id+ return watch_id