Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): scope background tasks and notifications to their owner

Yufeng He3eca56c40bfc
diff --git a/README.md b/README.md
index 96e51d72c..a55911c6e 100644
--- a/README.md
+++ b/README.md
@@ -1708,7 +1708,7 @@ loopback development mode. When `API_AUTH_KEY` is configured, `/docs` and
For localhost development, `vibe-trading serve` keeps the browser workflow simple. For any non-local client, sensitive API endpoints require `API_AUTH_KEY`; use `Authorization: Bearer <key>` for JSON/upload requests. Browser EventSource streams are handled by the Web UI after you enter the same key once in Settings.
-Shell-capable process tools (`bash` / `background_run` / `cancel_background`) are enabled only for the interactive local CLI. Every other surface — the HTTP/SSE API and the MCP server on **all** transports (stdio included) — keeps them off unless you explicitly opt in with `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (or pass `--enable-shell-tools` to `vibe-trading-mcp`). Transport type never implicitly grants shell access. `cancel_background` stops only the tracked task ID returned by `background_run`; broad Python process-name termination is refused because it could terminate Vibe-Trading itself. Document and journal readers are limited to upload/import roots by default; place files under `~/.vibe-trading/uploads`, `~/.vibe-trading/runs`, `./uploads`, `./data` (or the legacy `agent/uploads` / `agent/runs`), or add a dedicated directory through `VIBE_TRADING_ALLOWED_FILE_ROOTS`. Sessions, runs, swarm runs, uploads, and the `sessions.db` index live under `~/.vibe-trading` (relocatable via the `VIBE_TRADING_HOME` shell environment variable); pre-existing history is moved there automatically on first run.
+Shell-capable process tools (`bash` / `background_run` / `cancel_background`) are enabled only for the interactive local CLI. Every other surface — the HTTP/SSE API and the MCP server on **all** transports (stdio included) — keeps them off unless you explicitly opt in with `VIBE_TRADING_ENABLE_SHELL_TOOLS=1` (or pass `--enable-shell-tools` to `vibe-trading-mcp`). Transport type never implicitly grants shell access. `cancel_background` stops only the tracked task ID returned by `background_run`; broad Python process-name termination is refused because it could terminate Vibe-Trading itself. A background task and the notice that it finished belong to the session or swarm worker that started them: another conversation cannot list the task, read its output or cancel it, and only the owner is shown the result. Document and journal readers are limited to upload/import roots by default; place files under `~/.vibe-trading/uploads`, `~/.vibe-trading/runs`, `./uploads`, `./data` (or the legacy `agent/uploads` / `agent/runs`), or add a dedicated directory through `VIBE_TRADING_ALLOWED_FILE_ROOTS`. Sessions, runs, swarm runs, uploads, and the `sessions.db` index live under `~/.vibe-trading` (relocatable via the `VIBE_TRADING_HOME` shell environment variable); pre-existing history is moved there automatically on first run.
Generated backtest code runs as a local Python subprocess and can make network requests through the configured market-data loaders. Its environment is intentionally narrow: the runner keeps OS/Python basics, proxy/certificate settings, `VIBE_TRADING_ALLOWED_RUN_ROOTS`, and read-only market-data keys such as `TUSHARE_TOKEN`, `FMP_API_KEY`, `FRED_API_KEY`, and `VIBE_TRADING_IWENCAI_KEY`. It does not pass LLM provider keys, API auth tokens, shell-tool switches, broker trading secrets, or live/advisory toggles to generated strategy code by default.
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index ddac01a60..5a5e85cb0 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -1245,6 +1245,16 @@ def _run_agent(
else:
console.print(f"[yellow]WARNING:[/yellow] {msg}")
+ # One owner for the whole CLI run: background results stay with the
+ # conversation that started them, and a bare run gets a private owner
+ # instead of a view shared with every other run in the process.
+ from src.tools.background_tools import BackgroundScope, get_background_manager
+
+ background_scope = BackgroundScope(
+ owner_id=f"session:{session_id}" if session_id else f"cli:{uuid.uuid4().hex}"
+ )
+ background = get_background_manager().for_scope(background_scope)
+
agent = AgentLoop(
registry=build_registry(
persistent_memory=pm,
@@ -1252,11 +1262,14 @@ def _run_agent(
agent_config=agent_config,
session_id=session_id or None,
warn_callback=_mcp_warn,
+ background_manager=background,
+ background_scope=background_scope,
),
llm=ChatLLM(),
event_callback=on_event,
max_iterations=max_iter,
persistent_memory=pm,
+ background_manager=background,
)
if run_dir_override:
agent.memory.run_dir = run_dir_override
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index dc4781aba..e0eb5dac6 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -186,6 +186,7 @@ class AgentLoop(ToolCallLifecycle):
max_iterations: int = 50,
persistent_memory: Optional[Any] = None,
cancel_event: Optional[threading.Event] = None,
+ background_manager: Optional[Any] = None,
) -> None:
"""Initialize AgentLoop.
@@ -200,6 +201,11 @@ class AgentLoop(ToolCallLifecycle):
tools (e.g. ``run_swarm``). The host session owns the event so a
user stop reaches both the loop and the tools it is blocked in;
``None`` keeps the loop self-contained (CLI and tests).
+ background_manager: Scoped handle over the background task table.
+ Must be the same handle the registry bound to its background
+ tools, so this loop drains the completions of its own tasks and
+ never another conversation's. Falls back to the handle the
+ registry recorded, and only then to an unowned one.
"""
self.registry = prepare_registry(registry)
self.llm = llm
@@ -238,6 +244,13 @@ class AgentLoop(ToolCallLifecycle):
# Skipped/error call IDs never enter this ledger.
self._successful_call_keys: dict[str, tuple[str, str]] = {}
self._cancel_event = cancel_event if cancel_event is not None else threading.Event()
+ # Resolved once, not per iteration: an unowned handle is private to
+ # itself, so re-deriving it would silently discard this loop's results.
+ self._background_manager = (
+ background_manager
+ or getattr(registry, "background", None)
+ or get_background_manager()
+ )
self._previous_summary: str = ""
self._persistent_memory = persistent_memory
self._run_iteration: int = 0
@@ -557,9 +570,8 @@ class AgentLoop(ToolCallLifecycle):
self._run_iteration += 1
current_iter = self._run_iteration
- # Inject background task notifications
- bg = get_background_manager()
- notifs = bg.drain_notifications()
+ # Inject background task notifications for this conversation.
+ notifs = self._background_manager.drain_notifications()
if notifs:
notif_text = "\n".join(f"[bg:{n['task_id']}] {n['status']}: {n['result']}" for n in notifs)
messages.append({"role": "user", "content": f"<background-results>\n{notif_text}\n</background-results>\n\n<system>Continue processing with the background results above.</system>"})
diff --git a/agent/src/session/service.py b/agent/src/session/service.py
index 3a854e085..e87be3f30 100644
--- a/agent/src/session/service.py
+++ b/agent/src/session/service.py
@@ -543,6 +543,7 @@ class SessionService:
Result dictionary containing status, run_dir, run_id, metrics, and related fields.
"""
from src.tools import build_registry
+ from src.tools.background_tools import BackgroundScope, get_background_manager
from src.providers.chat import ChatLLM
from src.agent.loop import AgentLoop
from src.memory.persistent import PersistentMemory
@@ -586,6 +587,14 @@ class SessionService:
# without a second cancellation channel that can drift out of sync.
turn_cancel = threading.Event()
+ # Background tasks belong to the session, not to the attempt: a later
+ # attempt must still read what an earlier one started. The attempt id is
+ # kept on each task so cancellation can be attributed later.
+ background_scope = BackgroundScope(
+ owner_id=f"session:{session_id}", attempt_id=attempt_id
+ )
+ background = get_background_manager().for_scope(background_scope)
+
registry = await loop.run_in_executor(
_AGENT_EXECUTOR,
lambda: build_registry(
@@ -596,6 +605,8 @@ class SessionService:
event_callback=event_callback,
warn_callback=_mcp_collision_warn,
cancel_event=turn_cancel,
+ background_manager=background,
+ background_scope=background_scope,
),
)
@@ -608,6 +619,7 @@ class SessionService:
max_iterations=get_env_config().agent_tuning.vibe_trading_agent_max_iterations,
persistent_memory=pm,
cancel_event=turn_cancel,
+ background_manager=background,
)
self._active_loops[session_id] = agent
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 6dd78139a..860e1d8e7 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -662,11 +662,23 @@ def _run_worker_impl(
# ``load_skill`` with the allowlist baked in; an empty ``skills`` list
# means unrestricted, matching the prompt-side filter semantics
# (``_filter_skill_descriptions`` treats empty as include-all).
+ # Each worker owns its background tasks. Two workers running the same
+ # preset concurrently must never read or cancel each other's commands, and
+ # neither may see the tasks of the session that launched the swarm.
+ from src.tools.background_tools import BackgroundScope, get_background_manager
+
+ background_scope = BackgroundScope(
+ owner_id=f"swarm:{Path(run_dir).name}:{agent_id}:{task_id}",
+ attempt_id=task_id,
+ )
+ background = get_background_manager().for_scope(background_scope)
registry = build_swarm_registry(
agent_spec.tools,
agent_config=agent_config,
include_shell_tools=include_shell_tools,
skill_allowlist=agent_spec.skills or None,
+ background_manager=background,
+ background_scope=background_scope,
)
# 2. Build system prompt with filtered skills
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index e6e281cfc..89f89df14 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import importlib
import logging
import pkgutil
+import uuid
from collections.abc import Mapping
from collections import deque
from pathlib import Path
@@ -83,6 +84,8 @@ def build_registry(
warn_callback: Callable[[str], None] | None = None,
interactive: bool | None = None,
cancel_event: Any | None = None,
+ background_manager: Any | None = None,
+ background_scope: Any | None = None,
_mcp_server_tool_name_segments: Mapping[str, str] | None = None,
) -> ToolRegistry:
"""Build the tool registry via auto-discovery, optionally enriched with MCP tools.
@@ -106,7 +109,8 @@ def build_registry(
tool discovery. Pass ``None`` (default) to preserve existing
behavior with no MCP integration.
session_id: Optional current session id injected into local tools that
- persist per-session state.
+ persist per-session state. Also used as the background-task owner
+ when no explicit ``background_scope`` is given.
event_callback: Optional event callback injected into local tools that
mutate session-scoped state.
warn_callback: Optional callable invoked with operator-facing warning
@@ -119,11 +123,26 @@ def build_registry(
channel rather than blocking on a browser that cannot open
(SPEC Transport §4). ``None`` (default) auto-detects via
``sys.stdin.isatty()``.
+ background_manager: Shared background task table. Defaults to the
+ process-wide one.
+ background_scope: Who owns the background tasks this registry can
+ start. When omitted the scope is derived from ``session_id``, or is
+ private to this registry when there is no session either. The
+ resolved handle is exposed as ``registry.background`` so the host
+ can give the same one to ``AgentLoop`` and keep task results and
+ completion notifications inside one conversation.
Returns:
ToolRegistry containing all available local tools followed by any
successfully discovered MCP tools.
"""
+ from src.tools.background_tools import (
+ BackgroundScope,
+ BackgroundRunTool,
+ CancelBackgroundTool,
+ CheckBackgroundTool,
+ get_background_manager,
+ )
from src.tools.goal_tool import (
AddGoalEvidenceTool,
GetResearchGoalTool,
@@ -149,6 +168,16 @@ def build_registry(
}
classes = _discover_subclasses()
registry = ToolRegistry()
+
+ bg_scope = background_scope or (
+ BackgroundScope(owner_id=f"session:{session_id}")
+ if session_id
+ else BackgroundScope(owner_id=f"isolated:{uuid.uuid4().hex}")
+ )
+ bg = (background_manager or get_background_manager()).for_scope(bg_scope)
+ # The loop drains the same handle the tools write to, so a task's result
+ # reaches the conversation that started it and no other.
+ registry.background = bg
for module_name, reason in _DISCOVERY_FAILURES.items():
registry.record_import_failure(module_name, reason)
@@ -162,6 +191,8 @@ def build_registry(
continue
if cls is RememberTool and persistent_memory is not None:
registry.register(cls(memory=persistent_memory))
+ elif cls in (BackgroundRunTool, CheckBackgroundTool, CancelBackgroundTool):
+ registry.register(cls(background=bg))
elif cls in session_injected_classes:
registry.register(cls(default_session_id=session_id, event_callback=event_callback))
elif cls is SwarmTool:
@@ -288,6 +319,8 @@ def build_filtered_registry(
*,
include_shell_tools: bool = False,
skill_allowlist: list[str] | None = None,
+ background_manager: Any | None = None,
+ background_scope: Any | None = None,
) -> ToolRegistry:
"""Build a ToolRegistry with only specified tools.
@@ -302,11 +335,17 @@ def build_filtered_registry(
skill_allowlist: When not ``None``, the ``load_skill`` tool (if
whitelisted) is rebuilt to refuse skill names outside this list,
so a documented skill boundary is enforced at runtime.
+ background_manager: Shared background task table.
+ background_scope: Owner of the background tasks this registry starts.
Returns:
ToolRegistry containing only the requested tools.
"""
- full = build_registry(include_shell_tools=include_shell_tools)
+ full = build_registry(
+ include_shell_tools=include_shell_tools,
+ background_manager=background_manager,
+ background_scope=background_scope,
+ )
return _filter_registry(
full,
tool_names,
@@ -321,6 +360,8 @@ def build_swarm_registry(
agent_config: "AgentConfig | None" = None,
include_shell_tools: bool = False,
skill_allowlist: list[str] | None = None,
+ background_manager: Any | None = None,
+ background_scope: Any | None = None,
) -> ToolRegistry:
"""Build a per-worker registry that merges local + remote MCP tools.
@@ -346,6 +387,11 @@ def build_swarm_registry(
skill_allowlist: When not ``None``, the ``load_skill`` tool (if
whitelisted) is rebuilt to refuse skill names outside this list,
enforcing the per-worker ``skills:`` boundary at runtime.
+ background_manager: Shared background task table.
+ background_scope: Owner of the background tasks this worker starts.
+ Swarm workers should pass one scoped to their run and identity so
+ concurrent workers never see each other's tasks. Omitting it gives
+ the worker a private scope rather than a shared one.
Returns:
ToolRegistry containing the whitelist intersection of local tools
@@ -358,6 +404,8 @@ def build_swarm_registry(
full = build_registry(
agent_config=swarm_agent_config,
include_shell_tools=include_shell_tools,
+ background_manager=background_manager,
+ background_scope=background_scope,
_mcp_server_tool_name_segments=swarm_local_server_names,
)
return _filter_registry(
diff --git a/agent/src/tools/background_tools.py b/agent/src/tools/background_tools.py
index 5e5f85652..f720d63b2 100644
--- a/agent/src/tools/background_tools.py
+++ b/agent/src/tools/background_tools.py
@@ -9,6 +9,7 @@ import subprocess
import threading
import time
import uuid
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -21,6 +22,27 @@ _TERMINATION_GRACE_SECONDS = 2.0
_MAX_OUTPUT_CHARS = 50_000
+@dataclass(frozen=True)
+class BackgroundScope:
+ """Which conversation or worker owns a background task.
+
+ The host that builds the tool registry supplies this. It never appears in a
+ model-visible tool schema: a model must not be able to claim another
+ session's task, or read its output, by naming an owner.
+
+ Ownership is by ``owner_id`` alone. ``attempt_id`` records which attempt
+ started the task so later bookkeeping can attribute it; a later attempt of
+ the same owner still sees tasks started by the earlier one.
+ """
+
+ owner_id: str
+ attempt_id: Optional[str] = None
+
+ def __post_init__(self) -> None:
+ if not str(self.owner_id).strip():
+ raise ValueError("a background scope must have a non-empty owner_id")
+
+
def _start_process(command: str) -> subprocess.Popen[str]:
"""Start a shell command in a process group that can be stopped as a unit."""
kwargs: dict[str, Any] = {
@@ -106,12 +128,37 @@ def _combined_output(stdout: str | None, stderr: str | None) -> str:
class BackgroundManager:
- """Background thread execution + notification queue."""
+ """Background thread execution + notification queue, addressed by owner.
+
+ One instance is a *handle*: it carries the scope its methods read and write
+ under. :meth:`for_scope` hands out another handle over the same task table,
+ so a session and its later attempts share their tasks while a different
+ session sees none of them.
+ """
- def __init__(self) -> None:
+ def __init__(self, scope: Optional[BackgroundScope] = None) -> None:
self.tasks: Dict[str, dict] = {}
- self._notifications: List[dict] = []
+ # (owner_id, payload). Kept as pairs so the payload shape consumers and
+ # existing tests see stays exactly what it was; routing is internal.
+ self._notifications: List[tuple[str, dict]] = []
self._lock = threading.Lock()
+ self._scope = scope or BackgroundScope(owner_id=f"isolated:{uuid.uuid4().hex}")
+
+ @property
+ def scope(self) -> BackgroundScope:
+ """The owner this handle reads and writes under."""
+ return self._scope
+
+ def for_scope(self, scope: BackgroundScope) -> "BackgroundManager":
+ """Return a handle over the same task table bound to another owner."""
+ other = BackgroundManager(scope=scope)
+ other.tasks = self.tasks
+ other._notifications = self._notifications
+ other._lock = self._lock
+ return other
+
+ def _owns(self, task: dict) -> bool:
+ return task.get("owner_id") == self._scope.owner_id
def run(self, command: str) -> str:
"""Start a background task and return its task_id.
@@ -140,6 +187,8 @@ class BackgroundManager:
"process": None,
"cancel_requested": False,
"started_at": started_at,
+ "owner_id": self._scope.owner_id,
+ "attempt_id": self._scope.attempt_id,
}
threading.Thread(target=self._execute, args=(task_id, command), daemon=True).start()
return json.dumps({"status": "ok", "task_id": task_id, "message": f"Started: {command[:80]}"})
@@ -203,11 +252,14 @@ class BackgroundManager:
max(0.0, time.monotonic() - started_at),
3,
)
- self._notifications.append({
- "task_id": task_id, "status": status,
- "command": command[:80], "result": (output or "")[:500],
- "exit_code": exit_code,
- })
+ self._notifications.append((
+ task["owner_id"],
+ {
+ "task_id": task_id, "status": status,
+ "command": command[:80], "result": (output or "")[:500],
+ "exit_code": exit_code,
+ },
+ ))
def cancel(self, task_id: str) -> str:
"""Cancel one task by its tracked process group.
@@ -220,7 +272,9 @@ class BackgroundManager:
"""
with self._lock:
task = self.tasks.get(task_id)
- if task is None:
+ # A task owned by another session is reported exactly like a task id
+ # that never existed, so probing cannot confirm one exists.
+ if task is None or not self._owns(task):
return json.dumps({
"status": "error",
"error": f"Unknown task {task_id}",
@@ -267,11 +321,12 @@ class BackgroundManager:
with self._lock:
if task_id:
t = self.tasks.get(task_id)
- task = dict(t) if t is not None else None
+ task = dict(t) if t is not None and self._owns(t) else None
else:
task_summaries = [
(tid, t["status"], t["command"])
for tid, t in self.tasks.items()
+ if self._owns(t)
]
if task_id:
@@ -285,6 +340,7 @@ class BackgroundManager:
"command": t["command"][:60],
"result": result or "(running)",
"exit_code": t.get("exit_code"),
+ "attempt_id": t.get("attempt_id"),
}
started_at = t.get("started_at")
if isinstance(started_at, (int, float)):
@@ -311,18 +367,32 @@ class BackgroundManager:
return "\n".join(lines) if lines else "No background tasks."
def drain_notifications(self) -> List[dict]:
+ """Return this owner's queued notifications, oldest first.
+
+ Notifications belonging to other owners stay queued for them; draining
+ one session can never consume another's result.
+ """
with self._lock:
- notifs = list(self._notifications)
- self._notifications.clear()
- return notifs
+ mine = [payload for owner, payload in self._notifications
+ if owner == self._scope.owner_id]
+ self._notifications = [(owner, payload) for owner, payload in self._notifications
+ if owner != self._scope.owner_id]
+ return mine
_BG = BackgroundManager()
def get_background_manager() -> BackgroundManager:
- """Return the global BackgroundManager singleton."""
- return _BG
+ """Return an unowned handle over the process-wide task table.
+
+ Every call binds its own isolated scope, so two callers each get a private
+ view and cannot see, read or cancel each other's tasks. A host that wants a
+ session or worker to receive its own completion notifications must build a
+ scoped handle with :meth:`BackgroundManager.for_scope` and hand the same
+ object to both the tool registry and ``AgentLoop``.
+ """
+ return _BG.for_scope(BackgroundScope(owner_id=f"isolated:{uuid.uuid4().hex}"))
class BackgroundRunTool(BaseTool):
@@ -338,8 +408,11 @@ class BackgroundRunTool(BaseTool):
}, "required": ["command"]}
is_readonly = False
+ def __init__(self, background: Optional[BackgroundManager] = None) -> None:
+ self.background = background if background is not None else get_background_manager()
+
def execute(self, **kw: Any) -> str:
- return _BG.run(kw["command"])
+ return self.background.run(kw["command"])
class CheckBackgroundTool(BaseTool):
@@ -354,8 +427,11 @@ class CheckBackgroundTool(BaseTool):
}, "required": []}
repeatable = True
+ def __init__(self, background: Optional[BackgroundManager] = None) -> None:
+ self.background = background if background is not None else get_background_manager()
+
def execute(self, **kw: Any) -> str:
- return _BG.check(kw.get("task_id"))
+ return self.background.check(kw.get("task_id"))
class CancelBackgroundTool(BaseTool):
@@ -378,5 +454,8 @@ class CancelBackgroundTool(BaseTool):
}
is_readonly = False
+ def __init__(self, background: Optional[BackgroundManager] = None) -> None:
+ self.background = background if background is not None else get_background_manager()
+
def execute(self, **kw: Any) -> str:
- return _BG.cancel(kw["task_id"])
+ return self.background.cancel(kw["task_id"])
diff --git a/agent/tests/test_agent_loop_no_assistant_prefill.py b/agent/tests/test_agent_loop_no_assistant_prefill.py
index 74797b574..21f806db7 100644
--- a/agent/tests/test_agent_loop_no_assistant_prefill.py
+++ b/agent/tests/test_agent_loop_no_assistant_prefill.py
@@ -12,9 +12,6 @@ from __future__ import annotations
from pathlib import Path
from typing import Any
-import pytest
-
-import src.agent.loop as loop_mod
from src.agent.loop import AgentLoop
from src.agent.trace import TraceWriter
@@ -68,7 +65,12 @@ class _StubLLM:
return self._Response()
-def _build_agent(llm: Any, max_iter: int = 3, tmp_run_dir: Path | None = None) -> AgentLoop:
+def _build_agent(
+ llm: Any,
+ max_iter: int = 3,
+ tmp_run_dir: Path | None = None,
+ background_manager: Any = None,
+) -> AgentLoop:
from src.tools import build_registry
from src.memory.persistent import PersistentMemory
@@ -79,6 +81,7 @@ def _build_agent(llm: Any, max_iter: int = 3, tmp_run_dir: Path | None = None) -
event_callback=None,
max_iterations=max_iter,
persistent_memory=pm,
+ background_manager=background_manager,
)
if tmp_run_dir is not None:
tmp_run_dir.mkdir(parents=True, exist_ok=True)
@@ -101,7 +104,6 @@ def test_agent_run_messages_never_end_with_assistant(tmp_path: Path) -> None:
def test_background_notifications_are_reintroduced_as_user_messages(
tmp_path: Path,
- monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Background notifications used to append a trailing assistant ack."""
@@ -116,8 +118,12 @@ def test_background_notifications_are_reintroduced_as_user_messages(
]
llm = _StubLLM()
- monkeypatch.setattr(loop_mod, "get_background_manager", lambda: _BackgroundManager())
- agent = _build_agent(llm, max_iter=1, tmp_run_dir=tmp_path / "run")
+ agent = _build_agent(
+ llm,
+ max_iter=1,
+ tmp_run_dir=tmp_path / "run",
+ background_manager=_BackgroundManager(),
+ )
result = agent.run("Check background work")
diff --git a/agent/tests/test_background_scope_isolation.py b/agent/tests/test_background_scope_isolation.py
new file mode 100644
index 000000000..af973e554
--- /dev/null
+++ b/agent/tests/test_background_scope_isolation.py
@@ -0,0 +1,260 @@
+"""Background tasks must stay inside the session or worker that started them.
+
+A background task's result and its completion notification are runtime state
+belonging to one conversation. They live in process-wide tables, so a second
+session that reaches its next iteration first drains the first one's
+notification and can list, read or cancel its tasks. These tests pin the
+ownership boundary rather than any particular storage layout.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import time
+
+import pytest
+
+from src.tools import build_registry
+from src.tools.background_tools import BackgroundManager, get_background_manager
+
+
+def _echo_command(text: str) -> str:
+ return f'"{sys.executable}" -c "print(\'{text}\')"'
+
+
+def _run_to_completion(
+ manager: BackgroundManager, command: str, *, timeout: float = 15.0
+) -> str:
+ payload = json.loads(manager.run(command))
+ assert payload["status"] == "ok", payload
+ task_id = payload["task_id"]
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ status = json.loads(manager.check(task_id))["status"]
+ if status not in {"running", "cancelling"}:
+ return task_id
+ time.sleep(0.01)
+ raise AssertionError(f"background task {task_id} did not reach a terminal state")
+
+
+def _listed_task_ids(manager: BackgroundManager) -> list[str]:
+ listing = manager.check()
+ if listing == "No background tasks.":
+ return []
+ return [line.split(":", 1)[0] for line in listing.splitlines() if line]
+
+
+class TestTwoConcurrentSessions:
+ """The bug itself, expressed with the handle a host is given today."""
+
+ def test_second_session_cannot_drain_the_first_ones_notification(self) -> None:
+ session_a = get_background_manager()
+ session_b = get_background_manager()
+
+ _run_to_completion(session_a, _echo_command("belongs-to-a"))
+
+ assert session_b.drain_notifications() == []
+ assert [n["result"] for n in session_a.drain_notifications()] == [
+ "belongs-to-a"
+ ]
+
+ def test_second_session_cannot_list_the_first_ones_tasks(self) -> None:
+ session_a = get_background_manager()
+ session_b = get_background_manager()
+
+ task_id = _run_to_completion(session_a, _echo_command("private"))
+
+ assert task_id not in _listed_task_ids(session_b)
+
+ def test_second_session_cannot_cancel_the_first_ones_task(self) -> None:
+ session_a = get_background_manager()
+ session_b = get_background_manager()
+ task_id = "still-running"
+
+ session_a.tasks[task_id] = {
+ "status": "running",
+ "result": None,
+ "command": "python slow.py",
+ "exit_code": None,
+ "process": None,
+ "cancel_requested": False,
+ "started_at": time.monotonic(),
+ "owner_id": session_a.scope.owner_id,
+ "attempt_id": session_a.scope.attempt_id,
+ }
+
+ result = json.loads(session_b.cancel(task_id))
+ assert result == {"status": "error", "error": f"Unknown task {task_id}"}
+ assert session_a.tasks[task_id]["status"] == "running"
+ assert session_a.tasks[task_id]["cancel_requested"] is False
+
+ def test_second_session_cannot_read_the_first_ones_result(self) -> None:
+ session_a = get_background_manager()
+ session_b = get_background_manager()
+
+ task_id = _run_to_completion(session_a, _echo_command("private-result"))
+
+ foreign = json.loads(session_b.check(task_id))
+ assert foreign == {"status": "error", "error": f"Unknown task {task_id}"}
+ assert "private-result" not in json.dumps(foreign)
+
+
+class TestOwnerIsolation:
+ def test_completion_notification_reaches_only_its_own_owner(self) -> None:
+ from src.tools.background_tools import BackgroundScope
+
+ root = BackgroundManager(scope=BackgroundScope(owner_id="session-a"))
+ other = root.for_scope(BackgroundScope(owner_id="session-b"))
+
+ _run_to_completion(root, _echo_command("alice-output"))
+
+ assert [n["result"] for n in root.drain_notifications()] == ["alice-output"]
+ assert other.drain_notifications() == []
+
+ def test_owner_does_not_see_another_owners_task_listing(self) -> None:
+ from src.tools.background_tools import BackgroundScope
+
+ root = BackgroundManager(scope=BackgroundScope(owner_id="session-a"))
+ other = root.for_scope(BackgroundScope(owner_id="session-b"))
+
+ mine = _run_to_completion(root, _echo_command("a"))
+ theirs = _run_to_completion(other, _echo_command("b"))
+
+ assert mine != theirs
+ assert set(_listed_task_ids(root)) == {mine}
+ assert set(_listed_task_ids(other)) == {theirs}
+
+ def test_later_attempt_of_same_owner_reads_the_earlier_task(self) -> None:
+ from src.tools.background_tools import BackgroundScope
+
+ first = BackgroundScope(owner_id="session-a", attempt_id="attempt-1")
+ second = BackgroundScope(owner_id="session-a", attempt_id="attempt-2")
+ root = BackgroundManager(scope=first)
+ later = root.for_scope(second)
+
+ task_id = _run_to_completion(root, _echo_command("carried-over"))
+
+ record = json.loads(later.check(task_id))
+ assert record["status"] == "completed"
+ assert record["attempt_id"] == "attempt-1"
+ assert len(later.drain_notifications()) == 1
+
+ def test_notification_is_delivered_once_across_repeated_drains(self) -> None:
+ from src.tools.background_tools import BackgroundScope
+
+ manager = BackgroundManager(scope=BackgroundScope(owner_id="session-a"))
+
+ _run_to_completion(manager, _echo_command("once"))
+
+ assert len(manager.drain_notifications()) == 1
+ assert manager.drain_notifications() == []
+
+
+class TestRegistryBinding:
+ def test_scope_is_absent_from_the_model_visible_tool_schema(self) -> None:
+ registry = build_registry(include_shell_tools=True)
+
+ for name in ("background_run", "check_background", "cancel_background"):
+ tool = registry.get(name)
+ assert tool is not None, name
+ allowed = set(tool.parameters.get("properties", {}))
+ assert allowed <= {"command", "task_id"}, (name, allowed)
+ required = set(tool.parameters.get("required", []))
+ assert not (required & {"owner_id", "session_id", "attempt_id"}), name
+
+ def test_registry_tools_bind_the_scoped_handle_the_host_supplied(self) -> None:
+ from src.tools.background_tools import BackgroundScope
+
+ scope = BackgroundScope(owner_id="session-wired", attempt_id="attempt-1")
+ host_handle = BackgroundManager(scope=scope)
+
+ registry = build_registry(
+ include_shell_tools=True,
+ background_manager=host_handle,
+ background_scope=scope,
+ )
+
+ run_tool = registry.get("background_run")
+ assert run_tool is not None
+ assert run_tool.background.scope == scope
+ assert run_tool.background is registry.get("check_background").background
+
+ def test_registry_without_an_explicit_scope_is_still_owner_scoped(self) -> None:
+ first = build_registry(include_shell_tools=True)
+ second = build_registry(include_shell_tools=True)
+
+ first_scope = first.get("background_run").background.scope
+ second_scope = second.get("background_run").background.scope
+
+ assert first_scope != second_scope
+ assert first_scope.owner_id.startswith("isolated:")
+
+ def test_session_id_becomes_the_owner_when_no_scope_is_given(self) -> None:
+ registry = build_registry(session_id="session-xyz", include_shell_tools=True)
+
+ scope = registry.get("background_run").background.scope
+ assert scope.owner_id == "session:session-xyz"
+
+ def test_agent_loop_drains_the_same_handle_the_tools_write_to(self) -> None:
+ from types import SimpleNamespace
+
+ from src.agent.loop import AgentLoop
+ from src.tools.background_tools import BackgroundScope
+
+ scope = BackgroundScope(owner_id="session-wired", attempt_id="attempt-1")
+ handle = BackgroundManager(scope=scope)
+ registry = build_registry(
+ include_shell_tools=True,
+ background_manager=handle,
+ background_scope=scope,
+ )
+
+ task_id = _run_to_completion(
+ registry.get("background_run").background, _echo_command("wired")
+ )
+
+ loop = AgentLoop(registry=registry, llm=SimpleNamespace(), max_iterations=1)
+
+ # The loop drains exactly the handle the tool wrote to, so the result
+ # reaches this conversation and not another one.
+ assert loop._background_manager is registry.background
+ assert (
+ json.loads(loop._background_manager.check(task_id))["status"] == "completed"
+ )
+ assert [
+ n["result"] for n in loop._background_manager.drain_notifications()
+ ] == ["wired"]
+ stranger = BackgroundManager().for_scope(BackgroundScope(owner_id="stranger"))
+ assert stranger.drain_notifications() == []
+
+ def test_shell_tool_policy_is_unchanged_by_scoping(self) -> None:
+ registry = build_registry()
+
+ # Only the two process-control tools sit behind the shell opt-in.
+ assert registry.get("background_run") is None
+ assert registry.get("cancel_background") is None
+ assert registry.get("check_background") is not None
+
+ enabled = build_registry(include_shell_tools=True)
+ for name in ("background_run", "check_background", "cancel_background"):
+ assert enabled.get(name) is not None, name
+
+
+class TestScopeContract:
+ def test_scope_rejects_an_empty_owner(self) -> None:
+ from src.tools.background_tools import BackgroundScope
+
+ with pytest.raises(ValueError):
+ BackgroundScope(owner_id=" ")
+
+ def test_unowned_handles_are_not_a_shared_catch_all(self) -> None:
+ from src.tools.background_tools import BackgroundScope
+
+ first = get_background_manager()
+ second = get_background_manager()
+
+ assert first.scope != second.scope
+ assert first.scope.owner_id.startswith("isolated:")
+ assert second.scope.owner_id.startswith("isolated:")
+ assert BackgroundScope(owner_id="explicit") != first.scope
diff --git a/agent/tests/test_background_tools.py b/agent/tests/test_background_tools.py
index af598c403..06b76a1e1 100644
--- a/agent/tests/test_background_tools.py
+++ b/agent/tests/test_background_tools.py
@@ -24,6 +24,8 @@ def _execute(manager: BackgroundManager, task_id: str, command: str) -> dict:
"result": None,
"command": command,
"exit_code": None,
+ "owner_id": manager.scope.owner_id,
+ "attempt_id": manager.scope.attempt_id,
}
manager._execute(task_id, command)
return manager.tasks[task_id]
@@ -75,6 +77,8 @@ def test_check_running_task_reports_timeout_context(
"process": None,
"cancel_requested": False,
"started_at": 100.0,
+ "owner_id": manager.scope.owner_id,
+ "attempt_id": manager.scope.attempt_id,
}
monkeypatch.setattr(background_tools.time, "monotonic", lambda: 297.0)
@@ -105,6 +109,8 @@ def test_cancel_targets_only_the_tracked_process(
"exit_code": None,
"process": target,
"cancel_requested": False,
+ "owner_id": manager.scope.owner_id,
+ "attempt_id": manager.scope.attempt_id,
},
"sibling": {
"status": "running",
@@ -113,6 +119,8 @@ def test_cancel_targets_only_the_tracked_process(
"exit_code": None,
"process": sibling,
"cancel_requested": False,
+ "owner_id": manager.scope.owner_id,
+ "attempt_id": manager.scope.attempt_id,
},
}
stopped: list[object] = []
@@ -149,6 +157,8 @@ def test_cancel_completed_task_does_not_touch_process(
"exit_code": 0,
"process": process,
"cancel_requested": False,
+ "owner_id": manager.scope.owner_id,
+ "attempt_id": manager.scope.attempt_id,
}
stop = MagicMock()
monkeypatch.setattr(background_tools, "_force_stop_process_tree", stop)
diff --git a/agent/tests/test_session_service_mcp.py b/agent/tests/test_session_service_mcp.py
index ff684563c..798b27239 100644
--- a/agent/tests/test_session_service_mcp.py
+++ b/agent/tests/test_session_service_mcp.py
@@ -23,7 +23,17 @@ class _DummyIndex:
class _DummyAgentLoop:
- def __init__(self, *, registry, llm, event_callback, max_iterations, persistent_memory, cancel_event=None) -> None:
+ def __init__(
+ self,
+ *,
+ registry,
+ llm,
+ event_callback,
+ max_iterations,
+ persistent_memory,
+ cancel_event=None,
+ background_manager=None,
+ ) -> None:
del registry, llm, event_callback, max_iterations, persistent_memory
def run(self, *, user_message: str, history, session_id: str) -> dict[str, str]:
diff --git a/agent/tests/test_session_tool_trail.py b/agent/tests/test_session_tool_trail.py
index 4af23b276..85436ca62 100644
--- a/agent/tests/test_session_tool_trail.py
+++ b/agent/tests/test_session_tool_trail.py
@@ -145,6 +145,7 @@ def test_run_with_agent_consolidates_tool_events_by_call_id(
max_iterations,
persistent_memory,
cancel_event=None,
+ background_manager=None,
) -> None:
del registry, llm, max_iterations, persistent_memory, cancel_event
self._event_callback = event_callback
diff --git a/agent/tests/test_swarm_m4_e2e.py b/agent/tests/test_swarm_m4_e2e.py
index 4b4782cd0..25a47c59a 100644
--- a/agent/tests/test_swarm_m4_e2e.py
+++ b/agent/tests/test_swarm_m4_e2e.py
@@ -274,7 +274,7 @@ def test_run_worker_uses_remote_mcp_tool_and_report_cites_canned_data(
with (
patch(
"src.swarm.worker.build_swarm_registry",
- wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None: _registry_with_remote(
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None, background_manager=None, background_scope=None: _registry_with_remote(
tool_names,
remote_tools,
include_shell_tools=include_shell_tools,
@@ -358,7 +358,7 @@ def test_two_agents_with_distinct_servers_only_see_their_own_remote_tools(
with (
patch(
"src.swarm.worker.build_swarm_registry",
- wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None: _registry_with_remote(
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None, background_manager=None, background_scope=None: _registry_with_remote(
tool_names, remote_tools, include_shell_tools=include_shell_tools,
),
),
@@ -453,7 +453,7 @@ def test_tool_call_events_carry_mcp_metadata_and_redact_sensitive_arguments(
with (
patch(
"src.swarm.worker.build_swarm_registry",
- wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None: _registry_with_remote(
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None, background_manager=None, background_scope=None: _registry_with_remote(
tool_names, remote_tools, include_shell_tools=include_shell_tools,
),
),
@@ -543,7 +543,7 @@ def test_remote_tool_transport_failure_does_not_crash_worker(tmp_path: Path) ->
with (
patch(
"src.swarm.worker.build_swarm_registry",
- wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None: _registry_with_remote(
+ wraps=lambda tool_names, *, agent_config=None, include_shell_tools=False, skill_allowlist=None, background_manager=None, background_scope=None: _registry_with_remote(
tool_names, remote_tools, include_shell_tools=include_shell_tools,
),
),