← Back to Pull requests

Add ai.remote and RemoteAgent, for running an agent in a worker #350

Open
msullivan opened this pull request with 1018 lines diff across 5 files
View on GitHub
msullivan msullivan commented on Nov 13, 2026 01:08 UTC
Author

We add a generic protocol (ai.remote.Runner) for doing async
execution of functions in a remote runner.

ai.remote.RemoteAgent will offload the entire loop to a remote
runner when one is configured.

The main ai.Agent can offload tool calls to a remote runner also,
with different values to the execution_strategy to ai.tool:
local: always run locally
remote-enabled: use remote if a runner is configured
* remote: always remote, fail otherwise

A remote runner is configured with ai.remote.use_runner.

Diff: 1018 lines (+1016 / -2) across 5 files Reviewer: msullivan Review duration: 26129m
All Vouch review confidence checks passed
Residual risk 0.12 = Change Risk (0.63) × (1 − Review Confidence (0.80)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.63 · 1018 lines diff across 5 files
0.63
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.92 · 5 substantive comment(s)
0.92
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
80%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Self Review self_review
0.140
Real PR Conversation Timeline
13 items
vercel[bot] vercel[bot] commented on Nov 13, 2026 01:08 UTC
Bot

[vc]: #GARvbmhL/Mx8BK4NzDi95Z2TGBpjNJ6OImWcudcEEUc=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJhaS1weXRob24iLCJwcm9qZWN0SWQiOiJwcmpfRDg5bUY1TUlndnVuR0UyeVFuZWdQUlM3VnBlMCIsImluc3BlY3RvclVybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS92ZXJjZWwtbGFicy9haS1weXRob24vMmZHNWs4QXdDdXJ4UEJMaHNCSEdoaVFGTldOaSIsInByZXZpZXdVcmwiOiJhaS1weXRob24tZ2l0LXJlbW90ZS1hZ2VudC5sYWJzLnZlcmNlbC5kZXYiLCJuZXh0Q29tbWl0U3RhdHVzIjoiREVQTE9ZRUQiLCJsaXZlRmVlZGJhY2siOnsicmVzb2x2ZWQiOjAsInVucmVzb2x2ZWQiOjAsInRvdGFsIjowLCJsaW5rIjoiYWktcHl0aG9uLWdpdC1yZW1vdGUtYWdlbnQubGFicy52ZXJjZWwuZGV2In0sInJvb3REaXJlY3RvcnkiOiJkb2NzL2FpLXB5dGhvbiJ9XX0=
The latest updates on your projects. Learn more about Vercel for GitHub.

| Project | Deployment | Actions | Updated |
| :--- | :----- | :------ | :------ |
| <a href="https://vercel.com/vercel-labs/ai-python"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_D89mF5MIgvunGE2yQnegPRS7Vpe0&teamId=team_nO2mCG4W8IxPIeKoSsqwAxxB&s=32" width="16" height="16" align="middle" alt="" /></sup></a> ai-python | !Ready Ready | Preview, v0 | <relative-time datetime="2026-11-17T01:16:42.179Z">Nov 17, 2026 1:16am UTC</relative-time> |

anbuzin anbuzin commented on Nov 13, 2026 19:55 UTC
Contributor

Instead of having two ways to specify remoteness, (remote_tools and worker mode) we could make it so RemoteAgent always runs the loop remote, and normal ai.Agent always runs loop locally; and for the normal agent you can specify at tool definition time, whether you want that tool to run remote or locally.

Module-wise, I think we can make both of these top-level modules, even though they technically aren't AI-only; we have prior art in the form of ai.telemetry.

anbuzin anbuzin commented on Nov 13, 2026 19:56 UTC
Contributor

We can prefix all of them as ai.experimental though.

vercel[bot] vercel[bot] commented on code on Nov 16, 2026 23:13 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:
+            async for event in stream:
+                if not isinstance(event, _Added) and event.replay:
+                    # Not serialized with the event, but validated.
+                    yield {**event.model_dump(mode="json"), "replay": True}
+                else:
+                    yield event
+    finally:
+        del _registries[key]
+
+
+def _resolve_remote(
+    key: str, label: str, resolution: dict[str, Any] | BaseException
+) -> None:
+    if registry := _registries.get(key):
+        hooks_.resolve_hook(label, resolution, registry=registry)
+
+
+async def _cancel_remote(key: str, label: str, reason: str | None) -> None:
+    registry = _registries.get(key)
+    if registry is not None and label in registry._live_hooks:
+        await hooks_.cancel_hook(label, reason=reason, registry=registry)
+
+
+class _HookBridge:
+    """Stands in here for the remote loop's pending hooks.
+
+    A stand-in is a live hook in this run's registry, so the caller
+    resolves or cancels it as usual; the outcome is then passed on to
+    the hook in the runner.
+    """
+
+    def __init__(self, runner: Runner, key: str) -> None:
+        self._runner = runner
+        self._key = key
+        self._registry = hooks_.get_hook_registry()
+        self._runtime = runtime_.get_runtime()
+        self._tasks: dict[str, asyncio.Task[None]] = {}
+        self._cancelled: set[str] = set()
+
+    def forward(self, event: events.HookEvent) -> bool:
+        """Note a hook event from the runner; return whether to yield it.
+
+        A cancellation made here was already reported here.
+        """
+        hook = event.hook
+        if hook.status == "cancelled":
+            return hook.hook_id not in self._cancelled
+        if hook.status == "pending":
+            future: asyncio.Future[dict[str, Any]] = asyncio.Future()
+            self._registry._live_hooks[hook.hook_id] = (
+                future,
+                hook.metadata,
+                self._runtime,
+            )
+            self._tasks[hook.hook_id] = asyncio.create_task(
+                self._pass_on(hook.hook_id, future)
+            )

When an approval is pre\-registered before stream iteration\, RemoteAgent ignores that resolution and waits indefinitely for the already\-answered hook\.

<a href="https://vercel.com/vercel-labs/~/agent/tasks/b4a7274a-895b-42c8-b556-9dd248016784#suggestion-7171a4e842e334a863f49341458f3aae43f8cc6794157300f4f26a3967500c36" rel="noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://vercel.com/vercel-agent-view-suggestion-dark"><source media="(prefers-color-scheme: light)" srcset="https://vercel.com/vercel-agent-view-suggestion-light"><img src="https://vercel.com/vercel-agent-view-suggestion-light" alt="Fix on Vercel" width="127" height="28" /></picture></a>

<!-- VADE-GITHUB-SUGGESTION-ID:7171a4e842e334a863f49341458f3aae43f8cc6794157300f4f26a3967500c36 -->

<!-- OMNIAGENT-REVIEW-LOCATION:src%2Fai%2Fremote%2F__init__.py:162:172 -->

<!-- VADE-RECOMMENDATION: FIX -->

<!-- VADE-OUTCOME: ISSUE_RESOLVED -->

vercel[bot] vercel[bot] commented on code on Nov 16, 2026 23:13 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:

When a RemoteAgent loop or its tools call ai\.current\_agent\(\) in the worker\, the missing execution context raises LookupError instead of returning the running agent\.

<a href="https://vercel.com/vercel-labs/~/agent/tasks/b4a7274a-895b-42c8-b556-9dd248016784#suggestion-ab43c6e85626c1fe5e7e49bdcc3830214a7551998b65372a5701962b7f9e3654" rel="noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://vercel.com/vercel-agent-view-suggestion-dark"><source media="(prefers-color-scheme: light)" srcset="https://vercel.com/vercel-agent-view-suggestion-light"><img src="https://vercel.com/vercel-agent-view-suggestion-light" alt="Fix on Vercel" width="127" height="28" /></picture></a>

<!-- VADE-GITHUB-SUGGESTION-ID:ab43c6e85626c1fe5e7e49bdcc3830214a7551998b65372a5701962b7f9e3654 -->

<!-- OMNIAGENT-REVIEW-LOCATION:src%2Fai%2Fremote%2F__init__.py:108:115 -->

<!-- VADE-RECOMMENDATION: FIX -->

<!-- VADE-OUTCOME: ISSUE_RESOLVED -->

vercel[bot] vercel[bot] commented on code on Nov 16, 2026 23:13 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:
+            async for event in stream:
+                if not isinstance(event, _Added) and event.replay:
+                    # Not serialized with the event, but validated.
+                    yield {**event.model_dump(mode="json"), "replay": True}
+                else:
+                    yield event
+    finally:
+        del _registries[key]
+
+
+def _resolve_remote(
+    key: str, label: str, resolution: dict[str, Any] | BaseException
+) -> None:
+    if registry := _registries.get(key):
+        hooks_.resolve_hook(label, resolution, registry=registry)
+
+
+async def _cancel_remote(key: str, label: str, reason: str | None) -> None:
+    registry = _registries.get(key)
+    if registry is not None and label in registry._live_hooks:
+        await hooks_.cancel_hook(label, reason=reason, registry=registry)
+
+
+class _HookBridge:
+    """Stands in here for the remote loop's pending hooks.
+
+    A stand-in is a live hook in this run's registry, so the caller
+    resolves or cancels it as usual; the outcome is then passed on to
+    the hook in the runner.
+    """
+
+    def __init__(self, runner: Runner, key: str) -> None:
+        self._runner = runner
+        self._key = key
+        self._registry = hooks_.get_hook_registry()
+        self._runtime = runtime_.get_runtime()
+        self._tasks: dict[str, asyncio.Task[None]] = {}
+        self._cancelled: set[str] = set()
+
+    def forward(self, event: events.HookEvent) -> bool:
+        """Note a hook event from the runner; return whether to yield it.
+
+        A cancellation made here was already reported here.
+        """
+        hook = event.hook
+        if hook.status == "cancelled":
+            return hook.hook_id not in self._cancelled
+        if hook.status == "pending":
+            future: asyncio.Future[dict[str, Any]] = asyncio.Future()
+            self._registry._live_hooks[hook.hook_id] = (
+                future,
+                hook.metadata,
+                self._runtime,
+            )
+            self._tasks[hook.hook_id] = asyncio.create_task(
+                self._pass_on(hook.hook_id, future)
+            )
+        return True
+
+    async def _pass_on(
+        self, label: str, future: asyncio.Future[dict[str, Any]]
+    ) -> None:
+        try:
+            try:
+                resolution: dict[str, Any] | BaseException = await future
+            except asyncio.CancelledError as exc:
+                if not future.cancelled():
+                    raise
+                self._cancelled.add(label)
+                reason = exc.args[0] if exc.args else None
+                await self._runner.run(_cancel_remote, self._key, label, reason)
+                return
+            except Exception as exc:
+                resolution = exc
+            await self._runner.run(
+                _resolve_remote, self._key, label, resolution
+            )
+        finally:
+            self._registry._live_hooks.pop(label, None)
+            self._tasks.pop(label, None)
+
+    async def aclose(self) -> None:
+        tasks = list(self._tasks.values())
+        for task in tasks:
+            task.cancel()
+        await asyncio.gather(*tasks, return_exceptions=True)
+
+
+class RemoteAgent(agents.Agent):
+    """An agent that runs its loop in the ambient runner, if there is one.
+
+    Override ``loop`` as usual; it's the loop that runs in the runner.
+    """
+
+    async def _loop(
+        self, context: agents.Context
+    ) -> AsyncGenerator[events.AgentEvent]:
+        runner = runner_._runner.get()
+        if runner is None or runner_._in_runner.get():
+            async with contextlib.aclosing(self.loop(context)) as stream:
+                async for event in stream:
+                    yield event
+            return
+        key = uuid.uuid4().hex
+        bridge = _HookBridge(runner, key)
+        tools = messages_.tool_context(self._tools)
+        items = pydantic.TypeAdapter[events.AgentEvent | _Added](
+            events.AgentEvent | _Added
+        )
+        streaming = {
+            t.name: (
+                t.aggregator,
+                pydantic.TypeAdapter(agent_._item_type(t.fn)),
+            )
+            for t in self._tools
+            if t.aggregator is not None
+        }
+        try:
+            async with runner.iterate(
+                _remote_loop, self, context, key, free_running=True
+            ) as s:
+                async for data in s:
+                    item = items.validate_python(data, context=tools)
+                    if isinstance(item, _Added):
+                        context.messages.extend(item.messages)
+                        continue
+                    if (
+                        isinstance(item, events.PartialToolCallResult)
+                        and item.label is None
+                        and item.tool_name in streaming
+                    ):
+                        factory, adapter = streaming[item.tool_name]
+                        item = item.model_copy(
+                            update={
+                                "aggregator_factory": factory,
+                                "value": adapter.validate_python(item.value),
+                            }
+                        )
+                    if not isinstance(item, events.HookEvent) or bridge.forward(
+                        item
+                    ):
+                        yield item

When a SubAgentTool waits for approval\, RemoteAgent skips its wrapped HookEvent\, so resolving the nested hook never unblocks the run\.

<a href="https://vercel.com/vercel-labs/~/agent/tasks/b4a7274a-895b-42c8-b556-9dd248016784#suggestion-2b974a6a686d7747751cc44add3f0d6b872f7b9b37dff73d39987d6a92d41550" rel="noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://vercel.com/vercel-agent-view-suggestion-dark"><source media="(prefers-color-scheme: light)" srcset="https://vercel.com/vercel-agent-view-suggestion-light"><img src="https://vercel.com/vercel-agent-view-suggestion-light" alt="Fix on Vercel" width="127" height="28" /></picture></a>

<!-- VADE-GITHUB-SUGGESTION-ID:2b974a6a686d7747751cc44add3f0d6b872f7b9b37dff73d39987d6a92d41550 -->

<!-- OMNIAGENT-REVIEW-LOCATION:src%2Fai%2Fremote%2F__init__.py:260:263 -->

<!-- VADE-RECOMMENDATION: FIX -->

msullivan msullivan commented on code on Nov 16, 2026 23:15 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:

known issue, will get a follow-up I think

msullivan msullivan commented on code on Nov 16, 2026 23:15 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:

oh, no, known issue for just pure remote tool calls but we ought to make remoteagent work

vercel[bot] vercel[bot] commented on code on Nov 17, 2026 00:26 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:
+            async for event in stream:
+                if not isinstance(event, _Added) and event.replay:
+                    # Not serialized with the event, but validated.
+                    yield {**event.model_dump(mode="json"), "replay": True}
+                else:
+                    yield event
+    finally:
+        del _registries[key]
+
+
+def _resolve_remote(
+    key: str, label: str, resolution: dict[str, Any] | BaseException
+) -> None:
+    if registry := _registries.get(key):
+        hooks_.resolve_hook(label, resolution, registry=registry)
+
+
+async def _cancel_remote(key: str, label: str, reason: str | None) -> None:
+    registry = _registries.get(key)
+    if registry is not None and label in registry._live_hooks:
+        await hooks_.cancel_hook(label, reason=reason, registry=registry)
+
+
+class _HookBridge:
+    """Stands in here for the remote loop's pending hooks.
+
+    A stand-in is a live hook in this run's registry, so the caller
+    resolves or cancels it as usual; the outcome is then passed on to
+    the hook in the runner.
+    """
+
+    def __init__(self, runner: Runner, key: str) -> None:
+        self._runner = runner
+        self._key = key
+        self._registry = hooks_.get_hook_registry()
+        self._runtime = runtime_.get_runtime()
+        self._tasks: dict[str, asyncio.Task[None]] = {}
+        self._cancelled: set[str] = set()
+
+    def forward(self, event: events.HookEvent) -> bool:
+        """Note a hook event from the runner; return whether to yield it.
+
+        A cancellation made here was already reported here.
+        """
+        hook = event.hook
+        if hook.status == "cancelled":
+            return hook.hook_id not in self._cancelled
+        if hook.status == "pending":
+            future: asyncio.Future[dict[str, Any]] = asyncio.Future()
+            self._registry._live_hooks[hook.hook_id] = (
+                future,
+                hook.metadata,
+                self._runtime,
+            )
+            self._tasks[hook.hook_id] = asyncio.create_task(
+                self._pass_on(hook.hook_id, future)
+            )

Resolved in 4fbd2ee\: the hook bridge now consumes pre\-registered resolutions and forwards them to the remote hook\.

<!-- OMNIAGENT-REVIEW-RESOLUTION:7171a4e842e334a863f49341458f3aae43f8cc6794157300f4f26a3967500c36 -->

vercel[bot] vercel[bot] commented on code on Nov 17, 2026 00:26 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:

Resolved in 4fbd2ee\: the remote loop now sets the current agent in the worker\'s execution context\.

<!-- OMNIAGENT-REVIEW-RESOLUTION:ab43c6e85626c1fe5e7e49bdcc3830214a7551998b65372a5701962b7f9e3654 -->

msullivan msullivan commented on code on Nov 17, 2026 00:44 UTC
Code Review
src/ai/remote/__init__.py:1
@@ -0,0 +1,259 @@
+"""Run tools, or an agent's whole loop, in a runner.
+
+A runner runs functions somewhere else, such as in another process or
+a sandbox; anything with ``run`` and ``iterate`` methods will do (see
+:class:`Runner`).  Make one ambient with :func:`use_runner`::
+
+    async with ai.remote.use_runner(runner):
+        async with agent.run(model, messages) as stream:
+            ...
+
+Then a tool declared with ``execution_strategy="remote"`` or
+``"remote-enabled"`` runs in the runner, and a :class:`RemoteAgent`
+runs its whole loop there, tools included; events, messages added to
+the context, and hooks come back, and hooks are resolved or cancelled
+here as usual.  Code running in the runner runs every tool in place.
+With no ambient runner, everything runs here, except that a
+``"remote"`` tool fails.
+
+The agent, its context and its tools are pickled to the runner, so
+they must be picklable there.  Nothing the runner sends is unpickled,
+since what runs there may not be trusted: events and tool results come
+back as JSON and are validated here, tool results against the tool's
+return type.  A tool without one gets its result as plain JSON data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import dataclasses
+import uuid
+from collections.abc import AsyncGenerator, Sequence
+from typing import Any, cast
+
+import pydantic
+
+from .. import agents, models
+from ..agents import agent as agent_
+from ..agents import hooks as hooks_
+from ..agents import runner as runner_
+from ..agents import runtime as runtime_
+from ..agents.runner import RemoteIterator, Runner, use_runner
+from ..types import events
+from ..types import messages as messages_
+
+__all__ = [
+    "RemoteAgent",
+    "RemoteIterator",
+    "Runner",
+    "use_runner",
+    "with_resolved_key",
+]
+
+
+def with_resolved_key(model: models.Model) -> models.Model:
+    """Copy *model* with its API key read now, so it pickles along.
+
+    Otherwise the provider reads its key's env var when it's called,
+    and a runner may not have it.
+    """
+    key = model.provider.api_key
+    if key is None:
+        return model
+    provider = model.provider.model_copy(update={"api_key_value": key})
+    return model.model_copy(update={"provider": provider})
+
+
+@dataclasses.dataclass
+class _Added:
+    """Messages the remote loop added to its copy of the context."""
+
+    messages: list[messages_.Message]
+
+
+class _SyncingContext(agents.Context):
+    """The runner's copy of the context, reporting each ``add`` at once.
+
+    The ``_Added`` goes on the runtime's queue, which is merged into the
+    event stream ahead of the loop's own events, so it comes back while
+    the loop is still waiting on the next model response.
+    """
+
+    def add(
+        self,
+        message: messages_.Message | Sequence[messages_.Message] | None,
+    ) -> None:
+        before = len(self.messages)
+        super().add(message)
+        if len(self.messages) > before:
+            queue = runtime_.get_runtime()._event_queue
+            added = _Added(self.messages[before:])
+            queue.put_nowait(cast("events.AgentEvent", added))
+
+
+# The hook registries of the loops running in this process, by key, so
+# that hooks can be resolved and cancelled from the other side.
+_registries: dict[str, hooks_.HookRegistry] = {}
+
+
+async def _remote_loop(
+    agent: RemoteAgent, context: agents.Context, key: str
+) -> AsyncGenerator[events.AgentEvent | _Added | dict[str, Any]]:
+    """Run in the runner: the agent's loop.
+
+    Tools put partial results on the runtime, so this runs its own, to
+    merge them in.
+    """
+    context.__class__ = _SyncingContext
+    runner_._in_runner.set(True)
+    registry = _registries[key] = hooks_.HookRegistry()
+    # Left set: this generator's context is the runner's, not the run's.
+    hooks_._hook_registry.set(registry)
+    try:
+        loop = agent.loop(context)
+        async with contextlib.aclosing(runtime_.run(loop)) as stream:
+            async for event in stream:
+                if not isinstance(event, _Added) and event.replay:
+                    # Not serialized with the event, but validated.
+                    yield {**event.model_dump(mode="json"), "replay": True}
+                else:
+                    yield event
+    finally:
+        del _registries[key]
+
+
+def _resolve_remote(
+    key: str, label: str, resolution: dict[str, Any] | BaseException
+) -> None:
+    if registry := _registries.get(key):
+        hooks_.resolve_hook(label, resolution, registry=registry)
+
+
+async def _cancel_remote(key: str, label: str, reason: str | None) -> None:
+    registry = _registries.get(key)
+    if registry is not None and label in registry._live_hooks:
+        await hooks_.cancel_hook(label, reason=reason, registry=registry)
+
+
+class _HookBridge:
+    """Stands in here for the remote loop's pending hooks.
+
+    A stand-in is a live hook in this run's registry, so the caller
+    resolves or cancels it as usual; the outcome is then passed on to
+    the hook in the runner.
+    """
+
+    def __init__(self, runner: Runner, key: str) -> None:
+        self._runner = runner
+        self._key = key
+        self._registry = hooks_.get_hook_registry()
+        self._runtime = runtime_.get_runtime()
+        self._tasks: dict[str, asyncio.Task[None]] = {}
+        self._cancelled: set[str] = set()
+
+    def forward(self, event: events.HookEvent) -> bool:
+        """Note a hook event from the runner; return whether to yield it.
+
+        A cancellation made here was already reported here.
+        """
+        hook = event.hook
+        if hook.status == "cancelled":
+            return hook.hook_id not in self._cancelled
+        if hook.status == "pending":
+            future: asyncio.Future[dict[str, Any]] = asyncio.Future()
+            self._registry._live_hooks[hook.hook_id] = (
+                future,
+                hook.metadata,
+                self._runtime,
+            )
+            self._tasks[hook.hook_id] = asyncio.create_task(
+                self._pass_on(hook.hook_id, future)
+            )
+        return True
+
+    async def _pass_on(
+        self, label: str, future: asyncio.Future[dict[str, Any]]
+    ) -> None:
+        try:
+            try:
+                resolution: dict[str, Any] | BaseException = await future
+            except asyncio.CancelledError as exc:
+                if not future.cancelled():
+                    raise
+                self._cancelled.add(label)
+                reason = exc.args[0] if exc.args else None
+                await self._runner.run(_cancel_remote, self._key, label, reason)
+                return
+            except Exception as exc:
+                resolution = exc
+            await self._runner.run(
+                _resolve_remote, self._key, label, resolution
+            )
+        finally:
+            self._registry._live_hooks.pop(label, None)
+            self._tasks.pop(label, None)
+
+    async def aclose(self) -> None:
+        tasks = list(self._tasks.values())
+        for task in tasks:
+            task.cancel()
+        await asyncio.gather(*tasks, return_exceptions=True)
+
+
+class RemoteAgent(agents.Agent):
+    """An agent that runs its loop in the ambient runner, if there is one.
+
+    Override ``loop`` as usual; it's the loop that runs in the runner.
+    """
+
+    async def _loop(
+        self, context: agents.Context
+    ) -> AsyncGenerator[events.AgentEvent]:
+        runner = runner_._runner.get()
+        if runner is None or runner_._in_runner.get():
+            async with contextlib.aclosing(self.loop(context)) as stream:
+                async for event in stream:
+                    yield event
+            return
+        key = uuid.uuid4().hex
+        bridge = _HookBridge(runner, key)
+        tools = messages_.tool_context(self._tools)
+        items = pydantic.TypeAdapter[events.AgentEvent | _Added](
+            events.AgentEvent | _Added
+        )
+        streaming = {
+            t.name: (
+                t.aggregator,
+                pydantic.TypeAdapter(agent_._item_type(t.fn)),
+            )
+            for t in self._tools
+            if t.aggregator is not None
+        }
+        try:
+            async with runner.iterate(
+                _remote_loop, self, context, key, free_running=True
+            ) as s:
+                async for data in s:
+                    item = items.validate_python(data, context=tools)
+                    if isinstance(item, _Added):
+                        context.messages.extend(item.messages)
+                        continue
+                    if (
+                        isinstance(item, events.PartialToolCallResult)
+                        and item.label is None
+                        and item.tool_name in streaming
+                    ):
+                        factory, adapter = streaming[item.tool_name]
+                        item = item.model_copy(
+                            update={
+                                "aggregator_factory": factory,
+                                "value": adapter.validate_python(item.value),
+                            }
+                        )
+                    if not isinstance(item, events.HookEvent) or bridge.forward(
+                        item
+                    ):
+                        yield item

Decided I don't care

Reviewers
Assignees
msullivan msullivan
Labels
risk: low confidence: 80.5% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 62.8% (MEDIUM) · Higher = larger blast radius
62.8%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 80.5% · Lower = rushed or shallow review
80.5%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 12.3% · Safe to merge
12.3%