Skip to content
Python

fix(observability): close the gap with the background-subagents feature

Rohit C Prasad9a66c1e3b30e
diff --git a/coworker/engine.py b/coworker/engine.py
index 4395f0de..0598f06f 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -1674,10 +1674,12 @@ class TurnEngine:
}
state = self.compaction_state
if state is not None:
+ # Duck-typed on purpose: tests and embedders stub compaction_state with
+ # partial objects; the snapshot must degrade, never raise.
snapshot["compaction"] = {
- "created_at": state.created_at,
- "messages": state.boundary_index,
- "trimmed": state.trimmed,
+ "created_at": getattr(state, "created_at", None),
+ "messages": getattr(state, "boundary_index", None),
+ "trimmed": bool(getattr(state, "trimmed", False)),
}
return snapshot
diff --git a/coworker/observability/engine_hooks.py b/coworker/observability/engine_hooks.py
index 4b90c785..c0cbf359 100644
--- a/coworker/observability/engine_hooks.py
+++ b/coworker/observability/engine_hooks.py
@@ -225,11 +225,15 @@ class TurnRecording:
call_index: Optional[int] = None, parent_step_id: Optional[str] = None,
attrs: Optional[dict[str, Any]] = None,
content: Optional[dict[str, Any]] = None,
- turn_id: Any = CURRENT, shadow: bool = False) -> Optional[str]:
+ turn_id: Any = CURRENT, shadow: bool = False,
+ after_turn: Optional[bool] = None) -> Optional[str]:
"""`step_started`. The step belongs to the engine's current turn, or with `turn_id` to
that turn: a step tagged with a turn that already ended is `after_turn` (§3.3, an
after-turn title). A model step outside any turn is recorded with no turn; a tool
- step outside a turn is not recorded."""
+ step outside a turn is not recorded. An explicit `after_turn` overrides the
+ has-the-turn-ended computation: a detached helper (a background subagent) marks its
+ steps after_turn from the start, so the turn-end sweep (§7.4) never closes a step
+ whose owner legitimately outlives the turn."""
if not self.enabled:
return None
with self._lock:
@@ -248,6 +252,8 @@ class TurnRecording:
# Turns of one engine run one after another: another turn of this engine has
# ended, and so has this one once its end was sent.
after = tid is not None and (not same or self._ended)
+ if after_turn is not None:
+ after = bool(after_turn)
step_id = new_ulid()
ev = self._base("step_started", tid, sid)
ev.update({"step_id": step_id, "parent_step_id": parent_step_id, "kind": kind,
@@ -497,9 +503,14 @@ class HelperRecording:
# The helper's context is not the session's: no context step under the explore step.
records_context = False
- def __init__(self, parent: TurnRecording, parent_step_id: str, turn_id: Optional[str]) -> None:
+ def __init__(self, parent: TurnRecording, parent_step_id: str, turn_id: Optional[str],
+ *, detached: bool = False) -> None:
self.parent, self.parent_step_id = parent, parent_step_id
self.turn_id = turn_id
+ # A detached helper (a background subagent, OPE-253) outlives the parent's turn:
+ # every one of its steps is after_turn so the §7.4 turn-end sweep never closes a
+ # step its owner is still running. Explore's synchronous helper stays attached.
+ self.detached = detached
self.index = parent.helper_index(parent_step_id)
self._lock = threading.Lock()
self._kinds: dict[str, str] = {} # the helper's open steps: step_id -> kind
@@ -556,6 +567,8 @@ class HelperRecording:
kw.setdefault("parent_step_id", None)
kw["parent_step_id"] = kw["parent_step_id"] or self.parent_step_id
kw["turn_id"] = self.turn_id
+ if self.detached:
+ kw.setdefault("after_turn", True)
step_id = self.parent.start_step(**kw)
if step_id is not None:
with self._lock:
diff --git a/coworker/tools/agent_tasks.py b/coworker/tools/agent_tasks.py
index 42777ddd..42866f00 100644
--- a/coworker/tools/agent_tasks.py
+++ b/coworker/tools/agent_tasks.py
@@ -44,6 +44,8 @@ from typing import Any, Callable, Optional
import aisuite as ai
from ..engine import ApprovalOutcome, EventType, PermissionRequest, TurnEngine
+from ..observability.engine_hooks import HelperRecording, current_tool_run
+from ..observability.provider_view import tag as tag_provider
from .subagent import build_explorer_engine
_MAX_ACTIVE = 3
@@ -149,6 +151,11 @@ class AgentTask:
# The loop the child runs on (its own in read_only, the server's in inherit) —
# how cancel and follow-ups reach it thread-safely.
loop: Optional[asyncio.AbstractEventLoop] = None
+ # Observability (OPE-244 integration): the child's steps and model calls recorded
+ # on the parent's turn, nested under the spawn_agent step — the same HelperRecording
+ # contract as explore, so the Steps panel and the Usage ledger see background
+ # children too. None when recording was off at spawn time.
+ obs: Optional[Any] = None
def snapshot(self) -> dict[str, Any]:
return {
@@ -304,6 +311,17 @@ class AgentTaskRegistry:
self._finish(task, report, status)
def _finish(self, task: AgentTask, report: str, status: str) -> None:
+ # The spawn step's helper pill (attrs.helper, same shape as explore's): model
+ # calls, tool calls and tokens the child spent, stamped when it ends. Display
+ # only — the Usage ledger already counted its steps as they happened.
+ if task.obs is not None:
+ try:
+ task.obs.parent.update_step(
+ task.obs.parent_step_id,
+ attrs={"helper": task.obs.summary({"canceled": "interrupted"}.get(status, status))},
+ )
+ except Exception:
+ pass # a recording hiccup must never take the run result down
task.finished = time.time()
task.report = report
if status == "completed":
@@ -402,7 +420,7 @@ def agent_task_tools(
registry = AgentTaskRegistry()
ws = str(Path(workspace).resolve())
- def _build_child(task: AgentTask) -> TurnEngine:
+ def _build_child(task: AgentTask, child_provider: Any) -> TurnEngine:
if task.mode == "inherit":
parent = registry.parent
assert parent is not None
@@ -410,7 +428,7 @@ def agent_task_tools(
exclude={"spawn_agent", "agent_task_output", "agent_send", "agent_task_cancel", "explore"}
)
child = TurnEngine(
- provider=provider,
+ provider=child_provider,
registry=child_registry,
permissions=parent.permissions, # same mode, same session grants
model=model,
@@ -430,7 +448,7 @@ def agent_task_tools(
return child
return build_explorer_engine(
workspace=ws,
- provider=provider,
+ provider=child_provider,
model=model,
model_settings=model_settings,
max_iterations=_CHILD_MAX_ITERATIONS,
@@ -479,7 +497,21 @@ def agent_task_tools(
if approval_timeout:
timeout = max(float(approval_timeout), _MIN_APPROVAL_TIMEOUT)
t = registry.new_task(label.strip() or task.strip()[:40], task, mode, timeout)
- t.engine = _build_child(t)
+ # Observability (OPE-244 integration): the child records under THIS spawn step,
+ # on the parent's turn, exactly like explore's helper — so background runs show
+ # in the Steps panel and their tokens reach the Usage ledger. The recording
+ # outlives this turn by design; late steps on an ended turn are already a
+ # recorder concept (the after-turn title step).
+ run = current_tool_run()
+ child_provider: Any = provider
+ if run is not None and run.step_id is not None:
+ t.obs = HelperRecording(run.recording, run.step_id, run.turn_id, detached=True)
+ child_provider = tag_provider(
+ run.view, purpose="helper", parent=run.step_id, turn=run.turn_id, sink=t.obs
+ )
+ t.engine = _build_child(t, child_provider)
+ if t.obs is not None:
+ t.engine._obs = t.obs
registry._emit("agent_task_started", t)
_launch(t, task)
return {
diff --git a/tests/test_observability_subagents.py b/tests/test_observability_subagents.py
new file mode 100644
index 00000000..faebd72a
--- /dev/null
+++ b/tests/test_observability_subagents.py
@@ -0,0 +1,110 @@
+"""Observability × async subagents (the gap between OPE-244 and the subagents feature
+merged 2026-11-07): a background spawn_agent child records like explore's helper —
+its model and tool steps nest under the spawn_agent step on the parent's turn, its
+tokens reach the ledger, and the spawn step gains `attrs.helper` when it finishes,
+even though the child outlives the turn.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+
+from coworker.engine import TurnEngine
+from coworker.observability import Recorder
+from coworker.observability.provider_view import RecordingProvider
+from coworker.permissions import Mode, PermissionEngine
+from coworker.providers import AssistantTurn, ModelCapabilities, ProviderClient, ToolCall
+from coworker.providers.base import TokenUsage
+from coworker.tools import ToolRegistry
+from coworker.tools.agent_tasks import agent_task_tools
+
+
+class _DualProvider(ProviderClient):
+ """Scripts the parent (spawn, then done) and the explorer child (one read, then a
+ report), told apart by the child's system prompt."""
+
+ def complete(self, *, model, messages, tools=None, **settings):
+ head = messages[0] if messages else {}
+ is_child = head.get("role") == "system" and "read-only code explorer" in str(
+ head.get("content", "")
+ )
+ had_tool = any(m.get("role") == "tool" for m in messages)
+ if is_child:
+ if had_tool:
+ return AssistantTurn(
+ text="report: notes.txt says Friday release",
+ usage=TokenUsage(input=70, output=7),
+ )
+ return AssistantTurn(
+ tool_calls=[ToolCall(id="h1", name="read_file", arguments={"path": "notes.txt"})],
+ finish_reason="tool_calls",
+ )
+ if not had_tool:
+ return AssistantTurn(
+ tool_calls=[
+ ToolCall(
+ id="c1",
+ name="spawn_agent",
+ arguments={"task": "what is in notes.txt?", "label": "notes check"},
+ )
+ ],
+ finish_reason="tool_calls",
+ )
+ return AssistantTurn(text="spawned, moving on", usage=TokenUsage(input=50, output=5))
+
+ def capabilities(self, model):
+ return ModelCapabilities(tools=True)
+
+
+def test_background_child_records_under_the_spawn_step(tmp_path):
+ (tmp_path / "notes.txt").write_text("Friday release", encoding="utf-8")
+ base = RecordingProvider(_DualProvider())
+ tools, tasks = agent_task_tools(workspace=tmp_path, provider=base, model="openai:model-a")
+ registry = ToolRegistry()
+ registry.register_all(tools)
+ engine = TurnEngine(
+ provider=base,
+ registry=registry,
+ permissions=PermissionEngine(workspace_root=tmp_path, mode=Mode.BYPASS_APPROVALS),
+ model="openai:model-a",
+ )
+ tasks.bind(engine)
+ engine.agent_tasks = tasks
+ engine.audit_context = {"session_id": "sess_bg"}
+ rec = Recorder()
+ engine.recorder = rec
+
+ async def go():
+ return [ev async for ev in engine.run("survey the notes in the background")]
+
+ asyncio.run(go())
+
+ deadline = time.time() + 10
+ while time.time() < deadline:
+ snap = tasks.snapshot()
+ if snap and snap[0]["status"] == "done":
+ break
+ time.sleep(0.05)
+ assert tasks.snapshot()[0]["status"] == "done"
+
+ d = rec.as_dict()
+ [spawn] = [s for s in d["steps"] if s["kind"] == "tool" and s["name"] == "spawn_agent"]
+ nested = [s for s in d["steps"] if s.get("parent_step_id") == spawn["step_id"]]
+ kinds = {(s["kind"], (s.get("attrs") or {}).get("purpose")) for s in nested}
+ assert ("model", "helper") in kinds, "the child's model calls must record as helper steps"
+ assert ("tool", None) in kinds, "the child's read must nest under the spawn step"
+ [read] = [s for s in nested if s["kind"] == "tool"]
+ assert read["name"] == "read_file" and read["attrs"]["decision"] == {"helper": True}
+ # Detached helpers mark every step after_turn, so the §7.4 turn-end sweep can never
+ # close a step the still-running child owns (the race this test exists to pin).
+ assert all(s.get("after_turn") for s in nested)
+ assert all(s.get("status") != "interrupted" for s in nested)
+
+ # The child never becomes a second turn, and the spawn step carries the summary
+ # pill with the tokens the child actually spent.
+ assert len(d["turns"]) == 1
+ helper = (spawn.get("attrs") or {}).get("helper")
+ assert helper is not None, "the finished child must stamp attrs.helper on its spawn step"
+ assert helper["status"] == "ok"
+ assert helper["model_calls"] >= 1 and helper["tokens"] > 0