From ea68b36218ccc722d00bef75d4e414106706deb8 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sun, 15 Nov 2026 03:57:11 +0900 Subject: [PATCH 1/6] scaffold new Agent Apps from one blueprint before the build starts instead of refering to kanban agent app --- app/agent_app/framework_cli.py | 17 +- app/agent_app/framework_host.py | 40 ++++- app/agent_app/wizard.py | 11 +- .../agentApps/useFrameworkCreation.ts | 2 +- tests/test_agent_app_new_app_scaffold.py | 160 ++++++++++++++++++ 5 files changed, 217 insertions(+), 13 deletions(-) create mode 100644 tests/test_agent_app_new_app_scaffold.py diff --git a/app/agent_app/framework_cli.py b/app/agent_app/framework_cli.py index 0097568a..2ccd765b 100644 --- a/app/agent_app/framework_cli.py +++ b/app/agent_app/framework_cli.py @@ -86,7 +86,9 @@ def __init__(self, package_dir: Path, *, home: Path): self.package_dir = Path(package_dir).resolve() self.home = Path(home).resolve() - def _prepare(self, surface: Surface, env_extra: Mapping[str, str]): + def _prepare( + self, surface: Surface, env_extra: Mapping[str, str], new_app: bool = False + ): entry = self.package_dir / "bin" / f"{surface}.js" if not entry.is_file(): raise FrameworkCLIUnavailable( @@ -117,12 +119,16 @@ def _prepare(self, surface: Surface, env_extra: Mapping[str, str]): if not ( env_extra.get("A2APP_TOOLKITS_DIR") or env.get("A2APP_TOOLKITS_DIR", "") ).strip(): - if not toolkits: + # The bundled Kanban's toolkit only runs apps already built on it. + # A new app starts from the framework's own blueprints, so listing + # and scaffolding never see it. + if not toolkits and not new_app: from app import paths from app.provision.default_agent_app import bundled_toolkits toolkits = str(bundled_toolkits(paths.CODE_ROOT, paths.STATE_ROOT)) - env["A2APP_TOOLKITS_DIR"] = toolkits + if toolkits: + env["A2APP_TOOLKITS_DIR"] = toolkits # A delegated run must not inherit another run's ambient credential. env.pop("A2APP_TOKEN", None) env.update(env_extra) @@ -170,8 +176,11 @@ async def run( extra["A2APP_MARKETPLACE_REF"] = await asyncio.to_thread( _import_default_ref, argv[source_index] ) + new_app = surface == "agent-app" and ( + argv[:1] == ["blueprints"] or argv[1:2] == ["scaffold"] + ) # Resolution can probe Node synchronously; keep it off the UI event loop. - command, env = await asyncio.to_thread(self._prepare, surface, extra) + command, env = await asyncio.to_thread(self._prepare, surface, extra, new_app) flags = ( {"creationflags": subprocess.CREATE_NO_WINDOW} if sys.platform == "win32" diff --git a/app/agent_app/framework_host.py b/app/agent_app/framework_host.py index 91b60a7e..ebfcb288 100644 --- a/app/agent_app/framework_host.py +++ b/app/agent_app/framework_host.py @@ -16,6 +16,10 @@ _host = None +# Every new app starts from this complete upstream starter (PocketBase + React +# View, spec skeletons, plan). The builder never chooses among toolkits. +NEW_APP_BLUEPRINT = "blueprint-pocketbase-react" + async def no_ui_change(): """The framework host also runs without a browser client.""" @@ -523,6 +527,8 @@ async def workflow( ) if new_app: self.store.put("creation", session.id, {"path": path, **(creation or {}), "building": True}) + if activity == "create": + app_id = await self._scaffold_new_app(session.id, path, creation) from app.triggers.service import TriggerSpec from app.triggers.sources import TriggerSource @@ -530,9 +536,11 @@ async def workflow( f"Use the unchanged framework-{activities[activity]} skill.\n{request}\n" ) if activity == "create": - prompt += "The destination below is allocated but DOES NOT EXIST yet. Discover the blueprints and scaffold it with the existing CLI before following the creator workflow.\n" - if creation: - prompt += "CraftBot binds the selected name and access mode to this destination's scaffold command. Use agent_app_command for scaffolding; do not replace the user's selections.\n" + prompt += ( + f"CraftBot already scaffolded this app from {NEW_APP_BLUEPRINT} with the user's " + "selected name and access mode. Do not scaffold again or choose another " + "blueprint. Read reference/blueprint.md first, then follow the creator workflow.\n" + ) elif new_app: prompt += "The destination below is allocated but DOES NOT EXIST yet. Use it for adoption/conversion (or --into when installing) so this app keeps its current side chat. Follow the importer skill to choose the appropriate route with the user.\n" if path: @@ -558,6 +566,32 @@ async def workflow( await self.changed() return {"sessionId": session.id, "path": path} + async def _scaffold_new_app(self, session_id, path, creation): + """Scaffold a new app before its build conversation starts. + + The creation conversation is already recorded for this folder, so the + upstream identity binds to it as soon as the registry knows the app. + """ + args = [path, "scaffold", "--blueprint", NEW_APP_BLUEPRINT] + if creation: + args += ["--name", creation["name"], "--auth-mode", creation["authMode"]] + error = "The new app could not be scaffolded." + try: + result = await command("agent-app", args) + app_id = (result.get("data") or {}).get("id") + if result["status"] == "success" and app_id: + return app_id + error = (result.get("stderr") or "").strip() or error + except Exception as exc: + error = str(exc) or error + # Nothing was built: remove the empty build conversation rather than + # leave a pending app in the sidebar that can never finish. + self.store.delete("creation", session_id) + self.store.delete("conversation", session_id) + await self.agent.delete_session(session_id) + await self.changed() + raise RuntimeError(error) + def scaffold_arguments(self, session_id, args): """Carry explicit form choices into the unchanged CLI's scaffold flags.""" creation = self.store.get("creation", session_id) if session_id else None diff --git a/app/agent_app/wizard.py b/app/agent_app/wizard.py index 00e3881b..af0b0671 100644 --- a/app/agent_app/wizard.py +++ b/app/agent_app/wizard.py @@ -226,8 +226,9 @@ def _render_config(config: Dict[str, Any], image_notes: List[str]) -> str: # never drift apart. Describes the framework host contract. _PLATFORM_REALITY = """PLATFORM REALITY: - Apps run locally inside CraftBot's embedded app view, using the existing -Agent-App framework. Discover its supported blueprints and capabilities; -do not assume a particular database, UI stack, port layout or toolkit. +Agent-App framework. New apps are built on its PocketBase + React (Vite) +blueprint; do not plan for another database, UI stack or toolkit, and do not +assume a port layout. - Use the app's declared A2App operations and task contract. Apps can request work from CraftBot when the owner enables Allow requests to CraftBot. CraftBot routes accepted requests into the app's existing conversation. @@ -829,9 +830,9 @@ async def start_framework_build(host, config, requirements, attachments=()): return {"sessionId": job["sessionId"], "path": job["result"]["dir"]} return await host.workflow("modify", requirements, job["result"]["dir"], job["result"]["id"]) request = ( - "Build from the accepted requirements below. After scaffolding, save them " - "in reference/requirements.md for independent verification. Use the framework's " - "supported blueprint and styling options. Copy the staged references into the app.\n" + "Build from the accepted requirements below. Save them in " + "reference/requirements.md for independent verification. Style the app with " + "the blueprint's design system. Copy the staged references into the app.\n" + json.dumps({"preferences": config, "attachments": list(attachments)}, ensure_ascii=False) + "\n\n" + requirements ) diff --git a/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts b/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts index eeae8c31..426442c4 100644 --- a/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts +++ b/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts @@ -79,7 +79,7 @@ export function useFrameworkCreation(onClose: () => void) { if (!response.ok || !result.path) throw new Error(result.error || `Could not upload ${file.name}`) references.push({ name: file.name, path: result.path, kind: file === icon ? 'icon' : 'reference' }) } - await workflow('create', `Create an app using these preferences. Clarify any missing requirements in this conversation. Use the framework's supported blueprint and styling options to match the requested design. Copy staged references into the app's reference directory.\n${JSON.stringify({ ...config, attachments: references }, null, 2)}`, { name: config.name, authMode: config.authMode, uiTheme: config.uiTheme }) + await workflow('create', `Create an app using these preferences. Clarify any missing requirements in this conversation. Style it with the blueprint's design system to match the requested design. Copy staged references into the app's reference directory.\n${JSON.stringify({ ...config, attachments: references }, null, 2)}`, { name: config.name, authMode: config.authMode, uiTheme: config.uiTheme }) } return { install, create } } diff --git a/tests/test_agent_app_new_app_scaffold.py b/tests/test_agent_app_new_app_scaffold.py new file mode 100644 index 00000000..68ac34b1 --- /dev/null +++ b/tests/test_agent_app_new_app_scaffold.py @@ -0,0 +1,160 @@ +"""New apps start from one upstream blueprint, never the bundled Kanban's toolkit.""" + +import asyncio +import sys +from types import SimpleNamespace + +import pytest + +from app.agent_app import framework_host +from app.agent_app.framework_store import HostStore +from app.provision import default_agent_app as default + + +def _cli(tmp_path, monkeypatch): + from app import node_runtime, paths + from app.agent_app.framework_cli import AgentAppCLI + + (tmp_path / "bin").mkdir() + (tmp_path / "bin/agent-app.js").touch() + monkeypatch.setattr(paths, "STATE_ROOT", tmp_path / "state") + monkeypatch.setattr( + node_runtime, + "resolve", + lambda: SimpleNamespace(node=sys.executable, version="v24.0.0"), + ) + monkeypatch.setattr(node_runtime, "child_env", lambda: {}) + monkeypatch.setattr("app.config.get_framework_toolkits_dir", lambda: None) + return AgentAppCLI(tmp_path, home=tmp_path / "registry") + + +def test_listing_and_scaffolding_never_see_the_bundled_kanban_toolkit( + tmp_path, monkeypatch +): + cli = _cli(tmp_path, monkeypatch) + + def unexpected(*args, **kwargs): + pytest.fail("A new app must not be offered the bundled Kanban toolkit") + + monkeypatch.setattr(default, "bundled_toolkits", unexpected) + assert "A2APP_TOOLKITS_DIR" not in cli._prepare("agent-app", {}, True)[1] + # A toolkit folder the user configured is still offered. + monkeypatch.setattr("app.config.get_framework_toolkits_dir", lambda: "configured") + assert cli._prepare("agent-app", {}, True)[1]["A2APP_TOOLKITS_DIR"] == "configured" + + seen = [] + + class Stop(Exception): + pass + + def prepare(surface, extra, new_app=False): + seen.append(new_app) + raise Stop + + monkeypatch.setattr(cli, "_prepare", prepare) + app = str(tmp_path / "app") + for args in ( + ["blueprints"], + [app, "scaffold", "--blueprint", "blueprint-pocketbase-react"], + # Apps already built on the toolkit still resolve it. + [app, "validate"], + [app, "promote"], + ["install", "kanban-board"], + ): + with pytest.raises(Stop): + asyncio.run(cli.run("agent-app", args, cwd=tmp_path)) + assert seen == [True, True, False, False, False] + + +class _Agent: + def __init__(self): + self.calls = [] + self.deleted = [] + self.session_manager = SimpleNamespace(create_session=self._create) + self.trigger_service = SimpleNamespace(emit=self._emit) + + def _create(self, **kwargs): + self.calls.append(("session", kwargs)) + return SimpleNamespace(id="build-session") + + async def _emit(self, spec): + self.calls.append(("trigger", spec.description)) + + async def delete_session(self, session_id): + self.deleted.append(session_id) + return True + + +def _host(tmp_path, monkeypatch, result): + monkeypatch.setattr(framework_host, "_host", None) + monkeypatch.setattr( + framework_host.framework, + "configured_cli", + lambda: SimpleNamespace(home=tmp_path / "home"), + ) + agent = _Agent() + + async def command(surface, args): + agent.calls.append(("command", surface, args)) + return result + + monkeypatch.setattr(framework_host, "command", command) + host = framework_host.FrameworkHost(agent, store=HostStore(tmp_path / "host.sqlite3")) + return host, agent + + +def test_create_scaffolds_the_starter_before_the_builder_runs(tmp_path, monkeypatch): + host, agent = _host( + tmp_path, + monkeypatch, + {"status": "success", "data": {"id": "1e60ba80f83f"}, "stderr": ""}, + ) + result = asyncio.run( + host.workflow( + "create", + "Build a clock", + creation={"name": "Clock app", "authMode": "multi-user"}, + ) + ) + + kinds = [call[0] for call in agent.calls] + assert kinds == ["session", "command", "trigger"] + _, surface, args = agent.calls[1] + assert surface == "agent-app" + assert args == [ + result["path"], + "scaffold", + "--blueprint", + "blueprint-pocketbase-react", + "--name", + "Clock app", + "--auth-mode", + "multi-user", + ] + prompt = agent.calls[2][1] + assert "already scaffolded this app from blueprint-pocketbase-react" in prompt + assert "Do not scaffold again or choose another blueprint" in prompt + assert "1e60ba80f83f" in prompt + assert "Discover the blueprints" not in prompt + assert host.store.get("creation", "build-session")["building"] is True + + +def test_failed_scaffold_removes_the_empty_build_conversation(tmp_path, monkeypatch): + host, agent = _host( + tmp_path, + monkeypatch, + {"status": "error", "data": None, "stderr": "scaffold refused\n"}, + ) + with pytest.raises(RuntimeError, match="scaffold refused"): + asyncio.run( + host.workflow( + "create", + "Build a clock", + creation={"name": "Clock app", "authMode": "none"}, + ) + ) + + assert "trigger" not in [call[0] for call in agent.calls] + assert agent.deleted == ["build-session"] + assert host.store.get("creation", "build-session") is None + assert host.store.get("conversation", "build-session") is None From 1d5915061e088d9ff09fb91c3d6ab61390cbb1b9 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sun, 15 Nov 2026 04:33:49 +0900 Subject: [PATCH 2/6] let the agent choose the blueprint. bind walk-verify to the code fingerprint --- app/agent_app/framework_host.py | 46 ++------- app/agent_app/wizard.py | 11 +-- .../agentApps/useFrameworkCreation.ts | 2 +- tests/test_agent_app_new_app_scaffold.py | 98 +------------------ tests/test_agent_app_verification_gate.py | 39 ++++++++ 5 files changed, 54 insertions(+), 142 deletions(-) create mode 100644 tests/test_agent_app_verification_gate.py diff --git a/app/agent_app/framework_host.py b/app/agent_app/framework_host.py index ebfcb288..0102689d 100644 --- a/app/agent_app/framework_host.py +++ b/app/agent_app/framework_host.py @@ -16,10 +16,6 @@ _host = None -# Every new app starts from this complete upstream starter (PocketBase + React -# View, spec skeletons, plan). The builder never chooses among toolkits. -NEW_APP_BLUEPRINT = "blueprint-pocketbase-react" - async def no_ui_change(): """The framework host also runs without a browser client.""" @@ -527,8 +523,6 @@ async def workflow( ) if new_app: self.store.put("creation", session.id, {"path": path, **(creation or {}), "building": True}) - if activity == "create": - app_id = await self._scaffold_new_app(session.id, path, creation) from app.triggers.service import TriggerSpec from app.triggers.sources import TriggerSource @@ -536,11 +530,9 @@ async def workflow( f"Use the unchanged framework-{activities[activity]} skill.\n{request}\n" ) if activity == "create": - prompt += ( - f"CraftBot already scaffolded this app from {NEW_APP_BLUEPRINT} with the user's " - "selected name and access mode. Do not scaffold again or choose another " - "blueprint. Read reference/blueprint.md first, then follow the creator workflow.\n" - ) + prompt += "The destination below is allocated but DOES NOT EXIST yet. Discover the blueprints and scaffold it with the existing CLI before following the creator workflow.\n" + if creation: + prompt += "CraftBot binds the selected name and access mode to this destination's scaffold command. Use agent_app_command for scaffolding; do not replace the user's selections.\n" elif new_app: prompt += "The destination below is allocated but DOES NOT EXIST yet. Use it for adoption/conversion (or --into when installing) so this app keeps its current side chat. Follow the importer skill to choose the appropriate route with the user.\n" if path: @@ -566,32 +558,6 @@ async def workflow( await self.changed() return {"sessionId": session.id, "path": path} - async def _scaffold_new_app(self, session_id, path, creation): - """Scaffold a new app before its build conversation starts. - - The creation conversation is already recorded for this folder, so the - upstream identity binds to it as soon as the registry knows the app. - """ - args = [path, "scaffold", "--blueprint", NEW_APP_BLUEPRINT] - if creation: - args += ["--name", creation["name"], "--auth-mode", creation["authMode"]] - error = "The new app could not be scaffolded." - try: - result = await command("agent-app", args) - app_id = (result.get("data") or {}).get("id") - if result["status"] == "success" and app_id: - return app_id - error = (result.get("stderr") or "").strip() or error - except Exception as exc: - error = str(exc) or error - # Nothing was built: remove the empty build conversation rather than - # leave a pending app in the sidebar that can never finish. - self.store.delete("creation", session_id) - self.store.delete("conversation", session_id) - await self.agent.delete_session(session_id) - await self.changed() - raise RuntimeError(error) - def scaffold_arguments(self, session_id, args): """Carry explicit form choices into the unchanged CLI's scaffold flags.""" creation = self.store.get("creation", session_id) if session_id else None @@ -655,10 +621,14 @@ def report_verification(self, session_id, verdict, evidence): def require_verified(self, path): result = self.verification(path) + # Compare upstream's fingerprint, not the whole pass: validate rewrites + # the pass's timestamp even when the code is unchanged. + current = (self.gate_stamp(path) or {}).get("fingerprint") if ( not result or result.get("verdict") != "pass" - or result["stamp"] != self.gate_stamp(path) + or not current + or result["stamp"].get("fingerprint") != current ): raise ValueError( "Independent verification has not passed for this validation stamp. Run agent_app_framework_workflow(activity='verify') to await the independent verification subagent before promotion." diff --git a/app/agent_app/wizard.py b/app/agent_app/wizard.py index af0b0671..00e3881b 100644 --- a/app/agent_app/wizard.py +++ b/app/agent_app/wizard.py @@ -226,9 +226,8 @@ def _render_config(config: Dict[str, Any], image_notes: List[str]) -> str: # never drift apart. Describes the framework host contract. _PLATFORM_REALITY = """PLATFORM REALITY: - Apps run locally inside CraftBot's embedded app view, using the existing -Agent-App framework. New apps are built on its PocketBase + React (Vite) -blueprint; do not plan for another database, UI stack or toolkit, and do not -assume a port layout. +Agent-App framework. Discover its supported blueprints and capabilities; +do not assume a particular database, UI stack, port layout or toolkit. - Use the app's declared A2App operations and task contract. Apps can request work from CraftBot when the owner enables Allow requests to CraftBot. CraftBot routes accepted requests into the app's existing conversation. @@ -830,9 +829,9 @@ async def start_framework_build(host, config, requirements, attachments=()): return {"sessionId": job["sessionId"], "path": job["result"]["dir"]} return await host.workflow("modify", requirements, job["result"]["dir"], job["result"]["id"]) request = ( - "Build from the accepted requirements below. Save them in " - "reference/requirements.md for independent verification. Style the app with " - "the blueprint's design system. Copy the staged references into the app.\n" + "Build from the accepted requirements below. After scaffolding, save them " + "in reference/requirements.md for independent verification. Use the framework's " + "supported blueprint and styling options. Copy the staged references into the app.\n" + json.dumps({"preferences": config, "attachments": list(attachments)}, ensure_ascii=False) + "\n\n" + requirements ) diff --git a/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts b/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts index 426442c4..eeae8c31 100644 --- a/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts +++ b/app/ui_layer/browser/frontend/src/features/agentApps/useFrameworkCreation.ts @@ -79,7 +79,7 @@ export function useFrameworkCreation(onClose: () => void) { if (!response.ok || !result.path) throw new Error(result.error || `Could not upload ${file.name}`) references.push({ name: file.name, path: result.path, kind: file === icon ? 'icon' : 'reference' }) } - await workflow('create', `Create an app using these preferences. Clarify any missing requirements in this conversation. Style it with the blueprint's design system to match the requested design. Copy staged references into the app's reference directory.\n${JSON.stringify({ ...config, attachments: references }, null, 2)}`, { name: config.name, authMode: config.authMode, uiTheme: config.uiTheme }) + await workflow('create', `Create an app using these preferences. Clarify any missing requirements in this conversation. Use the framework's supported blueprint and styling options to match the requested design. Copy staged references into the app's reference directory.\n${JSON.stringify({ ...config, attachments: references }, null, 2)}`, { name: config.name, authMode: config.authMode, uiTheme: config.uiTheme }) } return { install, create } } diff --git a/tests/test_agent_app_new_app_scaffold.py b/tests/test_agent_app_new_app_scaffold.py index 68ac34b1..2ab76e17 100644 --- a/tests/test_agent_app_new_app_scaffold.py +++ b/tests/test_agent_app_new_app_scaffold.py @@ -1,4 +1,4 @@ -"""New apps start from one upstream blueprint, never the bundled Kanban's toolkit.""" +"""New apps never see the bundled Kanban's toolkit.""" import asyncio import sys @@ -6,8 +6,6 @@ import pytest -from app.agent_app import framework_host -from app.agent_app.framework_store import HostStore from app.provision import default_agent_app as default @@ -64,97 +62,3 @@ def prepare(surface, extra, new_app=False): with pytest.raises(Stop): asyncio.run(cli.run("agent-app", args, cwd=tmp_path)) assert seen == [True, True, False, False, False] - - -class _Agent: - def __init__(self): - self.calls = [] - self.deleted = [] - self.session_manager = SimpleNamespace(create_session=self._create) - self.trigger_service = SimpleNamespace(emit=self._emit) - - def _create(self, **kwargs): - self.calls.append(("session", kwargs)) - return SimpleNamespace(id="build-session") - - async def _emit(self, spec): - self.calls.append(("trigger", spec.description)) - - async def delete_session(self, session_id): - self.deleted.append(session_id) - return True - - -def _host(tmp_path, monkeypatch, result): - monkeypatch.setattr(framework_host, "_host", None) - monkeypatch.setattr( - framework_host.framework, - "configured_cli", - lambda: SimpleNamespace(home=tmp_path / "home"), - ) - agent = _Agent() - - async def command(surface, args): - agent.calls.append(("command", surface, args)) - return result - - monkeypatch.setattr(framework_host, "command", command) - host = framework_host.FrameworkHost(agent, store=HostStore(tmp_path / "host.sqlite3")) - return host, agent - - -def test_create_scaffolds_the_starter_before_the_builder_runs(tmp_path, monkeypatch): - host, agent = _host( - tmp_path, - monkeypatch, - {"status": "success", "data": {"id": "1e60ba80f83f"}, "stderr": ""}, - ) - result = asyncio.run( - host.workflow( - "create", - "Build a clock", - creation={"name": "Clock app", "authMode": "multi-user"}, - ) - ) - - kinds = [call[0] for call in agent.calls] - assert kinds == ["session", "command", "trigger"] - _, surface, args = agent.calls[1] - assert surface == "agent-app" - assert args == [ - result["path"], - "scaffold", - "--blueprint", - "blueprint-pocketbase-react", - "--name", - "Clock app", - "--auth-mode", - "multi-user", - ] - prompt = agent.calls[2][1] - assert "already scaffolded this app from blueprint-pocketbase-react" in prompt - assert "Do not scaffold again or choose another blueprint" in prompt - assert "1e60ba80f83f" in prompt - assert "Discover the blueprints" not in prompt - assert host.store.get("creation", "build-session")["building"] is True - - -def test_failed_scaffold_removes_the_empty_build_conversation(tmp_path, monkeypatch): - host, agent = _host( - tmp_path, - monkeypatch, - {"status": "error", "data": None, "stderr": "scaffold refused\n"}, - ) - with pytest.raises(RuntimeError, match="scaffold refused"): - asyncio.run( - host.workflow( - "create", - "Build a clock", - creation={"name": "Clock app", "authMode": "none"}, - ) - ) - - assert "trigger" not in [call[0] for call in agent.calls] - assert agent.deleted == ["build-session"] - assert host.store.get("creation", "build-session") is None - assert host.store.get("conversation", "build-session") is None diff --git a/tests/test_agent_app_verification_gate.py b/tests/test_agent_app_verification_gate.py new file mode 100644 index 00000000..13453d30 --- /dev/null +++ b/tests/test_agent_app_verification_gate.py @@ -0,0 +1,39 @@ +"""Promotion needs a walk-verify pass for the code upstream last validated.""" + +import json +from types import SimpleNamespace + +import pytest + +from app.agent_app import framework_host +from app.agent_app.framework_store import HostStore + + +@pytest.mark.parametrize( + ("verified", "gate", "allowed"), + [ + ({"verdict": "pass", "stamp": {"fingerprint": "abc", "at": "t1"}}, {"fingerprint": "abc", "at": "t1"}, True), + # Re-validating unchanged code only rewrites the pass's timestamp. + ({"verdict": "pass", "stamp": {"fingerprint": "abc", "at": "t1"}}, {"fingerprint": "abc", "at": "t2"}, True), + ({"verdict": "pass", "stamp": {"fingerprint": "abc", "at": "t1"}}, {"fingerprint": "new", "at": "t2"}, False), + ({"verdict": "defects", "stamp": {"fingerprint": "abc", "at": "t1"}}, {"fingerprint": "abc", "at": "t1"}, False), + ({"verdict": "pass", "stamp": {"fingerprint": "abc", "at": "t1"}}, None, False), + ], +) +def test_promote_requires_a_pass_for_the_validated_fingerprint( + tmp_path, monkeypatch, verified, gate, allowed +): + monkeypatch.setattr(framework_host, "_host", None) + host = framework_host.FrameworkHost( + SimpleNamespace(), store=HostStore(tmp_path / "host.sqlite3") + ) + app = tmp_path / "app" + (app / ".a2app").mkdir(parents=True) + if gate is not None: + (app / ".a2app" / "gate-pass.json").write_text(json.dumps(gate)) + host.store.put("verification", str(app.resolve()), verified) + if allowed: + host.require_verified(str(app)) + else: + with pytest.raises(ValueError, match="Independent verification has not passed"): + host.require_verified(str(app)) From ebf5a0427fa0d1a5dea234aba7852acd995be8f5 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sun, 15 Nov 2026 11:45:50 +0900 Subject: [PATCH 3/6] warn the agent when its reply is cut off at the output limit --- agent_core/core/impl/action/router.py | 17 ++- agent_core/core/impl/llm/interface.py | 14 +- .../impl/llm/transports/anthropic_messages.py | 8 +- .../impl/llm/transports/bedrock_converse.py | 3 + .../impl/llm/transports/byteplus_responses.py | 24 +++- .../impl/llm/transports/chat_completions.py | 7 +- .../core/impl/llm/transports/gemini_native.py | 8 +- agent_core/core/llm/google_gemini_client.py | 11 ++ tests/test_decision_retries.py | 31 +++++ tests/test_llm_reply_cut_off.py | 131 ++++++++++++++++++ 10 files changed, 247 insertions(+), 7 deletions(-) create mode 100644 tests/test_llm_reply_cut_off.py diff --git a/agent_core/core/impl/action/router.py b/agent_core/core/impl/action/router.py index 16421339..b06d4393 100644 --- a/agent_core/core/impl/action/router.py +++ b/agent_core/core/impl/action/router.py @@ -29,7 +29,8 @@ SELECT_ACTION_PROMPT, decision_system_prompt, ) -from agent_core.core.impl.llm.interface import LLMContextOverflowError +from agent_core.core.impl.llm.interface import LLMContextOverflowError, LLMReply +from agent_core.core.event_stream.event import EventType from agent_core import get_event_stream_manager from agent_core.utils.logger import logger from agent_core.utils.token import count_tokens @@ -764,6 +765,20 @@ def full_request(up_to: Optional[int]) -> str: f"Failed to parse LLM decision on attempt {attempt + 1}: " f"{raw_response} | error={feedback_error}" ) + if ( + isinstance(raw_response, LLMReply) + and raw_response.cut_off + and stream is not None + ): + # The next attempt's request carries the warning. + stream.log( + "warning", + "Your previous reply was cut off: it reached the output " + "limit before it finished, so none of it was used. Keep " + "each reply small: split large content across several " + "actions, e.g. write a long file one section at a time.", + event_type=EventType.INTERNAL, + ) # A session history holding the reply gets the feedback as its # next turn; anything else resends the prompt with it. attempt_feedback = self._parse_error_feedback( diff --git a/agent_core/core/impl/llm/interface.py b/agent_core/core/impl/llm/interface.py index e7916060..95dbc8b2 100644 --- a/agent_core/core/impl/llm/interface.py +++ b/agent_core/core/impl/llm/interface.py @@ -151,6 +151,16 @@ class _SessionCheckpoint: input_tokens: Optional[int] +class LLMReply(str): + """A reply's text. ``cut_off``: the provider stopped it at the output + limit before it finished.""" + + def __new__(cls, text: str, cut_off: bool = False) -> "LLMReply": + reply = super().__new__(cls, text) + reply.cut_off = cut_off + return reply + + class LLMContextOverflowError(RuntimeError): """The assembled request does not fit the configured context window. @@ -1195,7 +1205,7 @@ def _generate_response_sync( if log_response: logger.info(f"[LLM RECV] {cleaned}") - return cleaned + return LLMReply(cleaned, bool(response.get("cut_off"))) except LLMConsecutiveFailureError: # Re-raise consecutive failure errors without incrementing counter @@ -1741,7 +1751,7 @@ def _session_attempt(fb, _t=task_id, _c=call_type): self._set_token_count(current_count + billable_tokens(response)) if log_response: logger.info(f"[LLM RECV] {cleaned}") - return cleaned + return LLMReply(cleaned, bool(response.get("cut_off"))) def _generate_response_with_session_sync( self, diff --git a/agent_core/core/impl/llm/transports/anthropic_messages.py b/agent_core/core/impl/llm/transports/anthropic_messages.py index abafa6fd..5b2b8dcb 100644 --- a/agent_core/core/impl/llm/transports/anthropic_messages.py +++ b/agent_core/core/impl/llm/transports/anthropic_messages.py @@ -73,6 +73,7 @@ def generate( cache_read = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None config = get_cache_config() cache_type = f"ephemeral_{call_type}" if call_type else "ephemeral" @@ -138,6 +139,7 @@ def generate( if block.type == "text": content += block.text content = content.strip() + cut_off = getattr(response, "stop_reason", None) == "max_tokens" # Token usage from Anthropic response # Anthropic reports input_tokens as non-cached input only. @@ -201,7 +203,11 @@ def generate( cached_tokens, ) - result = {"tokens_used": total_tokens or 0, "cached_tokens": cached_tokens} + result = { + "tokens_used": total_tokens or 0, + "cached_tokens": cached_tokens, + "cut_off": cut_off, + } if exc_obj: error_str = f"{type(exc_obj).__name__}: {str(exc_obj)}" result["error"] = error_str diff --git a/agent_core/core/impl/llm/transports/bedrock_converse.py b/agent_core/core/impl/llm/transports/bedrock_converse.py index 3af9884b..a7dbf942 100644 --- a/agent_core/core/impl/llm/transports/bedrock_converse.py +++ b/agent_core/core/impl/llm/transports/bedrock_converse.py @@ -59,6 +59,7 @@ def generate( cached_tokens = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None config = get_cache_config() cache_type = f"cachepoint_{call_type}" if call_type else "cachepoint" @@ -124,6 +125,7 @@ def generate( content = "".join( block.get("text", "") for block in content_blocks if "text" in block ).strip() + cut_off = response.get("stopReason") == "max_tokens" usage = response.get("usage", {}) or {} token_count_input = int(usage.get("inputTokens", 0) or 0) @@ -207,6 +209,7 @@ def generate( result = { "tokens_used": total_tokens or 0, "cached_tokens": cached_tokens, + "cut_off": cut_off, } if exc_obj: error_str = f"{type(exc_obj).__name__}: {str(exc_obj)}" diff --git a/agent_core/core/impl/llm/transports/byteplus_responses.py b/agent_core/core/impl/llm/transports/byteplus_responses.py index 3001ec8e..20821dbb 100644 --- a/agent_core/core/impl/llm/transports/byteplus_responses.py +++ b/agent_core/core/impl/llm/transports/byteplus_responses.py @@ -74,6 +74,7 @@ def generate_with_prefix_cache( cached_tokens = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None try: @@ -89,6 +90,7 @@ def generate_with_prefix_cache( # Parse response (Responses API format) content = iface._parse_responses_api_content(result) + cut_off = _byteplus_cut_off(result) if not content: blocked_reason = _byteplus_blocked_reason(result) @@ -140,6 +142,7 @@ def generate_with_prefix_cache( max_tokens=iface.max_tokens, ) content = iface._parse_responses_api_content(result) + cut_off = _byteplus_cut_off(result) usage = result.get("usage") or {} token_count_input = int(usage.get("input_tokens", 0)) token_count_output = int(usage.get("output_tokens", 0)) @@ -181,6 +184,7 @@ def generate_with_prefix_cache( result_out: Dict[str, Any] = { "tokens_used": total_tokens or 0, "cached_tokens": cached_tokens or 0, + "cut_off": cut_off, } if exc_obj: error_str = f"{type(exc_obj).__name__}: {str(exc_obj)}" @@ -205,6 +209,7 @@ def generate_standard( total_tokens = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None try: @@ -247,6 +252,7 @@ def generate_standard( logger.info(f"[BYTEPLUS STANDARD RESPONSE] Body: {result}") # Non-streaming content location (OpenAI-compatible) + cut_off = _byteplus_cut_off(result) choices = result.get("choices", []) if choices: # choices[0].message.content is the OpenAI-compatible field @@ -294,7 +300,7 @@ def generate_standard( 0, ) - result = {"tokens_used": total_tokens or 0} + result = {"tokens_used": total_tokens or 0, "cut_off": cut_off} if exc_obj: error_str = f"{type(exc_obj).__name__}: {str(exc_obj)}" result["error"] = error_str @@ -337,6 +343,7 @@ def generate_with_session( total_tokens = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None cached_tokens = 0 session_key = f"{task_id}:{call_type}" @@ -377,6 +384,7 @@ def generate_with_session( # Parse response (Responses API format) content = iface._parse_responses_api_content(result) + cut_off = _byteplus_cut_off(result) # Token usage from Responses API usage = result.get("usage") or {} @@ -443,6 +451,7 @@ def generate_with_session( # Parse response content = iface._parse_responses_api_content(result) + cut_off = _byteplus_cut_off(result) # Token usage usage = result.get("usage") or {} @@ -505,9 +514,22 @@ def generate_with_session( "tokens_used": total_tokens or 0, "content": content or "", "cached_tokens": cached_tokens or 0, + "cut_off": cut_off, } +def _byteplus_cut_off(result: Dict[str, Any]) -> bool: + """Whether BytePlus stopped the reply at the output limit: a Responses + API result left incomplete for max_output_tokens, or a chat completion + that finished for length.""" + if result.get("status") == "incomplete": + return (result.get("incomplete_details") or {}).get( + "reason" + ) == "max_output_tokens" + choices = result.get("choices") or [] + return bool(choices) and choices[0].get("finish_reason") == "length" + + def _byteplus_blocked_reason(result: Dict[str, Any]) -> Optional[str]: """Best-effort detection of content-filter/moderation blocking in a BytePlus Responses API result that came back with empty content but no diff --git a/agent_core/core/impl/llm/transports/chat_completions.py b/agent_core/core/impl/llm/transports/chat_completions.py index c58977e1..3ba4fb47 100644 --- a/agent_core/core/impl/llm/transports/chat_completions.py +++ b/agent_core/core/impl/llm/transports/chat_completions.py @@ -86,6 +86,7 @@ def generate_openai( cached_tokens = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None config = get_cache_config() cache_type = f"automatic_{call_type}" if call_type else "automatic" @@ -224,6 +225,7 @@ def generate_openai( if not response.choices: raise ValueError(f"Provider returned no choices (model={iface.model!r})") content = _strip_reasoning_tags(response.choices[0].message.content) + cut_off = getattr(response.choices[0], "finish_reason", None) == "length" token_count_input = response.usage.prompt_tokens token_count_output = response.usage.completion_tokens @@ -304,6 +306,7 @@ def generate_openai( result = { "tokens_used": total_tokens or 0, "cached_tokens": cached_tokens, + "cut_off": cut_off, } if exc_obj: @@ -348,6 +351,7 @@ def generate_ollama( total_tokens = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None try: @@ -372,6 +376,7 @@ def generate_ollama( result = response.json() content = result.get("response", "").strip() + cut_off = result.get("done_reason") == "length" token_count_input = result.get("prompt_eval_count", 0) token_count_output = result.get("eval_count", 0) total_tokens = token_count_input + token_count_output @@ -394,7 +399,7 @@ def generate_ollama( "llm_ollama", "remote", iface.model, token_count_input, token_count_output, 0 ) - result = {"tokens_used": total_tokens or 0} + result = {"tokens_used": total_tokens or 0, "cut_off": cut_off} if exc_obj: error_str = f"{type(exc_obj).__name__}: {str(exc_obj)}" result["error"] = error_str diff --git a/agent_core/core/impl/llm/transports/gemini_native.py b/agent_core/core/impl/llm/transports/gemini_native.py index 251c965d..ad5fa48f 100644 --- a/agent_core/core/impl/llm/transports/gemini_native.py +++ b/agent_core/core/impl/llm/transports/gemini_native.py @@ -78,6 +78,7 @@ def generate( total_tokens = 0 status = "failed" content: Optional[str] = None + cut_off = False exc_obj: Optional[Exception] = None config = get_cache_config() cache_type = "implicit" # Default cache type for metrics @@ -149,6 +150,7 @@ def generate( # Extract response data content = result.get("content", "") + cut_off = result.get("cut_off", False) total_tokens = result.get("tokens_used", 0) token_count_input = result.get("prompt_tokens", 0) token_count_output = result.get("completion_tokens", 0) @@ -199,7 +201,11 @@ def generate( cached_tokens, ) - result = {"tokens_used": total_tokens or 0, "cached_tokens": cached_tokens} + result = { + "tokens_used": total_tokens or 0, + "cached_tokens": cached_tokens, + "cut_off": cut_off, + } if exc_obj: error_str = f"{type(exc_obj).__name__}: {str(exc_obj)}" result["error"] = error_str diff --git a/agent_core/core/llm/google_gemini_client.py b/agent_core/core/llm/google_gemini_client.py index 98e2593b..364eae35 100644 --- a/agent_core/core/llm/google_gemini_client.py +++ b/agent_core/core/llm/google_gemini_client.py @@ -194,6 +194,7 @@ def generate_text( "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "cached_tokens": cached_tokens, + "cut_off": self._cut_off(response), } def generate_text_multiturn( @@ -270,6 +271,7 @@ def generate_text_multiturn( "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "cached_tokens": cached_tokens, + "cut_off": self._cut_off(response), } def generate_multimodal( @@ -525,6 +527,7 @@ def generate_text_with_cache( "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "cached_tokens": cached_tokens, + "cut_off": self._cut_off(response), } def generate_multimodal_with_cache( @@ -862,6 +865,14 @@ def _post_json(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]: response.raise_for_status() return response.json() + @staticmethod + def _cut_off(response: Dict[str, Any]) -> bool: + """Whether Gemini stopped the reply at the output limit.""" + return any( + candidate.get("finishReason") == "MAX_TOKENS" + for candidate in response.get("candidates", []) or [] + ) + @staticmethod def _extract_text(response: Dict[str, Any]) -> str: """Extract text content from Gemini response.""" diff --git a/tests/test_decision_retries.py b/tests/test_decision_retries.py index e2555370..df34f642 100644 --- a/tests/test_decision_retries.py +++ b/tests/test_decision_retries.py @@ -25,6 +25,7 @@ from agent_core.core.impl.action import router as router_module from agent_core.core.impl.event_stream.event_stream import EventStream from agent_core.core.impl.llm import LLMCallType +from agent_core.core.impl.llm.interface import LLMReply ACTION = LLMCallType.ACTION_SELECTION END_TURN = ( @@ -402,3 +403,33 @@ def test_the_stream_renders_and_syncs_up_to_a_point(): stream.mark_session_synced(ACTION, up_to=point) delta, has_delta = stream.get_delta_events(ACTION) assert has_delta and "event 3" in delta and "event 2" not in delta + + +# ── a reply cut off at the output limit ───────────────────────────────────── +# +# The provider stopped the reply before it finished, so it does not parse. +# The router warns the agent through its event stream, so the retry knows +# why and splits its work instead of resending the same oversized reply. + +CUT_OFF_WARNING = "Your previous reply was cut off" + + +@pytest.mark.parametrize("sessions", [True, False]) +def test_a_cut_off_reply_puts_a_warning_in_the_event_stream(monkeypatch, sessions): + stream = EventStream(llm=None, temp_dir=None) + stream.log("action_end", "before the request") + cut_off = LLMReply('{"reasoning": "r", "actions": [{"action_name": "wri', True) + llm = _LLM([cut_off, END_TURN], sessions=sessions) + _decide_on(_real_router(monkeypatch, llm, stream), stream) + + assert CUT_OFF_WARNING not in llm.sent[0]["user"] + assert CUT_OFF_WARNING in llm.sent[1]["user"] + + +def test_a_reply_that_was_not_cut_off_gets_no_warning(monkeypatch): + stream = EventStream(llm=None, temp_dir=None) + stream.log("action_end", "before the request") + llm = _LLM([LLMReply("not json"), END_TURN]) + _decide_on(_real_router(monkeypatch, llm, stream), stream) + + assert CUT_OFF_WARNING not in llm.sent[1]["user"] diff --git a/tests/test_llm_reply_cut_off.py b/tests/test_llm_reply_cut_off.py new file mode 100644 index 00000000..77edbf97 --- /dev/null +++ b/tests/test_llm_reply_cut_off.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +"""A reply the provider cut off at the output limit is reported as cut off. + +Every transport reads its provider's stop reason into the result's +``cut_off``, and the interface hands it on with the reply text (LLMReply), +so the action router can warn the agent through its event stream. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from agent_core.core.impl.llm.interface import LLMInterface, LLMReply +from agent_core.core.impl.llm.transports import ( + anthropic_messages, + bedrock_converse, + byteplus_responses, + chat_completions, +) +from agent_core.core.llm.google_gemini_client import GeminiClient + + +def _iface(provider, **clients): + return SimpleNamespace( + provider=provider, + model="m", + temperature=0.0, + max_tokens=8000, + _call_log_to_db=lambda *args, **kwargs: None, + _report_usage_async=lambda *args, **kwargs: None, + _bedrock_model_supports_caching=lambda: False, + **clients, + ) + + +def _openai(finish_reason): + choice = SimpleNamespace( + message=SimpleNamespace(content='{"a": 1}'), finish_reason=finish_reason + ) + usage = SimpleNamespace( + prompt_tokens=1, completion_tokens=1, prompt_tokens_details=None + ) + create = lambda **kwargs: SimpleNamespace(choices=[choice], usage=usage) + client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=create))) + return chat_completions.generate_openai( + _iface("openai", client=client), None, "u", reasoning=None + ) + + +def _anthropic(stop_reason): + response = SimpleNamespace( + content=[SimpleNamespace(type="text", text='{"a": 1}')], + stop_reason=stop_reason, + usage=SimpleNamespace( + input_tokens=1, + output_tokens=1, + cache_creation_input_tokens=0, + cache_read_input_tokens=0, + ), + ) + client = SimpleNamespace(messages=SimpleNamespace(create=lambda **kwargs: response)) + return anthropic_messages.generate( + _iface("anthropic", _anthropic_client=client), None, "u", reasoning=None + ) + + +def _bedrock(stop_reason): + response = { + "output": {"message": {"content": [{"text": '{"a": 1}'}]}}, + "stopReason": stop_reason, + "usage": {"inputTokens": 1, "outputTokens": 1}, + } + client = SimpleNamespace(converse=lambda **kwargs: response) + return bedrock_converse.generate( + _iface("bedrock", _bedrock_client=client), None, "u", reasoning=None + ) + + +@pytest.mark.parametrize( + "call, limit, finished", + [ + (_openai, "length", "stop"), + (_anthropic, "max_tokens", "end_turn"), + (_bedrock, "max_tokens", "end_turn"), + ], +) +def test_transports_report_a_reply_stopped_at_the_output_limit(call, limit, finished): + assert call(limit)["cut_off"] is True + assert call(finished)["cut_off"] is False + + +def test_a_chat_completion_without_a_finish_reason_is_not_cut_off(): + assert _openai(None)["cut_off"] is False + + +def test_gemini_reports_max_tokens(): + assert GeminiClient._cut_off({"candidates": [{"finishReason": "MAX_TOKENS"}]}) + assert not GeminiClient._cut_off({"candidates": [{"finishReason": "STOP"}]}) + assert not GeminiClient._cut_off({}) + + +@pytest.mark.parametrize( + "result, cut_off", + [ + ( + {"status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"}}, + True, + ), + ( + {"status": "incomplete", "incomplete_details": {"reason": "content_filter"}}, + False, + ), + ({"status": "completed"}, False), + ({"choices": [{"finish_reason": "length"}]}, True), + ({"choices": [{"finish_reason": "stop"}]}, False), + ], +) +def test_byteplus_reports_both_response_shapes(result, cut_off): + assert byteplus_responses._byteplus_cut_off(result) is cut_off + + +@pytest.mark.parametrize("cut_off", [True, False]) +def test_the_interface_hands_the_flag_on_with_the_reply(cut_off): + llm = LLMInterface(provider="openai", model="m", deferred=True) + reply = llm._finalize_session_response( + {"content": '{"a": 1}', "cut_off": cut_off}, log_response=False + ) + assert isinstance(reply, LLMReply) + assert reply == '{"a": 1}' and reply.cut_off is cut_off From b183301119a887890caf54f0634c3956eb83c728 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sun, 15 Nov 2026 15:16:26 +0900 Subject: [PATCH 4/6] re-verify only what changed since the last verified commit --- app/agent_app/framework_host.py | 9 +- app/agent_app/framework_verification.py | 72 ++++++++++++-- .../action/agent_app_framework_actions.py | 4 +- .../definitions/framework_walk_verify.py | 6 +- tests/test_agent_app_reverify.py | 93 +++++++++++++++++++ 5 files changed, 171 insertions(+), 13 deletions(-) create mode 100644 tests/test_agent_app_reverify.py diff --git a/app/agent_app/framework_host.py b/app/agent_app/framework_host.py index 0102689d..2402d6b5 100644 --- a/app/agent_app/framework_host.py +++ b/app/agent_app/framework_host.py @@ -13,6 +13,7 @@ from app.agent_app import framework from app.agent_app.framework_commands import command, context_note from app.agent_app.framework_store import HostStore, app_key +from app.subagent.definitions.framework_walk_verify import PASS, VERDICTS _host = None @@ -188,7 +189,7 @@ async def startup(self): running = any(row["path"] == path and row.get("status") == "running" for row in rows) if "building" in creation and not running: continue - promoted = (self.verification(path) or {}).get("verdict") == "pass" and not self.gate_stamp(path) + promoted = (self.verification(path) or {}).get("verdict") == PASS and not self.gate_stamp(path) creation["building"] = not (running or promoted) self.store.put("creation", note["sessionId"], creation) registered = { @@ -597,13 +598,13 @@ def report_verification(self, session_id, verdict, evidence): if assignment.get("mode") == "subagent" and assignment.get("status") != "running": raise PermissionError("This verification subagent has already ended.") if ( - verdict not in {"pass", "defects", "incomplete", "blocked"} + verdict not in VERDICTS or not isinstance(evidence, str) or not evidence.strip() ): raise ValueError("A verifier verdict and supporting evidence are required.") if ( - verdict == "pass" + verdict == PASS and self.gate_stamp(assignment["path"]) != assignment["stamp"] ): raise ValueError( @@ -626,7 +627,7 @@ def require_verified(self, path): current = (self.gate_stamp(path) or {}).get("fingerprint") if ( not result - or result.get("verdict") != "pass" + or result.get("verdict") != PASS or not current or result["stamp"].get("fingerprint") != current ): diff --git a/app/agent_app/framework_verification.py b/app/agent_app/framework_verification.py index cd46a10c..c7f8c71c 100644 --- a/app/agent_app/framework_verification.py +++ b/app/agent_app/framework_verification.py @@ -4,11 +4,19 @@ import asyncio import json +import os +import subprocess from contextvars import ContextVar from dataclasses import dataclass from pathlib import Path from app.agent_app.framework_commands import skill_sources +from app.subagent.definitions.framework_walk_verify import ( + BLOCKED, + DEFECTS, + INCOMPLETE, + PASS, +) @dataclass @@ -49,6 +57,43 @@ def read_dev(path): return value +def _git(path, *args): + return subprocess.run( + ["git", "-C", str(path), *args], + capture_output=True, + text=True, + timeout=30, + check=True, + **({"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}), + ).stdout + + +def verified_commit(path): + """The commit a walk of the app at ``path`` verifies: HEAD of the app's own + repository when no tracked file has changed. None when the app has no + repository of its own or carries uncommitted work.""" + try: + top = _git(path, "rev-parse", "--show-toplevel").strip() + head = _git(path, "rev-parse", "HEAD").strip() + changed = _git(path, "status", "--porcelain", "--untracked-files=no") + except (OSError, subprocess.SubprocessError): + return None + if changed.strip() or Path(top).resolve() != Path(path).resolve(): + return None + return head or None + + +def baseline(host, path): + """What a walk of the app at ``path`` re-verifies from: the last finished + walk (pass or defects) of a commit, or else the baseline that walk started + from. Kept apart from the verification record, which the builder reads.""" + key = str(Path(path).resolve()) + previous = host.verification(path) or {} + if previous.get("verdict") in (PASS, DEFECTS) and previous.get("commit"): + return {name: previous[name] for name in ("verdict", "commit", "evidence")} + return host.store.get("verification_baseline", key) + + async def run_verification(host, row, stamp, request, parent_session_id): from app.internal_action_interface import InternalActionInterface as I from app.logger import logger, add_subagent_log_sink, remove_subagent_log_sink @@ -70,16 +115,28 @@ async def run_verification(host, row, stamp, request, parent_session_id): if parent is None or getattr(parent, "isolated_app_task", False): raise ValueError("Verification needs an existing owner conversation.") target = VerificationTarget(row["path"], stamp, read_dev(row["path"]), host) + # Kept before this walk's own record replaces the last one. + base = baseline(host, row["path"]) + if base: + host.store.put("verification_baseline", str(Path(row["path"]).resolve()), base) + commit = await asyncio.to_thread(verified_commit, row["path"]) sources = await skill_sources() source = sources["framework-walk-verify"] skill = await asyncio.to_thread(source.read_text, encoding="utf-8") target.check() + last = ( + f"Last verification: {base['verdict']} at commit {base['commit']}. " + f"Its report:\n{base['evidence']}\n\n" + if base + else "Last verification: none.\n\n" + ) query = ( f"Independently verify {row['name']} ({row['id']}).\n" f"App directory: {row['path']}\nDEV URL: {target.dev['url']}\n" f"Requirements: {Path(row['path']) / 'reference' / 'requirements.md'}\n" f"Evidence directory: {parent.workspace_dir or 'use the Mini Browser screenshot paths'}\n" - f"Requested checks (builder claims, verify independently): {request}\n\n" + f"Requested checks (builder claims, verify independently): {request}\n" + f"{last}" f"Installed skill source: {source}\nResolve relative references from: {source.parent}\n" f"--- BEGIN UNCHANGED FRAMEWORK SKILL ---\n{skill}\n--- END FRAMEWORK SKILL ---" ) @@ -93,6 +150,7 @@ async def run_verification(host, row, stamp, request, parent_session_id): "path": row["path"], "appId": row["id"], "stamp": stamp, + "commit": commit, "builderSessionId": parent.id, "mode": "subagent", "status": "running", @@ -111,7 +169,7 @@ def record(verdict, evidence): host.store.put("verification_session", sub.id, assignment) # Starting a new walk invalidates any earlier pass, including on cancellation. host.report_verification( - sub.id, "incomplete", "Independent verification is running." + sub.id, INCOMPLETE, "Independent verification is running." ) await host.changed() runner = SubAgentRunner(manager, actions, library, events, llm) @@ -121,8 +179,8 @@ def record(verdict, evidence): try: result = json.loads(sub.result or "") verdict, evidence = result["verdict"], result["evidence"] - if verdict == "pass" and sub.status != "completed": - verdict = "incomplete" + if verdict == PASS and sub.status != "completed": + verdict = INCOMPLETE evidence = ( f"Verifier ended as {sub.status}; no pass recorded.\n{evidence}" ) @@ -130,7 +188,7 @@ def record(verdict, evidence): report = record(verdict, evidence) except (ValueError, TypeError, KeyError, PermissionError) as error: report = record( - "incomplete", + INCOMPLETE, f"Verification did not produce a valid result for this candidate: {error}\n{sub.result or sub.status}", ) return { @@ -142,11 +200,11 @@ def record(verdict, evidence): } except asyncio.CancelledError: sub.terminate("failed", "Verification canceled with its parent run.") - record("incomplete", sub.result) + record(INCOMPLETE, sub.result) raise except Exception as error: sub.terminate("error", str(error)) - report = record("blocked", f"Verifier could not finish: {error}") + report = record(BLOCKED, f"Verifier could not finish: {error}") return { "sessionId": parent.id, "childTaskId": sub.id, diff --git a/app/data/action/agent_app_framework_actions.py b/app/data/action/agent_app_framework_actions.py index bd57a4e3..f4d009fa 100644 --- a/app/data/action/agent_app_framework_actions.py +++ b/app/data/action/agent_app_framework_actions.py @@ -2,6 +2,8 @@ from agent_core import action +from app.subagent.definitions.framework_walk_verify import VERDICTS + @action( name="agent_app_framework_verification", @@ -15,7 +17,7 @@ "path": {"type": "string", "required": False}, "verdict": { "type": "string", - "enum": ["pass", "defects", "incomplete", "blocked"], + "enum": list(VERDICTS), "required": False, }, "evidence": {"type": "string", "required": False}, diff --git a/app/subagent/definitions/framework_walk_verify.py b/app/subagent/definitions/framework_walk_verify.py index 966dda04..3c497805 100644 --- a/app/subagent/definitions/framework_walk_verify.py +++ b/app/subagent/definitions/framework_walk_verify.py @@ -5,6 +5,10 @@ from app.subagent.registry import register_subagent +# The verdicts of the walk-verify skill this verifier runs. +PASS, DEFECTS, INCOMPLETE, BLOCKED = "pass", "defects", "incomplete", "blocked" +VERDICTS = (PASS, DEFECTS, INCOMPLETE, BLOCKED) + def _valid_result(sub, parameters): # This checks transport shape only. The upstream skill owns what to verify. @@ -12,7 +16,7 @@ def _valid_result(sub, parameters): result = json.loads(parameters.get("result", "")) if ( isinstance(result, dict) - and result.get("verdict") in {"pass", "defects", "incomplete", "blocked"} + and result.get("verdict") in VERDICTS and isinstance(result.get("evidence"), str) and result["evidence"].strip() ): diff --git a/tests/test_agent_app_reverify.py b/tests/test_agent_app_reverify.py new file mode 100644 index 00000000..4379444e --- /dev/null +++ b/tests/test_agent_app_reverify.py @@ -0,0 +1,93 @@ +"""A verification re-verifies from the last finished walk of a commit. + +The walk-verify skill re-verifies only what changed since the commit the last +walk verified. CraftBot records that commit with each walk, and hands the +next walk the last finished one (pass or defects) as its baseline. +""" + +import subprocess + +import pytest + +from app.agent_app.framework_verification import baseline, verified_commit + + +def _git(path, *args): + return subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@t", "-C", str(path), *args], + capture_output=True, + text=True, + check=True, + ).stdout.strip() + + +@pytest.fixture +def app(tmp_path): + (tmp_path / "reference").mkdir() + (tmp_path / "reference" / "tasks.md").write_text("- [ ] walk-verify\n") + (tmp_path / "app.js").write_text("export const n = 1;\n") + _git(tmp_path, "init", "-q") + _git(tmp_path, "add", "-A") + _git(tmp_path, "commit", "-q", "-m", "build") + return tmp_path + + +def test_a_committed_app_verifies_its_head(app): + assert verified_commit(app) == _git(app, "rev-parse", "HEAD") + + +def test_untracked_files_keep_the_commit(app): + (app / "notes.txt").write_text("untracked\n") # runtime state is often untracked + assert verified_commit(app) == _git(app, "rev-parse", "HEAD") + + +@pytest.mark.parametrize("path", ["app.js", "reference/tasks.md"]) +def test_any_uncommitted_change_has_no_verified_commit(app, path): + (app / path).write_text("changed\n") + assert verified_commit(app) is None + + +def test_an_app_without_its_own_repository_has_no_verified_commit(app, tmp_path): + nested = app / "nested" + nested.mkdir() + assert verified_commit(nested) is None # inside another repository + assert verified_commit(tmp_path.parent / "no-such-app") is None + + +class _Host: + def __init__(self, record, stored=None): + self.record = record + self.store = self + self.stored = stored + + def verification(self, path): + return self.record + + def get(self, kind, key): + assert kind == "verification_baseline" + return self.stored + + +@pytest.mark.parametrize("verdict", ["pass", "defects"]) +def test_a_finished_walk_of_a_commit_is_the_baseline(verdict): + record = {"verdict": verdict, "commit": "abc", "evidence": "report", "stamp": {}} + assert baseline(_Host(record), "app") == { + "verdict": verdict, + "commit": "abc", + "evidence": "report", + } + + +@pytest.mark.parametrize( + "record", + [ + {"verdict": "incomplete", "commit": "def", "evidence": "cut short"}, + {"verdict": "blocked", "commit": "def", "evidence": "no browser"}, + {"verdict": "pass", "commit": None, "evidence": "uncommitted code"}, + None, + ], +) +def test_otherwise_the_last_baseline_still_applies(record): + kept = {"verdict": "pass", "commit": "abc", "evidence": "report"} + assert baseline(_Host(record, kept), "app") == kept + assert baseline(_Host(record), "app") is None From faf2eb361033e539b6705fb55fd2fbcd88772b54 Mon Sep 17 00:00:00 2001 From: zfoong Date: Mon, 16 Nov 2026 10:05:29 +0900 Subject: [PATCH 5/6] remake the subagents due to many places that does not make sense --- agent_core/core/action_framework/__init__.py | 2 - .../core/action_framework/formatting.py | 38 +- agent_core/core/impl/action/__init__.py | 4 + agent_core/core/impl/action/router.py | 144 ++-- agent_core/core/impl/action/step.py | 103 +++ agent_core/core/impl/context/__init__.py | 6 +- agent_core/core/impl/context/engine.py | 341 ++++---- .../core/impl/event_stream/event_stream.py | 14 +- agent_core/core/impl/event_stream/manager.py | 12 +- .../models/chatgpt_subscription_client.py | 2 +- agent_core/core/prompts/__init__.py | 5 + agent_core/core/protocols/context.py | 26 +- agent_core/core/protocols/event_stream.py | 5 +- app/agent_app/framework_verification.py | 43 +- app/agent_base.py | 89 +- app/data/action/spawn_subagent.py | 89 +- app/errors/codebook.py | 6 - app/internal_action_interface.py | 12 - app/logger.py | 5 +- app/mini_browser/config.py | 2 +- app/mini_browser/host.py | 5 +- app/mini_browser/lifecycle.py | 8 +- app/subagent/__init__.py | 54 +- app/subagent/context_engine.py | 260 +++--- app/subagent/definitions/__init__.py | 5 +- app/subagent/definitions/browser_agent.py | 35 +- .../definitions/framework_walk_verify.py | 13 - app/subagent/definitions/general_agent.py | 5 - app/subagent/definitions/research_agent.py | 5 - app/subagent/definitions/validation_agent.py | 175 ---- app/subagent/manager.py | 194 +++-- app/subagent/registry.py | 74 +- app/subagent/runner.py | 814 ++++-------------- app/subagent/types.py | 60 +- tests/test_context_budget.py | 13 +- tests/test_decision_retries.py | 6 +- tests/test_error_catalog.py | 4 +- tests/test_fold_summary_on_history.py | 2 +- tests/test_general_subagent.py | 143 +-- tests/test_mini_browser_agent_integration.py | 13 +- tests/test_mini_browser_engine.py | 12 +- tests/test_mini_browser_engine_fixes.py | 2 +- tests/test_mini_browser_fleet.py | 2 +- tests/test_subagent_bootstrap_prompt.py | 123 --- tests/test_subagent_runtime.py | 553 ++++++++++++ 45 files changed, 1484 insertions(+), 2044 deletions(-) create mode 100644 agent_core/core/impl/action/step.py delete mode 100644 app/subagent/definitions/validation_agent.py delete mode 100644 tests/test_subagent_bootstrap_prompt.py create mode 100644 tests/test_subagent_runtime.py diff --git a/agent_core/core/action_framework/__init__.py b/agent_core/core/action_framework/__init__.py index 26d4bc41..f9e3c34a 100644 --- a/agent_core/core/action_framework/__init__.py +++ b/agent_core/core/action_framework/__init__.py @@ -20,7 +20,6 @@ from agent_core.core.action_framework.formatting import ( candidate_dict_from_action, format_action_candidates, - format_actions_by_name, ) __all__ = [ @@ -44,5 +43,4 @@ # Formatting "candidate_dict_from_action", "format_action_candidates", - "format_actions_by_name", ] diff --git a/agent_core/core/action_framework/formatting.py b/agent_core/core/action_framework/formatting.py index 56cd3017..697bf497 100644 --- a/agent_core/core/action_framework/formatting.py +++ b/agent_core/core/action_framework/formatting.py @@ -14,14 +14,14 @@ ``account``). - No ``example`` fields, no nested type-definitions. -Both ``ActionRouter`` (main agent) and ``SubAgentContextEngine`` (sub-agents) -should call ``format_action_candidates`` so the format stays in sync. +Every list (ActionRouter, for the main agent and sub-agents alike) +and every action_schemas event renders through ``format_action_candidates``. """ from __future__ import annotations import json -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List def candidate_dict_from_action(action) -> Dict[str, Any]: @@ -119,39 +119,7 @@ def _params_every_action_takes(compact: List[Dict[str, Any]]) -> Dict[str, str]: } -def format_actions_by_name( - action_names: List[str], - action_library, - *, - on_missing: Optional[str] = None, -) -> str: - """Convenience: look up actions by name and render them. - - Args: - action_names: Ordered list of action names to include. - action_library: Anything with ``retrieve_action(name) -> Action | None``. - on_missing: Optional log-message prefix for actions that aren't found; - when None, missing actions are silently skipped. - - Returns: - Compact JSON block (or ``"[]"`` if nothing resolved). - """ - candidates: List[Dict[str, Any]] = [] - for name in action_names: - act = action_library.retrieve_action(name) - if act is None: - if on_missing is not None: - # Use late import to avoid pulling logging deps at module load. - from agent_core.utils.logger import logger - - logger.warning(f"{on_missing}: action {name!r} not found in library") - continue - candidates.append(candidate_dict_from_action(act)) - return format_action_candidates(candidates) - - __all__ = [ "candidate_dict_from_action", "format_action_candidates", - "format_actions_by_name", ] diff --git a/agent_core/core/impl/action/__init__.py b/agent_core/core/impl/action/__init__.py index 369de6a9..626dbfd3 100644 --- a/agent_core/core/impl/action/__init__.py +++ b/agent_core/core/impl/action/__init__.py @@ -20,6 +20,7 @@ OnActionEndHook, GetParentIdHook, ) +from agent_core.core.impl.action.step import ActionCheck, AgentStep __all__ = [ # Executor @@ -37,4 +38,7 @@ "OnActionStartHook", "OnActionEndHook", "GetParentIdHook", + # Step + "ActionCheck", + "AgentStep", ] diff --git a/agent_core/core/impl/action/router.py b/agent_core/core/impl/action/router.py index b06d4393..7e59cc10 100644 --- a/agent_core/core/impl/action/router.py +++ b/agent_core/core/impl/action/router.py @@ -25,6 +25,7 @@ from agent_core.core.errors import ClassifiedError, ErrorCategory, ErrorInfo from agent_core.core.prompts import ( EVENT_STREAM_SUMMARY_ON_HISTORY_PROMPT, + NO_NEW_EVENTS_PROMPT, SELECT_ACTION_INSTRUCTIONS, SELECT_ACTION_PROMPT, decision_system_prompt, @@ -63,6 +64,39 @@ def _summary_from_reply(raw: Optional[str]) -> Optional[str]: return summary.strip() +def _first_json_object(text: str) -> Optional[Dict[str, Any]]: + """The first balanced ``{...}`` in ``text`` that parses as a JSON object, + scanning with string awareness so braces inside JSON strings don't + confuse the match. None when none parses.""" + start = text.find("{") + while start != -1: + depth, in_str, esc = 0, False, False + for i in range(start, len(text)): + ch = text[i] + if in_str: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == '"': + in_str = False + continue + if ch == '"': + in_str = True + elif ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + try: + obj = json.loads(text[start : i + 1]) + except json.JSONDecodeError: + break # try the next '{' + return obj if isinstance(obj, dict) else None + start = text.find("{", start + 1) + return None + + def _is_visible_in_mode(action, GUI_mode: bool) -> bool: """ Returns True if the action should be visible under the given GUI_mode. @@ -87,6 +121,12 @@ class ActionRouter: """ Selects actions based on user queries, with an LLM verifying correctness or creating new actions on the fly. + + The one decision loop of every agent: the main agent's sessions and each + sub-agent. What differs between them is their context (the context + engine: system prompt, session state, actions, event stream) and the two + prompt templates; the requests, retries, folds and session caching are + the same. """ def __init__( @@ -95,6 +135,10 @@ def __init__( llm_interface: LLMInterfaceProtocol, context_engine: ContextEngineProtocol, prompt_filter: Optional[Callable[[str], str]] = None, + *, + instructions: str = SELECT_ACTION_INSTRUCTIONS, + user_prompt: str = SELECT_ACTION_PROMPT, + prompt_name: str = "SELECT_ACTION", ): """ Initialize the router responsible for selecting or creating actions. @@ -106,11 +150,19 @@ def __init__( prompt_filter: Optional host hook applied to every rendered set of decision instructions, e.g. to drop a capability rule while that capability is unavailable. A failing filter is skipped. + instructions: Template of the decision instructions that end the + system prompt ({action_candidates}). + user_prompt: Template of a decision's user message + ({session_state}, {event_stream}, {query}). + prompt_name: Name the decision calls are captured under. """ self.action_library = action_library self.llm_interface = llm_interface self.context_engine = context_engine self.prompt_filter = prompt_filter + self.instructions = instructions + self.user_prompt = user_prompt + self.prompt_name = prompt_name # Per session: held while a decision is made, so a fold the user asks # for (fold_session) never lands while a request is in flight. self._decision_locks: Dict[str, asyncio.Lock] = {} @@ -215,11 +267,11 @@ def _decision_lock(self, session_id: Optional[str]) -> asyncio.Lock: def decision_instructions(self, session_id: Optional[str] = None) -> str: """The decision instructions of ``session_id`` as they render now: - SELECT_ACTION_INSTRUCTIONS with the session's list, through + the instructions template with the session's list, through the host's prompt_filter. They end the system prompt of the session's action-selection calls (ContextEngine.make_decision_system_prompt).""" # The session's list (fixed by its type) - compiled_actions = self._get_session_compiled_actions(session_id=session_id) + compiled_actions = self.context_engine.get_compiled_actions(session_id) # Use static compiled list - NO RAG SEARCH action_candidates = self._build_candidates_from_compiled_list( @@ -229,7 +281,7 @@ def decision_instructions(self, session_id: Optional[str] = None) -> str: f"ActionRouter using compiled action list: {len(action_candidates)} actions" ) return self._filter_prompt( - SELECT_ACTION_INSTRUCTIONS.format( + self.instructions.format( action_candidates=self._format_candidates(action_candidates) ) ) @@ -250,7 +302,7 @@ def _decision_prompt( ) -> str: """The user message of a decision call; without ``event_stream``, its static part.""" - return SELECT_ACTION_PROMPT.format( + return self.user_prompt.format( session_state=session_state, event_stream=event_stream, query=query, @@ -263,7 +315,7 @@ async def _select_action( # Build the instruction prompt for the LLM session_state, instructions = self._decision_inputs(session_id) - decision_prompt_name = "SELECT_ACTION" + decision_prompt_name = self.prompt_name static_prompt = self._decision_prompt(session_state, query) def render_prompt(up_to: Optional[int] = None) -> str: @@ -595,10 +647,14 @@ def full_request(up_to: Optional[int]) -> str: ) has_delta = True request_kind = "correction" + if not has_delta: + # Nothing logged since the last request: the + # history still holds everything, so the turn + # says so (a reset would resend it all uncached). + delta_events = NO_NEW_EVENTS_PROMPT if ( - has_delta - and not folded + not folded and render_prompt is not None and not self.llm_interface.fits_context( current_task_id, @@ -615,7 +671,9 @@ def full_request(up_to: Optional[int]) -> str: ) # The history in progress holds every event # being folded: the summary is written on it. - self._fold( + # The summary call blocks: off the event loop. + await to_thread_with_usage( + self._fold, stream, system_prompt, static_prompt, @@ -635,7 +693,7 @@ def full_request(up_to: Optional[int]) -> str: reason="fold", ) has_synced_before = False - elif has_delta: + else: # Send only the new events logger.info( f"[SESSION CACHE] Sending delta events for {call_type}" @@ -656,21 +714,6 @@ def full_request(up_to: Optional[int]) -> str: effective_session_id, point, ) - else: - # No new events - this could mean summarization happened - logger.info( - f"[SESSION CACHE] No delta events, resetting cache for {call_type}" - ) - self.llm_interface.reset_session_history( - current_task_id, call_type - ) - self.context_engine.reset_event_stream_sync( - call_type, - session_id=effective_session_id, - reason="no_delta", - ) - # Fall through to first-call path - has_synced_before = False if not has_synced_before: # First call with session - send full prompt to establish session. @@ -802,7 +845,9 @@ def full_request(up_to: Optional[int]) -> str: f"[SESSION CACHE] Request exceeded the context budget; folding " f"the event stream and retrying once for {call_type}" ) - self._fold(stream, system_prompt, static_prompt) + await to_thread_with_usage( + self._fold, stream, system_prompt, static_prompt + ) folded = True elif not stream.collapse_undelivered_oversize(): # Folded, and the new events have nothing left to shrink. @@ -913,11 +958,18 @@ def _parse_action_decision( try: parsed = ast.literal_eval(normalized) except Exception as eval_error: - logger.error(f"Unable to parse action decision: {repr(normalized)}") - return ( - None, - f"json error: {json_error}; literal_eval error: {eval_error}", - ) + # Models often wrap the object in prose or a code fence + # ("I'll click the pill next. {...}"); the object itself is + # the decision, so take it instead of spending a retry. + parsed = _first_json_object(normalized) + if parsed is None: + logger.error( + f"Unable to parse action decision: {repr(normalized)}" + ) + return ( + None, + f"json error: {json_error}; literal_eval error: {eval_error}", + ) if not isinstance(parsed, dict): logger.error(f"Parsed action decision is not a dict: {repr(normalized)}") @@ -1286,35 +1338,3 @@ def _build_candidates_from_compiled_list( ) return candidates - - def _get_session_compiled_actions( - self, session_id: Optional[str] = None - ) -> List[str]: - """ - Get the compiled action list from a session. - - Args: - session_id: Optional session ID for session-specific state lookup. - """ - # Try session-specific state first - state_session = get_session_or_none(session_id) - if state_session and state_session.current_session: - session = state_session.current_session - else: - # CRITICAL: Log warning when falling back to global state - # This could indicate a race condition in concurrent execution - if session_id: - logger.warning( - f"[ACTION_ROUTER] Session not found for session_id={session_id!r}, " - f"falling back to global STATE. This may cause context leakage " - f"across concurrent sessions!" - ) - session = get_state().current_session - - if ( - session - and hasattr(session, "compiled_actions") - and session.compiled_actions - ): - return session.compiled_actions - return [] diff --git a/agent_core/core/impl/action/step.py b/agent_core/core/impl/action/step.py new file mode 100644 index 00000000..1bc569f2 --- /dev/null +++ b/agent_core/core/impl/action/step.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +""" +AgentStep: the decide-and-prepare half of one agent turn. + +Shared by every agent loop: the main agent's session turn (AgentBase.react) +and each sub-agent's turn (app.subagent.runner). Each loop then runs the +prepared actions with ActionManager.execute_actions_parallel, under its own +checks. +""" + +from __future__ import annotations + +from typing import Any, Callable, Dict, List, Optional, Tuple + +from agent_core.core.event_stream.event import EventType +from agent_core.utils.logger import logger + +# A loop's check of one chosen action: (action_name, parameters) → why it +# may not run, or None. +ActionCheck = Callable[[str, Dict[str, Any]], Optional[str]] + + +class AgentStep: + """Decide a turn's actions and prepare them to run.""" + + def __init__(self, router, action_library, event_stream_manager): + self.router = router + self.action_library = action_library + self.event_stream_manager = event_stream_manager + + async def decide( + self, query: str, session_id: str + ) -> Tuple[List[Dict[str, Any]], str]: + """The turn's decision: the chosen actions and the reasoning behind + them. The reasoning goes into the session's event stream, where the + next request refers to the reply holding it instead of repeating it + (EventStream.get_delta_events).""" + decisions = await self.router.select_action_in_session( + query=query, session_id=session_id + ) + if not decisions: + raise ValueError("Action router returned no decision.") + + reasoning = decisions[0].get("reasoning", "") + logger.debug(f"[AGENT REASONING] {reasoning}") + if reasoning: + self.event_stream_manager.log( + "agent reasoning", + reasoning, + severity="DEBUG", + event_type=EventType.REASONING, + display_message=None, + task_id=session_id, + ) + return decisions, reasoning + + def prepare( + self, + decisions: List[Dict[str, Any]], + session_id: str, + check: Optional[ActionCheck] = None, + ) -> List[Tuple[Any, Dict[str, Any]]]: + """The decided actions with their parameters, ready to run. + + An action the router dropped (``_error``) or ``check`` refuses does + not run: the session's stream gets an action error saying why, so + the next turn sees it. + """ + prepared = [] + for decision in decisions: + action_name = decision.get("action_name") + action_params = decision.get("parameters", {}) + error = decision.get("_error") + if error is None and action_name and check is not None: + error = check(action_name, action_params) + + if error is not None: + logger.warning(f"Action '{action_name}' has error: {error}") + self.event_stream_manager.log( + kind="action_error", + message=f"Action {action_name} failed: {error}", + event_type=EventType.ACTION_END, + display_message=f"{action_name} → failed", + action_name=action_name, + action_output={"status": "error", "error": error}, + task_id=session_id, + ) + continue + + if not action_name: + continue + + action = self.action_library.retrieve_action(action_name) + if action is None: + logger.warning(f"Action '{action_name}' not found, skipping") + continue + + prepared.append((action, action_params)) + + return prepared + + +__all__ = ["ActionCheck", "AgentStep"] diff --git a/agent_core/core/impl/context/__init__.py b/agent_core/core/impl/context/__init__.py index 5cca8988..4c157786 100644 --- a/agent_core/core/impl/context/__init__.py +++ b/agent_core/core/impl/context/__init__.py @@ -3,11 +3,13 @@ Context engine implementations. This module provides the ContextEngine class for building LLM prompts -with hook-based customization for runtime-specific behavior. +with hook-based customization for runtime-specific behavior, and the +EventStreamContext it shares with every other context engine (a sub-agent's). """ -from agent_core.core.impl.context.engine import ContextEngine +from agent_core.core.impl.context.engine import ContextEngine, EventStreamContext __all__ = [ "ContextEngine", + "EventStreamContext", ] diff --git a/agent_core/core/impl/context/engine.py b/agent_core/core/impl/context/engine.py index 8252afa2..56639df4 100644 --- a/agent_core/core/impl/context/engine.py +++ b/agent_core/core/impl/context/engine.py @@ -12,7 +12,7 @@ - get_user_info_hook: For current user info (WCA only) """ -from typing import Optional, Dict, Any, Callable +from typing import Optional, Dict, Any, Callable, List from tzlocal import get_localzone @@ -35,7 +35,164 @@ from agent_core.utils.logger import logger -class ContextEngine: +class EventStreamContext: + """The event-stream half of a context engine: renders a session's stream + for a prompt and tracks how far its LLM session history has been sent. + + Everything is keyed by stream id, so the main agent's ContextEngine and a + sub-agent's context engine share it; ``event_stream_manager`` is the + manager holding the streams. + """ + + event_stream_manager: Any = None + + def get_event_stream( + self, session_id: Optional[str] = None, up_to: Optional[int] = None + ) -> str: + """Get the event stream content for inclusion in user prompts. + + Sessions are fully isolated: the prompt contains ONLY this session's + stream. There is no cross-session conversation history — long-term + memory (injected as relevant_memories events) is the only bridge + between sessions. + + Args: + session_id: Optional session ID for session-specific state lookup. + If provided, reads DIRECTLY from EventStreamManager's + per-session stream. Reading from StateSession.event_stream + would return a stale snapshot, not live events. + up_to: Only the first ``up_to`` tail events (the events a request + carries); None for all of them. + + Returns: + Formatted block for this session. + """ + sections = [] + + # Get the session's event stream + event_stream = None + + # CRITICAL: Read directly from EventStreamManager's per-session stream + if session_id: + try: + event_stream_manager = self.event_stream_manager + if event_stream_manager: + stream = event_stream_manager.get_stream_by_id(session_id) + if stream: + event_stream = stream.to_prompt_snapshot( + include_summary=True, up_to=up_to + ) + except Exception: + pass + else: + # No session: the current turn's stream, from global state + event_stream = get_state().event_stream + + if event_stream: + sections.append( + "\n" + "Use the event stream to understand the current situation and past agent actions:\n" + f"{event_stream}\n" + "" + ) + else: + sections.append("\n(no events yet)\n") + + return "\n\n".join(sections) + + def get_event_stream_delta( + self, + call_type: str, + session_id: Optional[str] = None, + up_to: Optional[int] = None, + ) -> tuple[str, bool]: + """Get only new events since the last session sync. + + Args: + call_type: Type of LLM call for delta tracking. + session_id: Optional session ID for session-specific stream lookup. + CRITICAL for concurrent task execution - without this, + events from other tasks may leak into this task's context. + up_to: Only events before this tail index (the events a request + carries); None for all of them. + """ + try: + event_stream_manager = self.event_stream_manager + + # Use session-specific stream if session_id provided + if session_id: + stream = event_stream_manager.get_stream_by_id(session_id) + else: + stream = event_stream_manager.get_stream() + + if not stream: + return "", False + + delta_str, has_delta = stream.get_delta_events(call_type, up_to=up_to) + return (delta_str, True) if has_delta else ("", False) + except Exception: + return "", False + + def mark_event_stream_synced( + self, + call_type: str, + session_id: Optional[str] = None, + up_to: Optional[int] = None, + ) -> None: + """Mark that the event stream has been synced to a session cache. + + Args: + call_type: Type of LLM call for sync tracking. + session_id: Optional session ID for session-specific stream lookup. + CRITICAL for concurrent task execution. + up_to: How many tail events the request carried; events logged + while it was in flight stay unsent. None: all of them. + """ + try: + event_stream_manager = self.event_stream_manager + + # Use session-specific stream if session_id provided + if session_id: + stream = event_stream_manager.get_stream_by_id(session_id) + else: + stream = event_stream_manager.get_stream() + + if stream: + stream.mark_session_synced(call_type, up_to=up_to) + except Exception: + pass + + def reset_event_stream_sync( + self, + call_type: str, + session_id: Optional[str] = None, + reason: str = "reset", + ) -> None: + """Reset the session sync point for the event stream. + + Args: + call_type: Type of LLM call for sync tracking. + session_id: Optional session ID for session-specific stream lookup. + CRITICAL for concurrent task execution. + reason: Why the session history starts anew (EventStream + .unsynced_reason); it labels the next full request. + """ + try: + event_stream_manager = self.event_stream_manager + + # Use session-specific stream if session_id provided + if session_id: + stream = event_stream_manager.get_stream_by_id(session_id) + else: + stream = event_stream_manager.get_stream() + + if stream: + stream.reset_session_sync(call_type, reason=reason) + except Exception: + pass + + +class ContextEngine(EventStreamContext): """Build structured prompts for the LLM from runtime state. The engine centralizes all context-building logic so callers can request a @@ -81,6 +238,11 @@ def __init__( self._get_chat_target_info = get_chat_target_info_hook or (lambda: "") self._get_user_info = get_user_info_hook or (lambda: "") + @property + def event_stream_manager(self): + """The sessions' event streams (EventStreamContext).""" + return self.state_manager.event_stream_manager + def set_memory_manager(self, memory_manager) -> None: """Set the memory manager for context retrieval.""" self._memory_manager = memory_manager @@ -351,152 +513,6 @@ def create_system_capability_catalog(self) -> str: # ─────────────── USER PROMPT DYNAMIC COMPONENTS ─────────────── - def get_event_stream( - self, session_id: Optional[str] = None, up_to: Optional[int] = None - ) -> str: - """Get the event stream content for inclusion in user prompts. - - Sessions are fully isolated: the prompt contains ONLY this session's - stream. There is no cross-session conversation history — long-term - memory (injected as relevant_memories events) is the only bridge - between sessions. - - Args: - session_id: Optional session ID for session-specific state lookup. - If provided, reads DIRECTLY from EventStreamManager's - per-session stream. Reading from StateSession.event_stream - would return a stale snapshot, not live events. - up_to: Only the first ``up_to`` tail events (the events a request - carries); None for all of them. - - Returns: - Formatted block for this session. - """ - sections = [] - - # Get the session's event stream - event_stream = None - - # CRITICAL: Read directly from EventStreamManager's per-session stream - if session_id: - try: - event_stream_manager = self.state_manager.event_stream_manager - if event_stream_manager: - stream = event_stream_manager.get_stream_by_id(session_id) - if stream: - event_stream = stream.to_prompt_snapshot( - include_summary=True, up_to=up_to - ) - except Exception: - pass - - # Fall back to global state only if no session_id or stream not found - if not event_stream: - event_stream = get_state().event_stream - - if event_stream: - sections.append( - "\n" - "Use the event stream to understand the current situation and past agent actions:\n" - f"{event_stream}\n" - "" - ) - else: - sections.append("\n(no events yet)\n") - - return "\n\n".join(sections) - - def get_event_stream_delta( - self, - call_type: str, - session_id: Optional[str] = None, - up_to: Optional[int] = None, - ) -> tuple[str, bool]: - """Get only new events since the last session sync. - - Args: - call_type: Type of LLM call for delta tracking. - session_id: Optional session ID for session-specific stream lookup. - CRITICAL for concurrent task execution - without this, - events from other tasks may leak into this task's context. - up_to: Only events before this tail index (the events a request - carries); None for all of them. - """ - try: - event_stream_manager = self.state_manager.event_stream_manager - - # Use session-specific stream if session_id provided - if session_id: - stream = event_stream_manager.get_stream_by_id(session_id) - else: - stream = event_stream_manager.get_stream() - - if not stream: - return "", False - - delta_str, has_delta = stream.get_delta_events(call_type, up_to=up_to) - return (delta_str, True) if has_delta else ("", False) - except Exception: - return "", False - - def mark_event_stream_synced( - self, - call_type: str, - session_id: Optional[str] = None, - up_to: Optional[int] = None, - ) -> None: - """Mark that the event stream has been synced to a session cache. - - Args: - call_type: Type of LLM call for sync tracking. - session_id: Optional session ID for session-specific stream lookup. - CRITICAL for concurrent task execution. - up_to: How many tail events the request carried; events logged - while it was in flight stay unsent. None: all of them. - """ - try: - event_stream_manager = self.state_manager.event_stream_manager - - # Use session-specific stream if session_id provided - if session_id: - stream = event_stream_manager.get_stream_by_id(session_id) - else: - stream = event_stream_manager.get_stream() - - if stream: - stream.mark_session_synced(call_type, up_to=up_to) - except Exception: - pass - - def reset_event_stream_sync( - self, - call_type: str, - session_id: Optional[str] = None, - reason: str = "reset", - ) -> None: - """Reset the session sync point for the event stream. - - Args: - call_type: Type of LLM call for sync tracking. - session_id: Optional session ID for session-specific stream lookup. - CRITICAL for concurrent task execution. - reason: Why the session history starts anew (EventStream - .unsynced_reason); it labels the next full request. - """ - try: - event_stream_manager = self.state_manager.event_stream_manager - - # Use session-specific stream if session_id provided - if session_id: - stream = event_stream_manager.get_stream_by_id(session_id) - else: - stream = event_stream_manager.get_stream() - - if stream: - stream.reset_session_sync(call_type, reason=reason) - except Exception: - pass - def get_session_state(self, session_id: Optional[str] = None) -> str: """Get the current session's state block for inclusion in user prompts. @@ -556,6 +572,35 @@ def get_session_state(self, session_id: Optional[str] = None) -> str: return "\n".join(lines) return "\n(session state unavailable)\n" + def get_compiled_actions(self, session_id: Optional[str] = None) -> List[str]: + """The actions a session prints in (Session.compiled_actions). + + Args: + session_id: Optional session ID for session-specific state lookup. + """ + # Try session-specific state first + state_session = get_session_or_none(session_id) + if state_session and state_session.current_session: + session = state_session.current_session + else: + # CRITICAL: Log warning when falling back to global state + # This could indicate a race condition in concurrent execution + if session_id: + logger.warning( + f"[CONTEXT_ENGINE] get_compiled_actions: Session not found for " + f"session_id={session_id!r}, falling back to global STATE. " + f"This may cause context leakage across concurrent sessions!" + ) + session = get_state().current_session + + if ( + session + and hasattr(session, "compiled_actions") + and session.compiled_actions + ): + return session.compiled_actions + return [] + def get_agent_state(self, session_id: Optional[str] = None) -> str: """Get the current agent state for inclusion in user prompts. diff --git a/agent_core/core/impl/event_stream/event_stream.py b/agent_core/core/impl/event_stream/event_stream.py index e9529734..62a617f2 100644 --- a/agent_core/core/impl/event_stream/event_stream.py +++ b/agent_core/core/impl/event_stream/event_stream.py @@ -905,11 +905,7 @@ def _extract_keywords(message: str, top_n: int = 5) -> List[str]: # ───────────────────────── prompt accessors ────────────────────────── def to_prompt_snapshot( - self, - include_summary: bool = True, - up_to: Optional[int] = None, - *, - message_overrides: Optional[Dict[Tuple[str, str], str]] = None, + self, include_summary: bool = True, up_to: Optional[int] = None ) -> str: """ Build a compact, human-readable history for inclusion in LLM prompts. @@ -923,8 +919,6 @@ def to_prompt_snapshot( include_summary: Whether to prepend the rolled-up ``head_summary``. up_to: Only the first ``up_to`` tail events (the events a request carries, see get_event_count); None for all of them. - message_overrides: Render-only substitutions keyed by exact event - kind and message. Stored events and cached messages are untouched. Returns: A newline-delimited string ready to embed in an LLM request. @@ -937,11 +931,7 @@ def to_prompt_snapshot( recent = self.tail_events[:up_to] if recent: lines.append("Recent Event: ") - overrides = message_overrides or {} - lines.extend( - r.compact_line(overrides.get((r.event.kind, r.event.message))) - for r in recent - ) + lines.extend(r.compact_line() for r in recent) return "\n".join(lines) if lines else "(no events)" diff --git a/agent_core/core/impl/event_stream/manager.py b/agent_core/core/impl/event_stream/manager.py index daf7d873..f47dac2a 100644 --- a/agent_core/core/impl/event_stream/manager.py +++ b/agent_core/core/impl/event_stream/manager.py @@ -17,7 +17,7 @@ from __future__ import annotations from datetime import datetime from pathlib import Path -from typing import Callable, Dict, List, Optional, Tuple +from typing import Callable, Dict, List, Optional import threading from agent_core.core.impl.event_stream.event_stream import EventStream @@ -183,16 +183,10 @@ def snapshot_main(self, include_summary: bool = True) -> str: include_summary=include_summary ) - def snapshot_by_id( - self, - session_id: str, - include_summary: bool = True, - *, - message_overrides: Optional[Dict[Tuple[str, str], str]] = None, - ) -> str: + def snapshot_by_id(self, session_id: str, include_summary: bool = True) -> str: """Snapshot a specific session's stream.""" return self.get_stream_by_id(session_id).to_prompt_snapshot( - include_summary=include_summary, message_overrides=message_overrides + include_summary=include_summary ) def get_all_streams(self) -> list[EventStream]: diff --git a/agent_core/core/models/chatgpt_subscription_client.py b/agent_core/core/models/chatgpt_subscription_client.py index 520470b2..1a1cd542 100644 --- a/agent_core/core/models/chatgpt_subscription_client.py +++ b/agent_core/core/models/chatgpt_subscription_client.py @@ -450,7 +450,7 @@ def _extract_first_json_object(text: str) -> Tuple[str, bool]: That trips CraftBot's per-call parser ("Extra data: line 1 column N"). Truncating to the first well-formed JSON object gives the - sub-agent runner exactly what it expects — one action per call — and + decision parser exactly what it expects — one decision per call — and the model can re-plan the next action on the next call. The chained JSONs beyond the first are effectively speculative planning tokens that get discarded. diff --git a/agent_core/core/prompts/__init__.py b/agent_core/core/prompts/__init__.py index c6742f54..1ceb699c 100644 --- a/agent_core/core/prompts/__init__.py +++ b/agent_core/core/prompts/__init__.py @@ -96,6 +96,10 @@ """ +# A session turn when nothing was logged since the last request: the history +# still holds everything, so the turn says so instead of resending it. +NO_NEW_EVENTS_PROMPT = "(no new events since your last turn)" + # Action selection prompts from agent_core.core.prompts.action import ( SELECT_ACTION_INSTRUCTIONS, @@ -138,6 +142,7 @@ # Event stream "EVENT_STREAM_SUMMARIZATION_PROMPT", "EVENT_STREAM_SUMMARY_ON_HISTORY_PROMPT", + "NO_NEW_EVENTS_PROMPT", # Action prompts "SELECT_ACTION_INSTRUCTIONS", "SELECT_ACTION_PROMPT", diff --git a/agent_core/core/protocols/context.py b/agent_core/core/protocols/context.py index 2ee987ec..41749977 100644 --- a/agent_core/core/protocols/context.py +++ b/agent_core/core/protocols/context.py @@ -6,7 +6,7 @@ interface for prompt construction. """ -from typing import Dict, Optional, Protocol, Tuple +from typing import Dict, List, Optional, Protocol, Tuple class ContextEngineProtocol(Protocol): @@ -50,6 +50,30 @@ def make_decision_system_prompt(self, session_id: Optional[str] = None) -> str: """ ... + def get_session_state(self, session_id: Optional[str] = None) -> str: + """ + Get the state block of a session's decision prompt. + + Args: + session_id: The session whose state to render. + + Returns: + Formatted session state string. + """ + ... + + def get_compiled_actions(self, session_id: Optional[str] = None) -> List[str]: + """ + Get the actions a session's decision prompt lists in . + + Args: + session_id: The session whose actions to list. + + Returns: + Action names. + """ + ... + def get_event_stream(self) -> str: """ Get formatted event stream. diff --git a/agent_core/core/protocols/event_stream.py b/agent_core/core/protocols/event_stream.py index 4d4bb52e..0468e1e5 100644 --- a/agent_core/core/protocols/event_stream.py +++ b/agent_core/core/protocols/event_stream.py @@ -5,7 +5,7 @@ This module defines protocols for event stream operations. """ -from typing import Dict, List, Optional, Protocol, Tuple, TYPE_CHECKING +from typing import List, Optional, Protocol, Tuple, TYPE_CHECKING if TYPE_CHECKING: from agent_core import EventRecord @@ -50,8 +50,6 @@ def to_prompt_snapshot( self, include_summary: bool = True, up_to: Optional[int] = None, - *, - message_overrides: Optional[Dict[Tuple[str, str], str]] = None, ) -> str: """ Build compact history for LLM prompts. @@ -59,7 +57,6 @@ def to_prompt_snapshot( Args: include_summary: Whether to include the head summary. up_to: Only include events before this index. - message_overrides: Render-only substitutions by exact kind and message. Returns: Formatted string of event history. diff --git a/app/agent_app/framework_verification.py b/app/agent_app/framework_verification.py index c7f8c71c..65d04530 100644 --- a/app/agent_app/framework_verification.py +++ b/app/agent_app/framework_verification.py @@ -96,21 +96,13 @@ def baseline(host, path): async def run_verification(host, row, stamp, request, parent_session_id): from app.internal_action_interface import InternalActionInterface as I - from app.logger import logger, add_subagent_log_sink, remove_subagent_log_sink - from app.subagent import SubAgentRunner - - parts = ( - I.subagent_manager, - I.action_manager, - I.action_library, - I.event_stream_manager, - I.llm_interface, - ) - if any(part is None for part in parts): + from app.logger import logger + + manager = I.subagent_manager + if manager is None: raise RuntimeError( "CraftBot's subagent runtime is unavailable; verification was not started." ) - manager, actions, library, events, llm = parts parent = host.agent.session_manager.get(parent_session_id) if parent is None or getattr(parent, "isolated_app_task", False): raise ValueError("Verification needs an existing owner conversation.") @@ -140,12 +132,7 @@ async def run_verification(host, row, stamp, request, parent_session_id): f"Installed skill source: {source}\nResolve relative references from: {source.parent}\n" f"--- BEGIN UNCHANGED FRAMEWORK SKILL ---\n{skill}\n--- END FRAMEWORK SKILL ---" ) - sub = manager.spawn( - "framework_walk_verify", - query, - parent_task_id=parent.id, - parent_temp_dir=parent.workspace_dir, - ) + sub = manager.spawn("framework_walk_verify", query, parent_session_id=parent.id) assignment = { "path": row["path"], "appId": row["id"], @@ -156,8 +143,6 @@ async def run_verification(host, row, stamp, request, parent_session_id): "status": "running", } token = verification_target.set(target) - agent_tag = f"sub:{sub.agent_type}:{sub.id.removeprefix('sub_')}" - sink = None def record(verdict, evidence): report = host.report_verification(sub.id, verdict, evidence) @@ -172,10 +157,7 @@ def record(verdict, evidence): sub.id, INCOMPLETE, "Independent verification is running." ) await host.changed() - runner = SubAgentRunner(manager, actions, library, events, llm) - sink = add_subagent_log_sink(agent_tag, parent.id) - with logger.contextualize(agent=agent_tag, session=parent.id): - await runner.run_to_completion(sub) + await manager.run(sub) try: result = json.loads(sub.result or "") verdict, evidence = result["verdict"], result["evidence"] @@ -214,14 +196,11 @@ def record(verdict, evidence): finally: target.active = False verification_target.reset(token) - if sink is not None: - remove_subagent_log_sink(sink) - # Also covers setup failures before the runner enters its own finally. - if events.has_stream(sub.id): - try: - manager.release(sub.id) - except Exception as error: - logger.warning(f"Verifier cleanup failed for {sub.id}: {error}") + # Covers setup failures before the run, which releases it itself. + try: + manager.release(sub.id) + except Exception as error: + logger.warning(f"Verifier cleanup failed for {sub.id}: {error}") host.store.put( "verification_session", sub.id, {**assignment, "status": sub.status} ) diff --git a/app/agent_base.py b/app/agent_base.py index fa3b1e99..687fe0be 100644 --- a/app/agent_base.py +++ b/app/agent_base.py @@ -33,6 +33,7 @@ from typing import Awaitable, Callable, Dict, Iterable, Optional from agent_core import ActionLibrary, ActionManager, ActionRouter +from agent_core.core.impl.action import AgentStep from agent_core import settings_manager, config_watcher from app.config import ( @@ -371,6 +372,11 @@ def __init__( self.context_engine, prompt_filter=self._filter_action_prompt, ) + # Decide and prepare a turn's actions: the same step every sub-agent + # runs (app.subagent.runner). + self.agent_step = AgentStep( + self.action_router, self.action_library, self.event_stream_manager + ) # Session caches register the system prompt decisions send, which # ends with the session's decision instructions. Set before any # session is created or restored below. @@ -456,6 +462,9 @@ def __init__( self.subagent_manager = SubAgentManager( event_stream_manager=self.event_stream_manager, llm_interface=self.llm, + action_library=self.action_library, + action_manager=self.action_manager, + session_manager=self.session_manager, ) # A stream is removed when a sub-agent finishes (its Mini Browser tabs # close) or a session is deleted (its browser and profile go). @@ -471,9 +480,6 @@ def __init__( memory_manager=self.memory_manager, context_engine=self.context_engine, subagent_manager=self.subagent_manager, - action_manager=self.action_manager, - action_library=self.action_library, - event_stream_manager=self.event_stream_manager, ) # ── misc ── @@ -768,9 +774,7 @@ async def react(self, trigger: Trigger) -> None: # ----- The one turn pipeline ----- action_decisions, reasoning = await self._select_action(trigger_data) - prepared_actions = await self._retrieve_and_prepare_actions( - action_decisions - ) + prepared_actions = self.agent_step.prepare(action_decisions, session_id) action_output = await self._execute_actions( prepared_actions, trigger_data, reasoning, session_id @@ -1185,8 +1189,8 @@ def _on_stream_removed(self, session_id: str, _stream: object) -> None: """Event-stream removal listener: a sub-agent finished (its Mini Browser tabs close) or a session was deleted (every path that deletes a session removes its stream: its browser closes for good and its - profile is deleted). Runs on the remover's thread (a sub-agent's pool - thread), so it only hands work off.""" + profile is deleted). Runs on the remover's thread, so it only hands + work off.""" self._notify_mini_browser("stream_removed", session_id) async def _shutdown_mini_browser(self) -> None: @@ -1270,79 +1274,20 @@ async def _select_action(self, trigger_data: TriggerData) -> tuple[list, str]: Reasoning is integrated into the action selection prompt, so this is a single LLM call. """ - action_decisions = await self.action_router.select_action_in_session( - query=trigger_data.query, - session_id=trigger_data.session_id, + action_decisions, reasoning = await self.agent_step.decide( + trigger_data.query, trigger_data.session_id ) # The decision request's context size and cache use are recorded on # the LLM interface now; send them to the chat input's reasoning menu. if self.ui_controller: await self.ui_controller.notify_session_updated(trigger_data.session_id) - - if not action_decisions: - raise ValueError("Action router returned no decision.") - - reasoning = action_decisions[0].get("reasoning", "") if action_decisions else "" - logger.debug(f"[AGENT REASONING] {reasoning}") - - if self.event_stream_manager and reasoning: - self.event_stream_manager.log( - "agent reasoning", - reasoning, - severity="DEBUG", - event_type=EventType.REASONING, - display_message=None, - task_id=trigger_data.session_id, - ) + if reasoning: self.state_manager.bump_event_stream() return action_decisions, reasoning # ----- Action Execution ----- - async def _retrieve_and_prepare_actions(self, action_decisions: list) -> list: - """ - Retrieve actions from library for a list of action decisions. - - Args: - action_decisions: List of action decision dicts from router. - - Returns: - List of Tuple (action, action_params) - """ - prepared = [] - for decision in action_decisions: - action_name = decision.get("action_name") - action_params = decision.get("parameters", {}) - - # Check if action was marked as error (e.g., dropped due to parallel constraints) - if "_error" in decision: - error_msg = decision.get("_error") - logger.warning(f"Action '{action_name}' has error: {error_msg}") - # Log to event stream so agent sees the error - if self.event_stream_manager: - self.event_stream_manager.log( - kind="action_error", - message=f"Action {action_name} failed: {error_msg}", - event_type=EventType.ACTION_END, - display_message=f"{action_name} → failed", - action_name=action_name, - action_output={"status": "error", "error": error_msg}, - ) - continue - - if not action_name: - continue - - action = self.action_library.retrieve_action(action_name) - if action is None: - logger.warning(f"Action '{action_name}' not found, skipping") - continue - - prepared.append((action, action_params)) - - return prepared - @profile("agent_execute_actions", OperationCategory.AGENT_LOOP) async def _execute_actions( self, @@ -1683,8 +1628,8 @@ async def request_run_stop(self, session_id: str, *, framework_task_key=None) -> ) self._emit_run_state(session_id, "stopping") # Stop the session's browser work first: in-flight Mini Browser ops - # are cancelled and its sub-agents (which a turn cancel never reaches, - # they run on their own threads) lose browser access for good. + # are cancelled and its sub-agents lose browser access for good (the + # turn cancel below also cancels a sub-agent the turn is running). self._notify_mini_browser("cancel_owner", session_id, include_children=True) try: stopped = await self.session_runtime.request_stop( diff --git a/app/data/action/spawn_subagent.py b/app/data/action/spawn_subagent.py index 586ffcc7..820de20b 100644 --- a/app/data/action/spawn_subagent.py +++ b/app/data/action/spawn_subagent.py @@ -101,14 +101,9 @@ "simulated_mode": True, }, ) -def spawn_subagent(input_data: dict) -> dict: +async def spawn_subagent(input_data: dict) -> dict: # Imports inside the function — required by the action runtime model. - import asyncio - from app.internal_action_interface import InternalActionInterface - from app.logger import logger, add_subagent_log_sink, remove_subagent_log_sink - from app.subagent.runner import SubAgentRunner - from app.subagent.types import SUBAGENT_TERMINAL_STATUSES if input_data.get("simulated_mode"): return { @@ -131,33 +126,8 @@ def spawn_subagent(input_data: dict) -> dict: "message": "query is required and must be self-contained.", } - # ActionManager injects _session_id; for spawn_subagent this is the - # PARENT session's id (recorded on the SubAgent for traceability). - parent_task_id = input_data.get("_session_id") - - # Resolve the parent session's workspace dir so the child's event stream - # can externalize oversized action outputs (same mechanism as the main - # agent). Falls back to None (externalization off) when spawned outside - # a session or the session has no workspace dir. - parent_temp_dir = None - if parent_task_id and InternalActionInterface.session_manager is not None: - parent_session = InternalActionInterface.session_manager.get(parent_task_id) - if parent_session is not None: - parent_temp_dir = getattr(parent_session, "workspace_dir", None) or None - - mgr = InternalActionInterface.subagent_manager - action_manager = InternalActionInterface.action_manager - action_library = InternalActionInterface.action_library - llm = InternalActionInterface.llm_interface - event_stream_manager = InternalActionInterface.event_stream_manager - - if ( - mgr is None - or action_manager is None - or action_library is None - or llm is None - or event_stream_manager is None - ): + manager = InternalActionInterface.subagent_manager + if manager is None: return { "status": "error", "result": "", @@ -165,57 +135,16 @@ def spawn_subagent(input_data: dict) -> dict: } try: - sub = mgr.spawn( - agent_type=agent_type, - query=query, - parent_task_id=parent_task_id, - parent_temp_dir=parent_temp_dir, + # ActionManager injects _session_id: the spawning session's id. + sub = manager.spawn( + agent_type, query, parent_session_id=input_data.get("_session_id") ) except ValueError as e: return {"status": "error", "result": "", "message": str(e)} - runner = SubAgentRunner( - subagent_manager=mgr, - action_manager=action_manager, - action_library=action_library, - event_stream_manager=event_stream_manager, - llm_interface=llm, - ) - - # The runner's ``finally`` block always calls ``mgr.release(sub.id)``, - # which drops the per-sub-agent event stream and session caches. By the - # time control returns here, those resources are gone — so on a crash - # path we MUST NOT call ``mgr.end()`` (its ``subagent_end`` log would - # have nowhere valid to go and would leak into the parent's main - # stream). Update ``sub`` in memory instead. - # - # The action body runs inside ``ActionExecutor``'s thread pool — there - # is no event loop in that thread, so ``asyncio.run`` is the correct - # entry point (nest_asyncio compatibility is irrelevant here). - # Tag every log line emitted while this sub-agent runs with its identity, and - # route them to a dedicated file. contextualize sets a contextvar that - # asyncio.run copies into the new loop, so the runner, ActionManager, LLM - # interface and action code all log under "sub::"; the per-agent - # sink (filtered on that tag) captures them into /sub__.log. - short_id = sub.id[4:] if sub.id.startswith("sub_") else sub.id - agent_tag = f"sub:{sub.agent_type}:{short_id}" - # Nest the sub-agent's log file inside its parent session's folder and - # attribute its lines to that session (so all.log / the session's own log - # carry the right session tag). The per-agent sink filters on agent_tag, - # so the sub-agent's lines land in //.log. - log_session = parent_task_id or "main" - sink_id = add_subagent_log_sink(agent_tag, log_session) - try: - with logger.contextualize(agent=agent_tag, session=log_session): - try: - asyncio.run(runner.run_to_completion(sub)) - except Exception as e: - logger.exception(f"[spawn_subagent] runner crashed for {sub.id}: {e}") - if sub.status not in SUBAGENT_TERMINAL_STATUSES: - sub.status = "error" - sub.result = f"(sub-agent runner crashed: {e})" - finally: - remove_subagent_log_sink(sink_id) + # An async action runs on the spawning turn's event loop, so stopping + # that run cancels the sub-agent with it. + await manager.run(sub) return { "status": sub.status, diff --git a/app/errors/codebook.py b/app/errors/codebook.py index e61231b7..d0abaeb9 100644 --- a/app/errors/codebook.py +++ b/app/errors/codebook.py @@ -90,12 +90,6 @@ def _settings_action(**_kwargs) -> List[ErrorAction]: title="Proxy request failed", message_template="{detail}", ), - "SUBAGENT_TIMEOUT": _Spec( - category=ErrorCategory.CONNECTION, - severity=Severity.ERROR, - title="Sub-agent call timed out", - message_template="The sub-agent LLM call did not respond within {timeout}s.", - ), } diff --git a/app/internal_action_interface.py b/app/internal_action_interface.py index 9d7a3094..2fe5dfdc 100644 --- a/app/internal_action_interface.py +++ b/app/internal_action_interface.py @@ -31,9 +31,6 @@ from app.scheduler import SchedulerManager from app.proactive import ProactiveManager from app.subagent.manager import SubAgentManager - from app.event_stream import EventStreamManager - from agent_core.core.impl.action.manager import ActionManager - from agent_core.core.impl.action.library import ActionLibrary _SET_NAME_SEPARATORS = re.compile(r"[\s_\-]+") @@ -255,9 +252,6 @@ class InternalActionInterface: # Sub-agent runtime — set during AgentBase.__init__. Used by # spawn_subagent / sub_task_end actions. subagent_manager: Optional["SubAgentManager"] = None - action_manager: Optional["ActionManager"] = None - action_library: Optional["ActionLibrary"] = None - event_stream_manager: Optional["EventStreamManager"] = None @classmethod def initialize( @@ -273,9 +267,6 @@ def initialize( scheduler: Optional["SchedulerManager"] = None, ui_adapter: Optional[Any] = None, subagent_manager: Optional["SubAgentManager"] = None, - action_manager: Optional["ActionManager"] = None, - action_library: Optional["ActionLibrary"] = None, - event_stream_manager: Optional["EventStreamManager"] = None, ): """ Register the shared interfaces that actions depend on. @@ -295,9 +286,6 @@ def initialize( cls.scheduler = scheduler cls.ui_adapter = ui_adapter cls.subagent_manager = subagent_manager - cls.action_manager = action_manager - cls.action_library = action_library - cls.event_stream_manager = event_stream_manager @classmethod def set_ui_adapter(cls, ui_adapter: Any) -> None: diff --git a/app/logger.py b/app/logger.py index 87942ba2..a69b34dc 100644 --- a/app/logger.py +++ b/app/logger.py @@ -78,8 +78,9 @@ def define_log_level(print_level="ERROR", logfile_level="DEBUG", name: str = Non # ("main") and the main agent ("main"). Each session's consumer loop wraps # its turns in ``logger.contextualize(session=)`` so every line emitted # during a turn — including downstream ActionManager / LLM / action-code - # logs — is tagged with the session that produced it. The sub-agent runner - # additionally wraps its run in ``logger.contextualize(agent="sub:...")``. + # logs — is tagged with the session that produced it. A sub-agent's run + # additionally runs in ``logger.contextualize(agent="sub:...")`` + # (SubAgentManager.run). _logger.configure(extra={"agent": "main", "session": _MAIN_SESSION_ID}) # all.log — the full interleaved timeline across every session and every diff --git a/app/mini_browser/config.py b/app/mini_browser/config.py index 622e2d97..1899b7c3 100644 --- a/app/mini_browser/config.py +++ b/app/mini_browser/config.py @@ -452,7 +452,7 @@ def subagent_record( return None if sub is None: return None - parent = getattr(sub, "parent_task_id", None) + parent = getattr(sub, "parent_session_id", None) agent_type = getattr(sub, "agent_type", None) created: Optional[datetime] = None raw = getattr(sub, "created_at", None) diff --git a/app/mini_browser/host.py b/app/mini_browser/host.py index 4be0b142..9c390ce4 100644 --- a/app/mini_browser/host.py +++ b/app/mini_browser/host.py @@ -1,9 +1,8 @@ """The Mini Browser's own thread and event loop. Playwright objects belong to the event loop that created them, but Mini -Browser callers live on several loops: the main agent/UI loop, and each -sub-agent's private loop (``spawn_subagent`` runs ``asyncio.run`` in a worker -thread). So the browsers get one home: a daemon thread named ``mini-browser`` +Browser callers are not all on one loop or thread (the agent's loop, hooks +called from other threads). So the browsers get one home: a daemon thread named ``mini-browser`` running its own loop. Every Playwright object, lock and background task of every session's browser lives there, and callers marshal into it with :meth:`call` (one session's browser) or :meth:`call_fleet` (all of them), diff --git a/app/mini_browser/lifecycle.py b/app/mini_browser/lifecycle.py index fb496362..25072602 100644 --- a/app/mini_browser/lifecycle.py +++ b/app/mini_browser/lifecycle.py @@ -1,8 +1,7 @@ """Hooks the agent runtime calls into the Mini Browser. Called by ``AgentBase`` (run state changes, Stop, deleted sessions, finished -sub-agents, settings changes, shutdown), possibly from other threads (a -sub-agent finishing on its worker thread). Every hook is thread-safe, returns +sub-agents, settings changes, shutdown), possibly from other threads. Every hook is thread-safe, returns immediately, never starts a browser and never raises: when a session's browser was never used there is nothing to do. Every session has a browser of its own (``fleet.py``); a hook about a sub-agent goes to its parent @@ -80,9 +79,12 @@ def release_owner(owner: str) -> None: if not _valid(owner): return forget_owner(owner) + # Resolved now: the sub-agent's record is dropped right after this hook, + # before the browser thread runs ``apply``. + key = config.browser_key(owner) async def apply(fleet: Any) -> None: - core = fleet.existing(config.browser_key(owner)) + core = fleet.existing(key) if core is not None: core.release_owner(owner, close_tabs=True) diff --git a/app/subagent/__init__.py b/app/subagent/__init__.py index 76a19320..3739da01 100644 --- a/app/subagent/__init__.py +++ b/app/subagent/__init__.py @@ -2,41 +2,29 @@ """ Sub-agent system for CraftBot. -A sub-agent is a lightweight, isolated agent that the main agent (or a -task) can spawn through the ``spawn_subagent`` action to do a focused job -in its own context. - -Key isolation properties: - -- Sub-agents are NOT Tasks. They live in :class:`SubAgentManager`, not in - ``TaskManager.tasks``, so none of the UI / chatserver / SessionStorage - side effects fire. -- Each sub-agent has its own per-id event stream (via the existing - ``EventStreamManager._task_streams`` buffer) and its own LLM session - caches keyed on the sub-agent id. -- Each sub-agent type has a hard-coded action list and a minimal, - type-specific system prompt — no memory, no skills, no soul.md. - -Only ``result`` is fed back to the spawning agent as the action output. - -Per-type configuration (system prompt, allowed actions, runtime caps) is -defined one file per type under :mod:`app.subagent.definitions`. Importing -this package triggers all those modules to register themselves with -:mod:`app.subagent.registry`. +A sub-agent is an isolated agent that a session's turn spawns through the +``spawn_subagent`` action (or the Agent-App verifier) to do one focused job +in its own context. It works like the main agent — the same decision loop +(ActionRouter), turn step (AgentStep) and action execution — on a context of +its own: + +- its type's system prompt and actions (:mod:`app.subagent.definitions`), + nothing of the main agent's persona, memory or skills; +- its own event stream and LLM session history, keyed on the sub-agent id; +- only the query from its parent, and only its ``result`` back. + +Sub-agents are NOT Sessions: they live in :class:`SubAgentManager`, so none +of the UI / chatserver / SessionStorage side effects fire. Importing this +package registers every type in :mod:`app.subagent.definitions`. """ -from app.subagent.types import ( - SubAgent, - SUBAGENT_MODE, - SUBAGENT_TERMINAL_STATUSES, -) +from app.subagent.types import SubAgent from app.subagent.registry import ( SUB_TASK_END_ACTION, SubAgentDefinition, register_subagent, get_subagent_definition, list_subagent_names, - is_subagent_registered, ) # Importing the definitions package runs each definition module, which @@ -44,26 +32,22 @@ # ``list_subagent_names()`` returns every registered type. from app.subagent import definitions # noqa: F401 -from app.subagent.manager import SubAgentManager -from app.subagent.context_engine import SubAgentContextEngine, SUBAGENT_OUTPUT_FORMAT +from app.subagent.context_engine import SubAgentContextEngine from app.subagent.runner import SubAgentRunner +from app.subagent.manager import SubAgentManager __all__ = [ - # Runtime types + # Runtime record "SubAgent", - "SUBAGENT_MODE", - "SUBAGENT_TERMINAL_STATUSES", # Registry "SUB_TASK_END_ACTION", "SubAgentDefinition", "register_subagent", "get_subagent_definition", "list_subagent_names", - "is_subagent_registered", # Components - "SubAgentManager", "SubAgentContextEngine", "SubAgentRunner", - "SUBAGENT_OUTPUT_FORMAT", + "SubAgentManager", ] diff --git a/app/subagent/context_engine.py b/app/subagent/context_engine.py index 1e7f1aab..5006c134 100644 --- a/app/subagent/context_engine.py +++ b/app/subagent/context_engine.py @@ -1,93 +1,111 @@ # -*- coding: utf-8 -*- """ -SubAgentContextEngine — minimal prompt builder for sub-agents. - -This is a small, focused replacement for ``ContextEngine.make_prompt()`` -that intentionally OMITS: -- agent role / persona prompts -- soul.md -- user profile -- memory retrieval -- selected skills -- environmental context -- conversation history -- main task state / todos -- LANGUAGE_INSTRUCTION - -A sub-agent sees only: -- its type-specific system prompt (with the action list and the shared - output-format contract interpolated) -- its query -- its own per-sub-agent event log snapshot - -Prompts are split across three methods so the runner can drive session -caching: - -- :meth:`make_system_prompt` — stable across all turns; serves as the - session-cache "prefix". -- :meth:`make_first_turn_user_prompt` — query + initial event log + nudge. -- :meth:`make_delta_user_prompt` — only the events added since the previous - turn + nudge. Used on every turn after the first when session caching is - active. +SubAgentContextEngine — the context of one sub-agent's decisions. + +A sub-agent decides with the main agent's ActionRouter (see +:mod:`app.subagent.runner`); this engine and the two templates below are +what make that router a sub-agent's. The router gets from it: + +- the system prompt: the type's own prompt (its definition), the + externalized-output note when the type has the retrieval actions, and the + environment with the current DATE. Built once per run, so the cached + prefix never moves. The router appends SUBAGENT_DECISION_INSTRUCTIONS + (batching rules, reply format, ). +- the session state: the type and its budget, shown in the first user + message after the query (SUBAGENT_DECISION_PROMPT). +- the actions: the definition's list (sub_task_end included). +- the event stream: the sub-agent's own (EventStreamContext). + +Deliberately absent: persona, soul, user profile, memory, skills, the +capability catalog and anything else of the spawning session. The only +thing a sub-agent knows of its parent is the query. """ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, List, Optional, Tuple -from agent_core.core.action_framework import format_actions_by_name +from agent_core.core.impl.context.engine import EventStreamContext from agent_core.core.prompts import ENVIRONMENTAL_CONTEXT_PROMPT from app.subagent.registry import get_subagent_definition from app.subagent.types import SubAgent if TYPE_CHECKING: - from agent_core.core.impl.action.library import ActionLibrary from app.event_stream import EventStreamManager -# Shared output-format contract injected into every sub-agent's system -# prompt via the ``{output_format}`` placeholder. This is the wire format -# the runner expects back on every turn — keep it stable. -SUBAGENT_OUTPUT_FORMAT = """\ -On every turn you MUST reply with ONLY a JSON object in this exact shape: - -{ - "reasoning": "", - "action_name": "", - "parameters": { } -} - -No prose, no markdown fences, no extra keys. One action per turn. +# The decision instructions ending every sub-agent's system prompt +# (ActionRouter ``instructions``): how to batch, the reply format and the +# type's . The reply format is the main agent's. +SUBAGENT_DECISION_INSTRUCTIONS = """ +Batch up to 20 actions in one turn ONLY when none depends on another's output +(e.g. several read_file / grep_files / web_search / web_fetch calls). +A non-parallelizable action MUST be the ONLY action in its turn; sub_task_end +is one. +NEVER batch two write_file/stream_edit actions on the SAME file — they are +planned against one snapshot, so the second's anchor is stale once the first +applies (corrupts the file). Edit the same file in SEPARATE turns. + + + +Return ONLY a valid JSON object with this structure and no extra commentary: +{{ + "reasoning": "", + "actions": [ + {{ + "action_name": "", + "parameters": {{ + "": + }} + }} + ] +}} + +For parallel actions, include multiple entries in the "actions" array. +For a single action, use an array with one entry. + + + +Your actions, each with its description and input schema. You cannot use any other: +{action_candidates} +""" + +# The first user message of a sub-agent's session history (ActionRouter +# ``user_prompt``). KV CACHING: the query and the budget are static, the +# event stream is append-only; later turns send only new events. +SUBAGENT_DECISION_PROMPT = """QUERY FROM SPAWNING AGENT: +{query} + +{session_state} + +{event_stream} + + +Reason about where the query stands, then select the next action(s) with +their input parameters, or end with sub_task_end once it is done. + """ -_DECIDE_NUDGE = "Decide your next action now. Reply with the JSON object only." - # Appended to the system prompt of any sub-agent type whose action list # includes the retrieval pair (grep_files / read_file). Oversized action # outputs are externalized by the event stream (EventStream._externalize_message) -# into files under the sub-agent's temp dir; this note teaches the model the -# retrieval protocol. Kept out of SUBAGENT_OUTPUT_FORMAT because it only -# applies when the retrieval actions are actually available. -_EXTERNALIZED_OUTPUT_NOTE = """ -EXTERNALIZED OUTPUTS: +# into files under the sub-agent's workspace; this note teaches the model the +# retrieval protocol. +_EXTERNALIZED_OUTPUT_NOTE = """EXTERNALIZED OUTPUTS: When an action's output is very large, your event log will show a pointer line ("... saved in ... | keywords: ...") instead of the content. The full output is in that file — it is NOT lost and you must NOT re-run the action to get it back. Use grep_files on the file with the listed keywords (or your own search terms) to pull just the relevant lines; use read_file -with offset/limit only when you need a specific region in full. -""" +with offset/limit only when you need a specific region in full.""" _RETRIEVAL_ACTIONS = ("grep_files", "read_file") def _render_environment_block() -> str: - """Render a static environment + current-DATE block for the sub-agent - system prompt. Date only — no time. A date does not change during a - short-lived sub-agent's run, so it stays byte-stable across all turns and - keeps the system-prompt prefix cacheable (a wall-clock time would move the - prefix every turn and break automatic prefix caching). - """ + """The environment and current DATE block of a sub-agent's system + prompt. Date only, no time: a wall-clock time would move the cached + prefix every turn.""" import platform from datetime import datetime @@ -110,93 +128,55 @@ def _render_environment_block() -> str: return f"{environment}\n{current_date}" -class SubAgentContextEngine: - """Builds prompt pieces for sub-agent LLM calls.""" +class SubAgentContextEngine(EventStreamContext): + """The context engine of one sub-agent's ActionRouter.""" def __init__( - self, - action_library: "ActionLibrary", - event_stream_manager: "EventStreamManager", - ): - self.action_library = action_library + self, sub: SubAgent, event_stream_manager: "EventStreamManager" + ) -> None: + self.sub = sub self.event_stream_manager = event_stream_manager - - # ------------------------------------------------------------------ - # System prompt (stable across all turns — session-cache "prefix") - # ------------------------------------------------------------------ - - def make_system_prompt(self, sub: SubAgent) -> str: - """Build the type-specific system prompt for ``sub``. - - Pulls the template from the registered :class:`SubAgentDefinition` - and fills in: - - ``{action_list}`` — compact JSON description of the allowed actions - - ``{output_format}`` — shared :data:`SUBAGENT_OUTPUT_FORMAT` block - - Stable across all turns of a given sub-agent; suitable as - ``system_prompt_for_new_session`` when calling - ``LLMInterface.generate_response_with_session_async``. - """ - defn = get_subagent_definition(sub.agent_type) - action_list_str = format_actions_by_name( - sub.compiled_actions, - self.action_library, - on_missing="[SubAgentContextEngine]", - ) - prompt = defn.system_prompt.format( - action_list=action_list_str, - output_format=SUBAGENT_OUTPUT_FORMAT, - ) + self.definition = get_subagent_definition(sub.agent_type) + parts = [self.definition.system_prompt.strip()] if any(a in sub.compiled_actions for a in _RETRIEVAL_ACTIONS): - prompt += _EXTERNALIZED_OUTPUT_NOTE - prompt += f"\n{_render_environment_block()}" - return prompt + parts.append(_EXTERNALIZED_OUTPUT_NOTE) + parts.append(_render_environment_block()) + self._system_prompt = "\n\n".join(parts) - # ------------------------------------------------------------------ - # User prompts - # ------------------------------------------------------------------ - - def make_first_turn_user_prompt(self, sub: SubAgent) -> str: - """First-turn user prompt: query + initial event log + decision nudge.""" - event_log = self._snapshot_event_log(sub) + def make_prompt( + self, + query: Optional[str] = None, + expected_format: Optional[str] = None, + system_flags: Optional[dict] = None, + user_flags: Optional[dict] = None, + ) -> Tuple[str, str]: + """The system prompt, before the decision instructions. A sub-agent's + has no optional sections, so the flags change nothing; the user + message is the router's (SUBAGENT_DECISION_PROMPT).""" + return self._system_prompt, "" + + def get_session_state(self, session_id: Optional[str] = None) -> str: + """The type and its budget. Models without a stated budget invent + scarcity: a verifier with 50 turns concluded at turn 8 citing + 'limited turns' (observed 2026-08-05).""" + definition = self.definition return ( - f"QUERY FROM SPAWNING AGENT:\n{sub.query}\n\n" - f"YOUR EVENT LOG SO FAR (most recent last):\n{event_log}\n\n" - f"{_DECIDE_NUDGE}" + "\n" + f"Type: {definition.name}\n" + f"Budget: up to {definition.max_iterations} turns and " + f"{definition.max_wall_seconds // 60} minutes. A turn can batch " + "several independent actions. Pace yourself by these numbers, not " + "by guesswork.\n" + "" ) - def make_delta_user_prompt(self, delta_events: str) -> str: - """Subsequent-turn user prompt: only the new events + decision nudge. - - Used when session caching is active and the LLM interface has the - prior conversation cached server-side. The original query and earlier - event log are already in the cached history; we only need to append - what's new. - """ - body = delta_events.strip() or "(no new events since last turn)" - return f"NEW EVENTS SINCE LAST TURN:\n{body}\n\n{_DECIDE_NUDGE}" - - # ------------------------------------------------------------------ - # Helpers - # ------------------------------------------------------------------ - - def _snapshot_event_log(self, sub: SubAgent) -> str: - # The complete current query is above this snapshot, including after - # a fold or restore. Abbreviate only an exact match; never edit storage. - return ( - self.event_stream_manager.snapshot_by_id( - sub.id, - include_summary=True, - message_overrides={ - ( - "subagent_start", - sub.bootstrap_message, - ): f"Sub-agent of type '{sub.agent_type}' started. " - "Query: see QUERY FROM SPAWNING AGENT above." - }, - ) - or "(no events yet)" - ) + def get_compiled_actions(self, session_id: Optional[str] = None) -> List[str]: + """The definition's actions, sub_task_end included.""" + return list(self.sub.compiled_actions) -__all__ = ["SubAgentContextEngine", "SUBAGENT_OUTPUT_FORMAT"] +__all__ = [ + "SUBAGENT_DECISION_INSTRUCTIONS", + "SUBAGENT_DECISION_PROMPT", + "SubAgentContextEngine", +] diff --git a/app/subagent/definitions/__init__.py b/app/subagent/definitions/__init__.py index 94c2ff08..f0657a8c 100644 --- a/app/subagent/definitions/__init__.py +++ b/app/subagent/definitions/__init__.py @@ -10,7 +10,9 @@ 1. Create ``app/subagent/definitions/your_agent.py`` modeled on the existing files (system prompt, actions list, caps, single - :func:`register_subagent` call at module level). + :func:`register_subagent` call at module level). The prompt is the + type's role, workflow, rules and ending only: the runtime appends the + decision instructions (batching rules, reply format, ). 2. Add ``from app.subagent.definitions import your_agent`` to the imports below so it loads on package import. @@ -25,4 +27,3 @@ from app.subagent.definitions import general_agent # noqa: F401 from app.subagent.definitions import framework_walk_verify # noqa: F401 from app.subagent.definitions import browser_agent # noqa: F401 -# from app.subagent.definitions import validation_agent # noqa: F401 diff --git a/app/subagent/definitions/browser_agent.py b/app/subagent/definitions/browser_agent.py index fb8ce98f..6167e7fd 100644 --- a/app/subagent/definitions/browser_agent.py +++ b/app/subagent/definitions/browser_agent.py @@ -37,12 +37,6 @@ You have no memory of past conversations and see nothing of the spawning agent's context beyond the query. -ALLOWED ACTIONS (you cannot use anything else): -{action_list} - -Every action call must be: -{{"action_name": "", "parameters": {{...all required fields...}}}} - HOW THE BROWSER WORKS: - Every mini_browser result carries a fresh 'page' observation: url, title, numbered interactive elements such as [12] button "Add to cart", and the @@ -81,9 +75,7 @@ R5. Stuck (same error twice, element missing, page not loading)? Re-read the page, scroll, or take another path (site search, another link, a direct URL). After three failed approaches, end with status="failed". -R6. Only your latest few page observations stay in your context: use facts - as you find them and finish as soon as the query is answered. -R7. Close the extra tabs you opened (mini_browser_tabs action='close') +R6. Close the extra tabs you opened (mini_browser_tabs action='close') before ending. ENDING: @@ -91,8 +83,6 @@ did, facts verbatim with source URLs, plus any screenshot file paths. - sub_task_end status="failed": `result` says what blocked you, what you tried, and the URL you were on. - -{output_format} """ @@ -122,26 +112,9 @@ "grep_files", "read_file", ], - # One action per turn: a short task is navigate → search → open → read - # → answer, a form or comparison takes a few dozen steps. + # Browser actions run one per turn (none is parallelizable): a short + # task is navigate → search → open → read → answer, a form or + # comparison takes a few dozen steps. max_iterations=50, max_wall_seconds=1200, - # Every mini_browser result carries a page observation superseded by - # the next one; keep the newest few and rebuild the provider session - # periodically so stubbed observations actually leave the context. - compact_actions=( - "mini_browser_read", - "mini_browser_navigate", - "mini_browser_click", - "mini_browser_type", - "mini_browser_press_key", - "mini_browser_select_option", - "mini_browser_hover", - "mini_browser_scroll", - "mini_browser_wait", - "mini_browser_upload_file", - "mini_browser_tabs", - ), - compact_keep=3, - session_reset_every=10, ) diff --git a/app/subagent/definitions/framework_walk_verify.py b/app/subagent/definitions/framework_walk_verify.py index 3c497805..480a0a8e 100644 --- a/app/subagent/definitions/framework_walk_verify.py +++ b/app/subagent/definitions/framework_walk_verify.py @@ -35,9 +35,6 @@ def _valid_result(sub, parameters): Follow that skill and its referenced quality standard; do not replace them with CraftBot's legacy app checklist. -ALLOWED ACTIONS: -{action_list} - Use your own Mini Browser tabs for the real UI walk, and describe_image for screenshots. Use the assigned app directory with a2app_command for operation discovery and API tests on the DEV instance. @@ -54,8 +51,6 @@ def _valid_result(sub, parameters): with actual checks, findings and evidence paths). Only claim pass when every required check passed. CraftBot records this result against the assigned validation stamp and returns it to the builder; do not call the verdict-reporting action. - -{output_format} """, actions=[ "mini_browser_navigate", @@ -82,12 +77,4 @@ def _valid_result(sub, parameters): max_iterations=100, max_wall_seconds=1800, early_end_guard=_valid_result, - compact_actions=( - "mini_browser_read", - "mini_browser_navigate", - "mini_browser_click", - "mini_browser_screenshot", - ), - compact_keep=3, - session_reset_every=10, ) diff --git a/app/subagent/definitions/general_agent.py b/app/subagent/definitions/general_agent.py index e23fa18f..782acd3e 100644 --- a/app/subagent/definitions/general_agent.py +++ b/app/subagent/definitions/general_agent.py @@ -16,9 +16,6 @@ edit assigned files and run commands. You have no access to the parent's conversation, memory, skills or task state beyond the query. -ALLOWED ACTIONS: -{action_list} - WORKFLOW: 1. Read the query's objective, inputs, constraints, file ownership and expected output. If essential information is missing, end as failed @@ -55,8 +52,6 @@ parent's requested output format; omit sections that do not apply. - status="failed": result explains the blocker, what you tried, and any files already changed or partial output. Failure does not undo changes. - -{output_format} """ diff --git a/app/subagent/definitions/research_agent.py b/app/subagent/definitions/research_agent.py index afbaf059..bd7bebbb 100644 --- a/app/subagent/definitions/research_agent.py +++ b/app/subagent/definitions/research_agent.py @@ -27,9 +27,6 @@ conversations and no access to the spawning agent's context beyond the query. -ALLOWED ACTIONS (you cannot use anything else): -{action_list} - YOUR LOOP: 1. Use web_search to identify candidate sources for the query. 2. Use web_fetch (or http_request for structured APIs) to read the @@ -89,8 +86,6 @@ call sub_task_end with status="failed" and put what you searched and why it failed in `result` — do NOT make up a partial answer. - Hitting the iteration cap without ending is a failure. Be efficient. - -{output_format} """ diff --git a/app/subagent/definitions/validation_agent.py b/app/subagent/definitions/validation_agent.py deleted file mode 100644 index 5afee118..00000000 --- a/app/subagent/definitions/validation_agent.py +++ /dev/null @@ -1,175 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Validation sub-agent. - -A maximally strict checker. The spawning agent supplies a Definition of -Done (DoD) in the query and the validation agent grades the artifact -against it. There is no implicit standard hard-coded here — the DoD is -the spec, and the validator's job is to find anything that falls short -of it, no matter how small. - -Default behaviour: -- Reject on ambiguity (PASS requires concrete evidence; absence of - evidence is a FAIL, not a pass). -- Cite exact failures (file:line, command + exit code, regex hit, value - found vs expected). -- Return a remediation list so the spawning agent can fix and retry. - -To tweak this agent's behaviour, edit: -- :data:`SYSTEM_PROMPT` — what the model is told to do. -- ``actions=`` — which actions the model is allowed to call. -- ``max_iterations`` / ``max_wall_seconds`` — runtime caps. - -``sub_task_end`` is added automatically by the registry — do not list it. -""" - -from app.subagent.registry import register_subagent - - -SYSTEM_PROMPT = """\ -You are a validation sub-agent. - -Your job is to grade an artifact (file, output, claim, deliverable) -against a Definition of Done (DoD) supplied by the spawning agent, and -return PASS / FAIL / PARTIAL with concrete, citable evidence for every -criterion. You are intentionally the toughest reviewer the artifact -will ever see. - -ALLOWED ACTIONS (you cannot use anything else): -{action_list} - -PARSING THE QUERY: -The spawning agent's query MUST contain a Definition of Done section -that lists the criteria the artifact must meet. Look for a heading -like "Definition of Done", "DoD", "Acceptance criteria", or a numbered -list of requirements. If none is present, immediately call sub_task_end -with status="failed" and result="No Definition of Done provided in the -query — cannot validate. Resend with explicit acceptance criteria." - -YOUR LOOP: -1. Read the artifact(s) named in the query. Use read_file, read_pdf, - list_folder, find_files, grep_files as appropriate. -2. For each criterion in the DoD, gather objective evidence: - - Run tests / scripts via run_shell. - - Grep for forbidden or required patterns. - - Fetch URLs the artifact references via web_fetch / http_request - and verify they resolve / return the expected shape. - - Search authoritative references via web_search for standards - compliance (RFC, MDN, language specs, etc.). - - For visual / design checks: describe_image on screenshots, PDF format, or - read the rendered HTML / DOM. -3. Decide each criterion: PASS only with concrete evidence; otherwise - FAIL. -4. Call sub_task_end with the verdict + per-criterion table + - remediation list. - -RULES (apply strictly — these are mechanical, not stylistic): - -G1. PASS requires concrete evidence: file:line, command + exit code, - regex hit, measured value, or quoted standard clause. "Looks fine" - is not evidence. Evidence must point to a specific action you ran - in THIS validation run. - -G2. Absence of evidence = FAIL. Never PASS on unverifiable. If you did - not run an action to verify a criterion, the criterion is ✗. - -G3. Near-miss = FAIL. Be literal: "all tests pass" + one xfail = FAIL; - "no console errors" + one warning = FAIL; "no broken page breaks" - + one truncated word at a page break = FAIL. There is no "minor" - failure category. - -G4. STANDARDS COMPLIANCE IS LITERAL. If the DoD cites a standard file - (FORMAT.md, AGENT.md, STYLE_GUIDE.md, RFC, WCAG, PEP), you MUST - open it (read_file / web_fetch) and check the named clauses one - by one. Refusing to open the named standard = ✗ on that criterion. - Assuming compliance without opening the standard = ✗. - -G5. DON'T MODIFY THE ARTIFACT. You're a checker, never an editor. - -G6. Every FAIL has an actionable Fix line: file path + offending content - + corrected content or rule citation. - -G7. CONTENT SPOT-CHECK. For numerical claims, dates, named events / - products in the artifact: identify the cited source → fetch - (web_fetch / read_file) → grep for the claimed value. Source - doesn't contain it → ✗ on "no fabrication" / "content accuracy". - Prefer high-impact claims (largest numbers, future-dated events, - standout statistics) over trivial ones. - -G8. SUBSTANCE CHECK. If the DoD specifies content volume (word count, - fact count, row count), actually count via read_file + grep / wc - and compare to the required minimum. Cite counted-vs-required as - evidence. A "comprehensive report" that is ONLY 4 pages long FAILS. - -G9. CONCRETE FORMAT PROPERTIES are checked literally with a specific - action per property. For PDFs / docs: read_pdf + grep for known - artifacts (page numbers mid-paragraph, corrupted character runs - indicating text truncation at page breaks, etc.). You must also - check for visual defect. Overflow table cell, missing unicode, - broken image link MUST be rejected. - - Anti-cheating: do NOT mark something ⚠ when it should be ✗ just to - reach PARTIAL. The ⚠ category is for criteria that are verifiable - and met but borderline (e.g. value sits at the edge of an allowed - range). Failed criteria are ✗, full stop. - -OUTPUT TEMPLATE — use this skeleton exactly: - -``` -VERDICT: PASS | FAIL | PARTIAL - -## Criteria -| # | Criterion (from DoD) | Status | Evidence | -|---|---|---|---| -| 1 | | ✓ / ✗ / ⚠ | | -| ... | ... | ... | ... | - -## Failures (only if any ✗ or ⚠) -- [#N] — - - Fix: -``` - -ENDING RULES: -- Call sub_task_end with status="completed" and the verdict block in - `result`. The verdict itself (PASS / FAIL / PARTIAL) lives INSIDE - `result`; the action-level status is always "completed" once you've - rendered the verdict. -- Use status="failed" only when you cannot run the validation at all - (missing DoD, missing artifact, missing tools). In that case put the - reason in `result`. -- Hitting the iteration cap without a verdict is a failure. Be - deliberate, not exhaustive. - -{output_format} -""" - - -register_subagent( - name="validation_agent", - description=( - "Grades an artifact against a Definition of Done you provide in `query`; " - "returns PASS/FAIL/PARTIAL with evidence. Query MUST include a DoD" - ), - system_prompt=SYSTEM_PROMPT, - actions=[ - # Filesystem / artifact inspection (read-only) - "read_file", - "read_pdf", - "find_files", - "grep_files", - "list_folder", - # Execute checks - "run_shell", - "run_powershell", - # External standards & API verification - "web_search", - "web_fetch", - "http_request", - # Format normalization & content rendering - "convert_to_markdown", - "describe_image", - "understand_video", - ], - max_iterations=30, - max_wall_seconds=900, -) diff --git a/app/subagent/manager.py b/app/subagent/manager.py index 2deb6b08..af999062 100644 --- a/app/subagent/manager.py +++ b/app/subagent/manager.py @@ -2,44 +2,43 @@ """ SubAgentManager — registry and lifecycle owner for sub-agents. -This is a deliberate parallel to ``TaskManager`` but with NONE of the side -effects that would make a sub-agent visible in the UI, persisted to disk, -or reported to a chatserver. It only reuses the event-stream buffer and -LLM session-cache primitives, which are pure data structures. +A deliberate parallel to ``SessionManager`` with NONE of the side effects +that would make a sub-agent visible in the UI as a chat, persist it, or +report it to a chatserver. A sub-agent gets its own event stream and its +own LLM session history; nothing of the spawning session's context. -Lifecycle is split into three operations to keep the event-stream usable -across all of them: +Lifecycle: - :meth:`spawn` — register a new ``SubAgent`` and create its event stream. -- :meth:`end` — mark the sub-agent terminal (status + result + breadcrumb - event). Safe to call from inside the ``sub_task_end`` action because the - stream stays alive — the subsequent ``action_end`` log for ``sub_task_end`` - still routes to the child stream. -- :meth:`release` — actually tear down the child's event stream and LLM - session caches. Called by the runner AFTER its loop exits, so every - log for the terminating action has already fired. - -What it deliberately does NOT do at any stage: -- Does NOT touch ``TaskManager.tasks`` or call ``create_task``. -- Does NOT call ``state_manager.on_task_created`` (the UI hot path). -- Does NOT call ``_on_task_persist`` (no SessionStorage row). -- Does NOT log to the main stream. -- Does NOT update ``current_task_id`` agent property. +- :meth:`run` — drive it until its run ends (SubAgentRunner), then + :meth:`release` it. Both ``spawn_subagent`` and the Agent-App verifier + start sub-agents this way. +- :meth:`end` — mark it terminal (status + result + breadcrumb event). + Called from inside the ``sub_task_end`` action, so the stream stays alive: + the action's ``action_end`` still has to be logged to it. +- :meth:`release` — drop its stream, LLM session and record once the run + is over. """ from __future__ import annotations import uuid from pathlib import Path -from typing import Dict, Optional, TYPE_CHECKING +from typing import TYPE_CHECKING, Dict, Optional -from app.logger import logger +from agent_core.core.event_stream.event import EventType +from agent_core.core.session import MAIN_SESSION_ID +from app.logger import add_subagent_log_sink, logger, remove_subagent_log_sink from app.subagent.registry import get_subagent_definition +from app.subagent.runner import SubAgentRunner from app.subagent.types import SubAgent if TYPE_CHECKING: + from agent_core.core.impl.action.library import ActionLibrary + from agent_core.core.impl.action.manager import ActionManager from app.event_stream import EventStreamManager from app.llm import LLMInterface + from app.session.session_manager import SessionManager class SubAgentManager: @@ -49,81 +48,101 @@ def __init__( self, event_stream_manager: "EventStreamManager", llm_interface: "LLMInterface", + action_library: "ActionLibrary", + action_manager: "ActionManager", + session_manager: "SessionManager", ): self.event_stream_manager = event_stream_manager self.llm_interface = llm_interface + self.action_library = action_library + self.action_manager = action_manager + self.session_manager = session_manager self.subagents: Dict[str, SubAgent] = {} # ------------------------------------------------------------------ - # Spawn + # Spawn / run # ------------------------------------------------------------------ def spawn( self, agent_type: str, query: str, - parent_task_id: Optional[str] = None, - parent_temp_dir: Optional[str] = None, + parent_session_id: Optional[str] = None, ) -> SubAgent: """ Register a new sub-agent and set up its isolated event stream. Args: agent_type: Name of a sub-agent type registered in - :mod:`app.subagent.registry` (one of the files under - :mod:`app.subagent.definitions`). + :mod:`app.subagent.registry`. query: The full instruction for the sub-agent. Must be self-contained — the sub-agent has no access to the parent's context. - parent_task_id: Optional id of the task that spawned this - sub-agent, for logging only. - parent_temp_dir: Optional temp directory of the spawning task. - When set, the child's event stream externalizes oversized - action outputs into ``//`` (same - mechanism as the main agent). Nesting under the parent's - temp dir means the files outlive the sub-agent — the parent - can still grep paths cited in the child's result — and are - removed by the parent task's normal temp-dir cleanup. - When None (e.g. conversation-mode spawn), externalization - stays off, preserving the previous behaviour. - - Returns: - The newly created :class:`SubAgent`. - """ - defn = get_subagent_definition(agent_type) + parent_session_id: The session whose turn spawns it. - sub_id = f"sub_{uuid.uuid4().hex[:8]}" + Raises: + ValueError: for an unknown ``agent_type``. + """ + definition = get_subagent_definition(agent_type) sub = SubAgent( - id=sub_id, + id=f"sub_{uuid.uuid4().hex[:8]}", agent_type=agent_type, - parent_task_id=parent_task_id, + parent_session_id=parent_session_id, query=query, - compiled_actions=defn.compiled_actions, + compiled_actions=definition.compiled_actions, ) - self.subagents[sub_id] = sub - - # Isolated event stream. EventStreamManager.create_stream is a pure - # data-structure op — no UI/chatserver hooks fire here. The temp_dir - # enables output externalization (EventStream._externalize_message); - # the directory itself is created lazily on first externalized event. - sub_temp_dir = Path(parent_temp_dir) / sub_id if parent_temp_dir else None - self.event_stream_manager.create_stream(sub_id, temp_dir=sub_temp_dir) - - # Drop a single bootstrap event onto the CHILD's stream only. - # The parent stream never sees it. + self.subagents[sub.id] = sub + + # Its workspace lives inside the spawning session's: oversized action + # outputs are saved there (EventStream._externalize_message), so the + # parent can still read paths the result cites, and they go with + # that session's workspace. + workspace = self._parent_workspace(parent_session_id) / sub.id + workspace.mkdir(parents=True, exist_ok=True) + self.event_stream_manager.create_stream(sub.id, temp_dir=workspace) self.event_stream_manager.log( kind="subagent_start", - message=sub.bootstrap_message, + message=f"Sub-agent of type '{agent_type}' started.", + event_type=EventType.INTERNAL, display_message=f"subagent[{agent_type}] start", - task_id=sub_id, + task_id=sub.id, ) logger.info( - f"[SubAgentManager] Spawned {sub_id} type={agent_type} " - f"parent={parent_task_id}" + f"[SubAgentManager] Spawned {sub.id} type={agent_type} " + f"parent={parent_session_id}" ) return sub + async def run(self, sub: SubAgent) -> SubAgent: + """Drive ``sub`` until its run ends, then release it. + + Its log lines are tagged "sub::" and also go to a file of + their own inside the spawning session's log folder. + """ + tag = f"sub:{sub.agent_type}:{sub.id.removeprefix('sub_')}" + log_session = sub.parent_session_id or MAIN_SESSION_ID + sink = add_subagent_log_sink(tag, log_session) + try: + with logger.contextualize(agent=tag, session=log_session): + try: + await SubAgentRunner(self, sub).run() + except Exception as e: + # A bug, not the model: the runner ends runs itself. + logger.exception(f"[SubAgentManager] {sub.id} crashed: {e}") + self.end(sub.id, "error", f"(sub-agent crashed: {e})") + finally: + self.release(sub.id) + finally: + remove_subagent_log_sink(sink) + return sub + + def _parent_workspace(self, parent_session_id: Optional[str]) -> Path: + """The spawning session's workspace (the main session's when there + is no spawning session).""" + session = self.session_manager.get(parent_session_id) or self.session_manager.main + return Path(session.workspace_dir) + # ------------------------------------------------------------------ # Lookup # ------------------------------------------------------------------ @@ -139,19 +158,13 @@ def end(self, sub_id: str, status: str, result: str) -> None: """ Mark a sub-agent terminal. - This is intentionally **lightweight**: it sets the status/result, - writes one ``subagent_end`` breadcrumb event to the child stream, - and returns. The stream and any LLM session caches are kept alive - because this method is called from inside the ``sub_task_end`` - action — the ActionManager still has to log ``action_end`` for - ``sub_task_end`` after the action body returns, and that log must - route to the child's stream (not the parent's main stream). - - Resource teardown happens in :meth:`release`, which the - ``SubAgentRunner`` calls after its loop exits. + Sets the status/result and writes one ``subagent_end`` breadcrumb + to the child stream. The stream stays alive: this is called from + inside the ``sub_task_end`` action, whose ``action_end`` the + ActionManager logs after the action body returns. :meth:`run` + releases it once the run is over. - Idempotent — repeat calls on a terminal sub-agent are ignored so - a batch with multiple ``sub_task_end`` calls can't corrupt state. + Idempotent — repeat calls on a terminal sub-agent are ignored. """ sub = self.subagents.get(sub_id) if sub is None: @@ -170,6 +183,7 @@ def end(self, sub_id: str, status: str, result: str) -> None: self.event_stream_manager.log( kind="subagent_end", message=f"Sub-agent ended with status '{status}'.", + event_type=EventType.INTERNAL, display_message=f"subagent[{sub.agent_type}] {status}", task_id=sub_id, ) @@ -180,36 +194,20 @@ def end(self, sub_id: str, status: str, result: str) -> None: ) # ------------------------------------------------------------------ - # Release — resource teardown (called by runner, post-loop) + # Release — resource teardown # ------------------------------------------------------------------ def release(self, sub_id: str) -> None: """ - Tear down the per-sub-agent event stream and LLM session caches. - - Must be called AFTER every action lifecycle log for this sub-agent - has fired. The runner calls it once, after ``run_to_completion``'s - loop exits, so any ``action_end`` logged by ``sub_task_end`` is - still routed to the child stream. + Drop a finished sub-agent: its event stream (the removal listeners + drain it to the UI and close its Mini Browser tabs), its LLM session + and its record. Idempotent. """ - sub = self.subagents.get(sub_id) - if sub is None: - logger.debug(f"[SubAgentManager] release() on unknown sub-agent: {sub_id}") - return - - self.event_stream_manager.remove_stream(sub_id) - self.llm_interface.end_all_session_caches(sub_id) - logger.debug(f"[SubAgentManager] Released {sub_id} (stream + session caches)") - - # ------------------------------------------------------------------ - # Test / inspection helpers - # ------------------------------------------------------------------ - - def reset(self) -> None: - """Forget every tracked sub-agent. Test-only.""" - for sub_id in list(self.subagents.keys()): + if self.event_stream_manager.has_stream(sub_id): self.event_stream_manager.remove_stream(sub_id) - self.subagents.clear() + self.llm_interface.end_all_session_caches(sub_id) + if self.subagents.pop(sub_id, None) is not None: + logger.debug(f"[SubAgentManager] Released {sub_id}") __all__ = ["SubAgentManager"] diff --git a/app/subagent/registry.py b/app/subagent/registry.py index 2d0cdd2a..0b0cc3b5 100644 --- a/app/subagent/registry.py +++ b/app/subagent/registry.py @@ -5,7 +5,7 @@ Every sub-agent type lives in its own module under :mod:`app.subagent.definitions` and calls :func:`register_subagent` at import time. That gives each type a single place where its prompt, allowed actions, and runtime caps are -defined — no scattering across ``types.py`` + ``prompts/``. +defined. ``sub_task_end`` is the universal terminator action. The registry appends it to every definition's action list automatically; it must NEVER be @@ -27,6 +27,10 @@ # definitions cannot accidentally omit it or list it twice. SUB_TASK_END_ACTION = "sub_task_end" +# A veto on premature sub_task_end calls: (sub, parameters) → rejection text, +# or None to allow the end. +EarlyEndGuard = Callable[["SubAgent", Dict[str, object]], Optional[str]] + @dataclass(frozen=True) class SubAgentDefinition: @@ -39,16 +43,21 @@ class SubAgentDefinition: Shown to the spawning agent in the ``spawn_subagent`` action's description — keep it tight: ~80–120 chars, no trailing period needed. - system_prompt: The system-prompt template. Must contain - ``{action_list}`` and ``{output_format}`` placeholders — the - context engine fills these in per turn. + system_prompt: The type's own system prompt: its role, workflow, + rules and ending. The runtime appends the decision instructions + (batching rules, reply format, the list) and the + environment, so the prompt never lists actions or the format. actions: Frozen tuple of action names this type may invoke, INCLUDING ``sub_task_end`` (auto-injected). Anything outside this set is refused by the runner. - max_iterations: Hard cap on action turns before the runner ends - the sub-agent as ``failed``. + max_iterations: Hard cap on turns before the runner ends the + sub-agent as ``failed``. max_wall_seconds: Hard cap on wall-clock execution before the runner ends the sub-agent as ``timeout``. + early_end_guard: Optional veto on premature sub_task_end calls. The + runner logs the rejection into the sub's stream (costing one + turn) and the loop continues; on the final turn it is not + consulted, so it can never trap a sub-agent into the turn cap. """ name: str @@ -57,33 +66,7 @@ class SubAgentDefinition: actions: Tuple[str, ...] max_iterations: int max_wall_seconds: int - # Forced parameters per action: ((action_name, ((param, value), ...)), ...) - # e.g. scope shared-browser console reads to recent entries only. - param_overrides: Tuple[Tuple[str, Tuple[Tuple[str, object], ...]], ...] = () - # Optional veto on premature sub_task_end calls: (sub, parameters) → - # rejection text, or None to allow the end. The runner logs the rejection - # into the sub's stream (costing one turn) and the loop continues — - # structural enforcement for types whose models surrender early (a - # verifier with 50 turns concluded at turn 8 citing "limited turns"). - early_end_guard: Optional[ - Callable[["SubAgent", Dict[str, object]], Optional[str]] - ] = None - # Context compaction (scoped walk-verify Phase 3): action names whose - # OLDER outputs are replaced by a short stub once `compact_keep` newer - # ones exist — a browser snapshot is superseded by the next snapshot, so - # keeping 40 of them in context buys nothing. Takes effect when the - # provider-side session is rebuilt: every `session_reset_every` turns - # (0 = only on summarization). - compact_actions: Tuple[str, ...] = () - compact_keep: int = 2 - session_reset_every: int = 0 - - def overrides_for(self, action_name: str) -> Dict[str, object]: - """The forced parameters for one action ({} when none).""" - for name, pairs in self.param_overrides: - if name == action_name: - return dict(pairs) - return {} + early_end_guard: Optional[EarlyEndGuard] = None @property def compiled_actions(self) -> List[str]: @@ -104,13 +87,7 @@ def register_subagent( actions: Iterable[str], max_iterations: int, max_wall_seconds: int, - param_overrides: Tuple[Tuple[str, Tuple[Tuple[str, object], ...]], ...] = (), - early_end_guard: Optional[ - Callable[["SubAgent", Dict[str, object]], Optional[str]] - ] = None, - compact_actions: Iterable[str] = (), - compact_keep: int = 2, - session_reset_every: int = 0, + early_end_guard: Optional[EarlyEndGuard] = None, ) -> None: """Register a sub-agent type. @@ -118,12 +95,13 @@ def register_subagent( name: Unique agent_type identifier (e.g. ``"research_agent"``). description: One short sentence shown to the spawning agent in the ``spawn_subagent`` action description. Keep it tight. - system_prompt: System-prompt template with ``{action_list}`` and - ``{output_format}`` placeholders. + system_prompt: The type's own system prompt (see + :class:`SubAgentDefinition`). actions: Action names this type may invoke. ``sub_task_end`` is auto-appended; do NOT list it here. - max_iterations: Hard cap on action turns. + max_iterations: Hard cap on turns. max_wall_seconds: Hard cap on wall-clock execution. + early_end_guard: Optional veto on premature sub_task_end calls. Raises: ValueError: if ``name`` is already registered, ``description`` is @@ -172,11 +150,7 @@ def register_subagent( actions=tuple(cleaned), max_iterations=max_iterations, max_wall_seconds=max_wall_seconds, - param_overrides=param_overrides, early_end_guard=early_end_guard, - compact_actions=tuple(dict.fromkeys(compact_actions)), - compact_keep=max(1, int(compact_keep)), - session_reset_every=max(0, int(session_reset_every)), ) logger.debug( f"[SubAgentRegistry] Registered {name!r} " @@ -200,15 +174,11 @@ def list_subagent_names() -> List[str]: return sorted(_REGISTRY) -def is_subagent_registered(name: str) -> bool: - return name in _REGISTRY - - __all__ = [ "SUB_TASK_END_ACTION", + "EarlyEndGuard", "SubAgentDefinition", "register_subagent", "get_subagent_definition", "list_subagent_names", - "is_subagent_registered", ] diff --git a/app/subagent/runner.py b/app/subagent/runner.py index fc781edb..9d12e541 100644 --- a/app/subagent/runner.py +++ b/app/subagent/runner.py @@ -1,716 +1,200 @@ # -*- coding: utf-8 -*- """ -SubAgentRunner — minimal action loop for one sub-agent. - -This is intentionally NOT a thin wrapper around the main agent's -``react()`` loop. Sub-agents don't need todo planning, memory pulls, -conversation routing, GUI workflows, or proactive handling. They need: - - while not terminal: - prompt = type-specific system prompt + query + own event log - decision = LLM(prompt) → {action_name, parameters} - if action_name not in compiled_actions: skip with warning - action_manager.execute_action(action, ..., session_id=sub.id) - -The runner relies on existing primitives for execution and logging: - -- ``ActionManager.execute_action`` runs the action and logs - ``action_start`` / ``action_end`` to the sub-agent's stream (because we - pass ``session_id=sub.id`` and ``is_running_task=True``). -- ``sub_task_end`` is the action that marks the sub-agent terminal — the - runner detects that by checking ``sub.is_terminal()`` after every step. - -Session caching: - -- A single session cache is registered with the LLM interface up front - (once per sub-agent lifetime) using the sub-agent's system prompt. -- The first turn sends the full ``query + initial event log`` user - prompt; subsequent turns send only the events appended to the child - stream since the previous call, drastically reducing tokens. -- The LLM interface transparently handles providers without session - caching (e.g. ollama) — the call shape is the same. - -Resource cleanup: - -- ``SubAgentManager.end()`` only flips status and writes a breadcrumb; - it deliberately leaves the stream alive so the ``sub_task_end`` action - can finish logging ``action_end`` to the child stream. -- After the loop exits, the runner calls ``SubAgentManager.release()`` - in a ``finally`` to drop the stream and release session caches. +SubAgentRunner — drives one sub-agent until its run ends. + +A sub-agent runs the main agent's turn on a context of its own: the same +ActionRouter (requests, retries, folds, session caching), the same AgentStep +(reasoning event, prepared actions) and the same +ActionManager.execute_actions_parallel. What is its own: + +- its context (SubAgentContextEngine) and the two decision templates; +- the check on every chosen action: only the definition's actions run, and + the definition's early_end_guard may refuse a sub_task_end (except on the + final turn); +- how the run ends: sub_task_end (the action ends it), the turn cap + (failed), the time cap (timeout; whatever is in flight is cancelled), an + error (failed), or the spawning run being stopped (failed, and the + cancellation propagates). + +It runs on the event loop of the turn that spawned it, so stopping that run +stops the sub-agent. SubAgentManager.run wraps it (log sink, release). """ from __future__ import annotations -import ast -import json -import time -from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple +import asyncio +from typing import TYPE_CHECKING, Any, Dict, Optional +from agent_core.core.event_stream.event import EventType +from agent_core.core.impl.action import ActionRouter, AgentStep from agent_core.core.impl.llm import LLMCallType, LLMConsecutiveFailureError +from agent_core.core.prompts import decision_system_prompt from app.logger import logger -from app.subagent.context_engine import SubAgentContextEngine +from app.subagent.context_engine import ( + SUBAGENT_DECISION_INSTRUCTIONS, + SUBAGENT_DECISION_PROMPT, + SubAgentContextEngine, +) from app.subagent.registry import SUB_TASK_END_ACTION, get_subagent_definition from app.subagent.types import SubAgent if TYPE_CHECKING: - from agent_core.core.impl.action.library import ActionLibrary - from agent_core.core.impl.action.manager import ActionManager - from app.event_stream import EventStreamManager - from app.llm import LLMInterface from app.subagent.manager import SubAgentManager -# Max LLM format-error retries per turn before the runner aborts the sub-agent. -_MAX_PARSE_RETRIES = 3 - -# Hard ceiling on ONE LLM round-trip. Generous (large prompts + slow -# providers) but finite — the wall-clock cap depends on calls returning. -_LLM_CALL_TIMEOUT_S = 300 - -# Sub-agents only ever do action selection — never GUI or reasoning calls — -# so a single call type covers their entire lifetime. -_SUBAGENT_CALL_TYPE = LLMCallType.ACTION_SELECTION +# The session history a sub-agent's decisions continue (the router's). +_CALL_TYPE = LLMCallType.ACTION_SELECTION class SubAgentRunner: """Drives a single sub-agent to a terminal state.""" - def __init__( - self, - subagent_manager: "SubAgentManager", - action_manager: "ActionManager", - action_library: "ActionLibrary", - event_stream_manager: "EventStreamManager", - llm_interface: "LLMInterface", - ): - self.subagent_manager = subagent_manager - self.action_manager = action_manager - self.action_library = action_library - self.event_stream_manager = event_stream_manager - self.llm_interface = llm_interface - self.context_engine = SubAgentContextEngine( - action_library=action_library, - event_stream_manager=event_stream_manager, + def __init__(self, manager: "SubAgentManager", sub: SubAgent): + self.manager = manager + self.sub = sub + self.definition = get_subagent_definition(sub.agent_type) + self.context = SubAgentContextEngine(sub, manager.event_stream_manager) + self.router = ActionRouter( + manager.action_library, + manager.llm_interface, + self.context, + instructions=SUBAGENT_DECISION_INSTRUCTIONS, + user_prompt=SUBAGENT_DECISION_PROMPT, + prompt_name=f"SUBAGENT_{sub.agent_type.upper()}", + ) + self.step = AgentStep( + self.router, manager.action_library, manager.event_stream_manager ) - # ------------------------------------------------------------------ - # Public entrypoint - # ------------------------------------------------------------------ - - async def run_to_completion(self, sub: SubAgent) -> SubAgent: - """ - Loop until the sub-agent reaches a terminal status, hits the - iteration cap, or hits the wall-clock cap. Always returns the - same ``SubAgent`` (mutated in place). - - Always calls ``SubAgentManager.release(sub.id)`` before returning, - even on exception, so the per-sub-agent event stream and session - caches don't leak. - """ - defn = get_subagent_definition(sub.agent_type) - max_iter = defn.max_iterations - max_wall = defn.max_wall_seconds - deadline = time.monotonic() + max_wall - + async def run(self) -> None: + """Take turns until the sub-agent ends, within its time cap.""" + sub, cap_seconds = self.sub, self.definition.max_wall_seconds logger.info( f"[SubAgentRunner] starting {sub.id} type={sub.agent_type} " - f"max_iter={max_iter} max_wall={max_wall}s" - ) - - # Register the session cache once for this sub-agent's whole - # lifetime. The system prompt is stable across turns, so this - # only needs to happen here, not on every step. - self._register_session(sub) - - try: - while not sub.is_terminal(): - # Increment at the TOP of the loop so ``sub.iterations`` - # reflects the turn currently being executed. This makes - # the manager's "Ended iterations=N" log and the runner's - # "loop done iterations=N" log agree. - sub.iterations += 1 - - if sub.iterations > max_iter: - self._terminate_at_iteration_cap(sub, max_iter) - break - if time.monotonic() > deadline: - self._terminate_at_wall_clock(sub, max_wall) - break - - await self._run_one_step_safely(sub) - - # Context compaction (definition-driven): stub superseded - # outputs, and periodically rebuild the provider-side session - # from the compacted stream so the growth actually leaves the - # context (a cached session keeps every old snapshot until - # it is recreated). - try: - self._compact_stream(sub, defn) - if ( - defn.session_reset_every - and sub.iterations > 1 - and sub.iterations % defn.session_reset_every == 0 - and not sub.is_terminal() - ): - stream = self.event_stream_manager.get_stream_by_id(sub.id) - if stream is not None: - self._reset_session(sub, stream) - logger.info( - f"[SubAgentRunner] {sub.id} session rebuilt from " - f"compacted stream at turn {sub.iterations}" - ) - except Exception as e: - logger.debug(f"[SubAgentRunner] {sub.id} compaction skipped: {e}") - - logger.info( - f"[SubAgentRunner] {sub.id} loop done. status={sub.status} " - f"iterations={sub.iterations}" - ) - return sub - finally: - # Release runs AFTER the loop, not inside ``end()``. ActionManager - # logs ``action_end`` for ``sub_task_end`` after the action body - # returns; that log must still find the child's stream. We swallow - # release errors so a cleanup crash doesn't mask the original - # exception (if any) propagating out of the try block. - try: - self.subagent_manager.release(sub.id) - except Exception as e: - logger.warning(f"[SubAgentRunner] release({sub.id}) failed: {e}") - - # ------------------------------------------------------------------ - # Context compaction - # ------------------------------------------------------------------ - - _COMPACT_MARK = "[superseded output elided" - - def _compact_stream(self, sub: SubAgent, defn) -> None: - """Replace the OLDER outputs of `defn.compact_actions` with a short - stub, keeping the newest `defn.compact_keep`. A browser snapshot is - only useful until the next one; keeping every one of them in a - 40-turn walk is the single biggest context cost of a verify.""" - names = set(getattr(defn, "compact_actions", ()) or ()) - if not names: - return - stream = self.event_stream_manager.get_stream_by_id(sub.id) - if stream is None: - return - lock = getattr(stream, "_lock", None) - keep = max(1, int(getattr(defn, "compact_keep", 2) or 1)) - - def _do() -> None: - records = [ - rec - for rec in stream.tail_events - if getattr(rec.event, "action_name", None) in names - and getattr(rec.event, "action_output", None) is not None - ] - for rec in records[:-keep]: - msg = rec.event.message or "" - if msg.startswith(self._COMPACT_MARK): - continue - rec.event.message = ( - f"{self._COMPACT_MARK} — {len(msg)} chars from " - f"{rec.event.action_name}; a newer one exists below]" - ) - rec.event.action_output = None - rec._cached_tokens = None - - if lock is not None: - with lock: - _do() - else: - _do() - - # ------------------------------------------------------------------ - # Termination helpers (iteration cap / wall-clock cap) - # ------------------------------------------------------------------ - - def _terminate_at_iteration_cap(self, sub: SubAgent, cap: int) -> None: - logger.warning( - f"[SubAgentRunner] {sub.id} hit iteration cap ({cap}); ending as failed" + f"max_iter={self.definition.max_iterations} max_wall={cap_seconds}s" ) - # Roll the count back to the cap so it doesn't appear we ran an - # extra turn we never actually executed. - sub.iterations = cap - self.subagent_manager.end( + # Register the session history the router's requests continue, on + # the system prompt they send. + self.manager.llm_interface.create_session_cache( sub.id, - status="failed", - result=( - f"(sub-agent exhausted iteration cap of {cap} " - "without calling sub_task_end)" + _CALL_TYPE, + decision_system_prompt( + self.context.make_prompt()[0], self.router.decision_instructions(sub.id) ), ) - - def _terminate_at_wall_clock(self, sub: SubAgent, cap_seconds: int) -> None: - logger.warning( - f"[SubAgentRunner] {sub.id} hit wall-clock cap " - f"({cap_seconds}s); ending as timeout" - ) - # The increment at the top of the loop was speculative — we never - # actually ran this turn. Undo it so the count stays honest. - sub.iterations -= 1 - self.subagent_manager.end( - sub.id, - status="timeout", - result=( - f"(sub-agent ran past wall-clock cap of {cap_seconds}s " - "without calling sub_task_end)" - ), - ) - - # ------------------------------------------------------------------ - # Per-step: ask LLM → dispatch action - # ------------------------------------------------------------------ - - async def _run_one_step_safely(self, sub: SubAgent) -> None: - """Run one step, surfacing crashes as a stream event without aborting. - - The sub-agent gets another chance on the next turn to observe the - error and self-correct. If failures continue, the iteration cap - catches it. - """ try: - await self._run_one_step(sub) - except LLMConsecutiveFailureError as e: - # Fatal LLM failure (out-of-credits, auth, repeated provider - # errors). Retrying can't help, so end the sub-agent now with the - # real cause instead of spinning until the iteration cap. Ending - # makes ``sub.is_terminal()`` true, so the run loop exits cleanly. - cause = ( - e.last_error_info.message if e.last_error_info is not None else str(e) - ) - logger.error( - f"[SubAgentRunner] {sub.id} aborting after consecutive LLM " - f"failures: {cause}" - ) - self.event_stream_manager.log( - kind="subagent_error", - message=f"LLM unavailable: {cause}", - severity="ERROR", - task_id=sub.id, + await asyncio.wait_for(self._turns(), timeout=cap_seconds) + except asyncio.TimeoutError: + logger.warning( + f"[SubAgentRunner] {sub.id} hit its time cap ({cap_seconds}s)" ) - self.subagent_manager.end( + self.manager.end( sub.id, - status="failed", - result=f"(sub-agent aborted — LLM unavailable: {cause})", + "timeout", + f"(sub-agent ran past its time cap of {cap_seconds}s without " + "calling sub_task_end)", ) - except Exception as e: - logger.exception( - f"[SubAgentRunner] {sub.id} step {sub.iterations} crashed: {e}" + except asyncio.CancelledError: + self.manager.end( + sub.id, "failed", "(sub-agent stopped with the run that spawned it)" ) - self.event_stream_manager.log( - kind="subagent_error", - message=f"Step crashed: {e}", - severity="ERROR", - task_id=sub.id, - ) - - async def _run_one_step(self, sub: SubAgent) -> None: - decision, parse_error = await self._ask_llm_for_decision(sub) - if decision is None: - self._fail_unparseable(sub, parse_error) - return - await self._dispatch_action(sub, decision) - - def _fail_unparseable(self, sub: SubAgent, parse_error: Optional[str]) -> None: - self.event_stream_manager.log( - kind="subagent_error", - message=( - f"LLM produced unparseable decision after " - f"{_MAX_PARSE_RETRIES} attempts. Last error: {parse_error}" - ), - severity="ERROR", - task_id=sub.id, - ) - self.subagent_manager.end( - sub.id, - status="failed", - result=( - "(sub-agent could not produce a parseable action decision; " - f"last error: {parse_error})" - ), + raise + logger.info( + f"[SubAgentRunner] {sub.id} done. status={sub.status} " + f"iterations={sub.iterations}" ) - async def _dispatch_action(self, sub: SubAgent, decision: Dict[str, Any]) -> None: - action_name = decision.get("action_name") or "" - # Models frequently emit "params" instead of "parameters" — accept both - # (dropping the payload silently starved every tool call of its input). - parameters = decision.get("parameters") or decision.get("params") or {} - if not isinstance(parameters, dict): - parameters = {} - - # Enforce the frozen action list — refuse anything else. - if action_name not in sub.compiled_actions: - msg = ( - f"Disallowed action {action_name!r}. " - f"You can only use: {sub.compiled_actions}." - ) - logger.warning(f"[SubAgentRunner] {sub.id} {msg}") - self.event_stream_manager.log( - kind="action_blocked", - message=msg, - display_message=f"blocked: {action_name}", - task_id=sub.id, - ) - return - - # Definition-level veto on premature conclusions: the guard sees the - # sub_task_end parameters and may reject them with an instruction - # that lands in the sub's stream — the loop then continues and the - # model reads why. Guard errors fail open (the end proceeds); the - # guard itself must stand down near the caps so it can never trap a - # sub-agent into dying at the iteration cap with no verdict. - if action_name == SUB_TASK_END_ACTION: + async def _turns(self) -> None: + sub, cap = self.sub, self.definition.max_iterations + while not sub.is_terminal(): + if sub.iterations >= cap: + logger.warning(f"[SubAgentRunner] {sub.id} used all {cap} turns") + self.manager.end( + sub.id, + "failed", + f"(sub-agent used all {cap} turns without calling sub_task_end)", + ) + return + sub.iterations += 1 + self._warn_when_turns_run_low() try: - guard = get_subagent_definition(sub.agent_type).early_end_guard - except Exception: - guard = None - if guard is not None: - try: - rejection = guard(sub, parameters) - except Exception as e: - logger.warning( - f"[SubAgentRunner] {sub.id} early_end_guard crashed " - f"(allowing end): {e}" - ) - rejection = None - if rejection: - logger.info( - f"[SubAgentRunner] {sub.id} early sub_task_end " - f"rejected at iteration {sub.iterations}" - ) - self.event_stream_manager.log( - kind="action_blocked", - message=rejection, - display_message="early conclusion rejected — continuing", - task_id=sub.id, - ) - return - - # Apply registry-forced parameters (e.g. shared-browser hygiene). - try: - forced = get_subagent_definition(sub.agent_type).overrides_for(action_name) - except Exception: - forced = {} - if forced: - parameters = {**parameters, **forced} - - action = self.action_library.retrieve_action(action_name) - if action is None: - msg = ( - f"Action {action_name!r} is in the type's allow list but is " - "not registered in the library. Configuration bug." - ) - logger.error(f"[SubAgentRunner] {sub.id} {msg}") - self.event_stream_manager.log( - kind="action_blocked", - message=msg, - task_id=sub.id, + await self._turn() + except LLMConsecutiveFailureError as e: + # Out of credits, auth, repeated provider errors: name the + # real cause, not the generic retry message. + info = e.last_error_info + self._fail(info.message if info is not None else str(e)) + except Exception as e: + # The router gave up (unparseable or wrong-format replies, + # provider errors) after its own retries: the run ends, as a + # main-agent run does. + self._fail(str(e)) + + async def _turn(self) -> None: + sub = self.sub + decisions, reasoning = await self.step.decide(sub.query, sub.id) + prepared = self.step.prepare(decisions, sub.id, check=self._check) + if prepared: + await self.manager.action_manager.execute_actions_parallel( + actions=prepared, + context=reasoning, + event_stream="", + session_id=sub.id, + is_running_task=True, ) - return - - # ActionManager handles action_start/action_end logging to the child - # stream, error capture, and idempotency. We pass session_id=sub.id - # so every log routes to the child's per-id stream. - await self.action_manager.execute_action( - action=action, - context="", - event_stream="", - session_id=sub.id, - is_running_task=True, - is_gui_task=False, - input_data=parameters, - ) - - # ------------------------------------------------------------------ - # Session-cache management - # ------------------------------------------------------------------ - - def _register_session(self, sub: SubAgent) -> None: - """ - Register a session cache for this sub-agent's full lifetime. - - Stores the system prompt with the LLM interface so: - - the first ``generate_response_with_session_async`` call can - create the actual provider-side session lazily, and - - context-overflow recovery (provider-specific) can rebuild a - fresh session from the stored prompt. - - Called once before the loop starts. Re-registration would be - harmless (just overwrites the stored prompt) but wasteful. - """ - system_prompt = self.context_engine.make_system_prompt(sub) - self.llm_interface.create_session_cache( - sub.id, _SUBAGENT_CALL_TYPE, system_prompt - ) - def _reset_session(self, sub: SubAgent, stream) -> None: - """ - Drop the session cache and the stream's sync point for this turn. - - Called when the stream signals the sync point is no longer usable - (e.g. summarization has rolled events past it). The next call to - ``_build_user_prompt`` will resend the full first-turn prompt and - the LLM interface will lazily recreate the session. - """ - self.llm_interface.reset_session_history(sub.id, _SUBAGENT_CALL_TYPE) - stream.reset_session_sync(_SUBAGENT_CALL_TYPE) - - # ------------------------------------------------------------------ - # LLM call + JSON parsing — session-cache aware - # ------------------------------------------------------------------ - - async def _ask_llm_for_decision( - self, sub: SubAgent - ) -> Tuple[Optional[Dict[str, Any]], Optional[str]]: - """ - Ask the LLM for the next action and return ``(decision, error)``. - - Builds the user prompt (full first-turn vs. delta), invokes the - LLM, parses the JSON, and retries up to ``_MAX_PARSE_RETRIES`` - times if the response is unparseable. Returns ``(None, error)`` - if every attempt fails. - - Marks the stream's sync point on the first successful parse so - the next turn only sees events appended since this one. - """ - stream = self.event_stream_manager.get_stream_by_id(sub.id) - base_user_prompt, is_first_turn = self._build_user_prompt(sub, stream) - system_prompt = self.context_engine.make_system_prompt(sub) - - current_user_prompt = base_user_prompt - last_error: Optional[str] = None - last_raw: Optional[str] = None - - for attempt in range(1, _MAX_PARSE_RETRIES + 1): + def _check(self, action_name: str, parameters: Dict[str, Any]) -> Optional[str]: + """Why a chosen action may not run, or None (AgentStep.prepare).""" + sub, definition = self.sub, self.definition + if action_name not in sub.compiled_actions: + return ( + f"'{action_name}' is not one of your actions. You can only use: " + f"{', '.join(sub.compiled_actions)}." + ) + guard = definition.early_end_guard + if ( + action_name == SUB_TASK_END_ACTION + and guard is not None + and sub.iterations < definition.max_iterations + ): try: - raw = await self._invoke_llm(sub, current_user_prompt, system_prompt) - except LLMConsecutiveFailureError: - # Fatal: the LLM is in a broken state (e.g. out-of-credits, - # auth). Retrying within this turn can't help — let it - # propagate so the runner ends the sub-agent with the real - # cause instead of looping the parse retries. - raise + return guard(sub, parameters) except Exception as e: - logger.exception( - f"[SubAgentRunner] {sub.id} LLM call failed on attempt {attempt}: {e}" + logger.warning( + f"[SubAgentRunner] {sub.id} early_end_guard failed " + f"(allowing the end): {e}" ) - last_error = f"LLM call failed: {e}" - continue - - last_raw = raw or "" - decision, parse_error = self._parse_decision(raw) - if decision is not None: - # Advance the sync point so the next turn's delta excludes - # everything up to and including this turn's outcome. - stream.mark_session_synced(_SUBAGENT_CALL_TYPE) - return decision, None - - last_error = parse_error or "unknown parse error" - logger.warning( - f"[SubAgentRunner] {sub.id} parse error attempt {attempt}: " - f"{last_error} | raw={raw!r}" - ) - current_user_prompt = self._augment_with_retry_hint( - base=base_user_prompt if is_first_turn else current_user_prompt, - attempt=attempt, - error=last_error, - ) - - return None, f"{last_error} (last raw response: {last_raw!r})" - - async def _invoke_llm( - self, sub: SubAgent, user_prompt: str, system_prompt: str - ) -> str: - """ - One round-trip to the LLM via the session-cache path. - - ``system_prompt_for_new_session`` is passed every turn so the LLM - interface can recreate the session if a context-overflow reset - happened underneath us. - - Hard per-call timeout: a connection that dies mid-request (e.g. a - laptop sleep/wake severing the socket) otherwise blocks this await - forever — and the runner's wall-clock cap is only checked BETWEEN - turns, so one dead socket wedged the whole session - (observed: 20260724181301, 19-minute hang). - """ - import asyncio + return None - try: - return await asyncio.wait_for( - self.llm_interface.generate_response_with_session_async( - task_id=sub.id, - call_type=_SUBAGENT_CALL_TYPE, - user_prompt=user_prompt, - system_prompt_for_new_session=system_prompt, - prompt_name=f"SUBAGENT_{sub.agent_type.upper()}", + def _warn_when_turns_run_low(self) -> None: + """Once a fifth of the turns are left, say so in the stream.""" + cap = self.definition.max_iterations + left = cap - self.sub.iterations + 1 # this turn included + if left == max(1, cap // 5): + self.manager.event_stream_manager.log( + kind="warning", + message=( + f"Turn budget: {left} of {cap} turns left, this one " + "included. Finish the query and end with sub_task_end " + "before they run out." ), - timeout=_LLM_CALL_TIMEOUT_S, + event_type=EventType.INTERNAL, + task_id=self.sub.id, ) - except asyncio.TimeoutError as timeout_err: - raise LLMConsecutiveFailureError( - 1, - last_error=TimeoutError( - f"sub-agent LLM call exceeded {_LLM_CALL_TIMEOUT_S}s " - "(connection presumed dead)" - ), - ) from timeout_err - @staticmethod - def _augment_with_retry_hint(base: str, attempt: int, error: str) -> str: - return ( - f"{base}\n\n" - f"PREVIOUS ATTEMPT {attempt} FAILED TO PARSE.\n" - f"Error: {error}\n" - "Reply with ONLY the JSON object as specified. " - "No prose, no fences." + def _fail(self, cause: str) -> None: + sub = self.sub + logger.error( + f"[SubAgentRunner] {sub.id} turn {sub.iterations} failed: {cause}" ) - - # ------------------------------------------------------------------ - # User-prompt builder (first turn vs. delta) - # ------------------------------------------------------------------ - - def _build_user_prompt(self, sub: SubAgent, stream) -> Tuple[str, bool]: - """Return ``(user_prompt, is_first_turn)``. - - First turn: send the full query + the initial event log. - - Delta turns: send only events added since the last sync point. If - the stream reports no delta (e.g. summarization rolled events - past the sync point), reset the session and fall back to a fresh - first-turn prompt — that's the only path that re-grounds the - model after the cached history vanishes. - """ - if not stream.has_session_sync(_SUBAGENT_CALL_TYPE): - # A true first turn, or the stream folded and cleared the sync - # point; either way any accumulated turns are stale. - self._reset_session(sub, stream) - prompt = self.context_engine.make_first_turn_user_prompt(sub) - return self._with_turn_budget(sub, prompt), True - - delta_str, has_delta = stream.get_delta_events(_SUBAGENT_CALL_TYPE) - if not has_delta: - logger.info( - f"[SubAgentRunner] {sub.id} no delta events / summarization " - "detected — resetting session and resending full prompt" - ) - self._reset_session(sub, stream) - prompt = self.context_engine.make_first_turn_user_prompt(sub) - return self._with_turn_budget(sub, prompt), True - - prompt = self.context_engine.make_delta_user_prompt(delta_str) - return self._with_turn_budget(sub, prompt), False - - def _with_turn_budget(self, sub: SubAgent, prompt: str) -> str: - """Prefix every turn with the sub-agent's real position in its - iteration budget. Without it, models invent scarcity: a verifier - with 50 turns concluded at turn 8 citing 'limited turns' (observed - live 2026-08-05). System prompt stays untouched — a moving number - there would break prefix caching; user prompts change every turn - anyway.""" - try: - cap = get_subagent_definition(sub.agent_type).max_iterations - except Exception: - return prompt - remaining = max(0, cap - sub.iterations) - return ( - f"TURN BUDGET: this is turn {sub.iterations} of {cap} — " - f"{remaining} remain. Pace yourself by these numbers, not by " - "guesswork.\n\n" + prompt + self.manager.event_stream_manager.log( + kind="subagent_error", + message=f"Turn {sub.iterations} failed: {cause}", + severity="ERROR", + event_type=EventType.ERROR, + task_id=sub.id, ) - - # ------------------------------------------------------------------ - # JSON parsing - # ------------------------------------------------------------------ - - @staticmethod - def _parse_decision( - raw: Optional[str], - ) -> Tuple[Optional[Dict[str, Any]], Optional[str]]: - """Robust JSON/dict parsing of an LLM decision.""" - if not raw or not raw.strip(): - return None, "empty LLM response" - - text = raw.strip() - # Strip BOM, normalize line endings. - if text.startswith(""): - text = text[1:] - text = text.replace("\r\n", "\n").replace("\r", "").strip() - - # Strip markdown code fences if the LLM ignored instructions. - if text.startswith("```"): - first_nl = text.find("\n") - if first_nl != -1: - text = text[first_nl + 1 :] - if text.endswith("```"): - text = text[:-3] - text = text.strip() - - try: - parsed = json.loads(text) - except json.JSONDecodeError as e: - try: - parsed = ast.literal_eval(text) - except Exception as e2: - # Models routinely prefix a sentence of reasoning before the - # JSON ("I'll click the pill next. {...}"). Observed live - # 2026-08-25: 13 such turns per walk, each costing a full - # retry call. Salvage the first balanced top-level object. - salvaged = SubAgentRunner._extract_json_object(text) - if salvaged is not None: - parsed = salvaged - else: - return None, f"json: {e}; literal_eval: {e2}" - - if not isinstance(parsed, dict): - return None, "parsed value is not a dict" - if "action_name" not in parsed: - # Salvage: models under repeated correction sometimes emit just the - # bare final-result object. Wrap it as an explicit terminator so a - # usable result is never thrown away over formatting. - if any(k in parsed for k in ("result", "verdicts", "summary")): - return { - "action_name": "sub_task_end", - "parameters": {"status": "completed", "result": json.dumps(parsed)}, - }, None - return None, "missing 'action_name' field" - return parsed, None - - @staticmethod - def _extract_json_object(text: str) -> Optional[Dict[str, Any]]: - """First balanced `{…}` in `text` that parses as a dict, scanning - with string awareness so braces inside JSON strings don't confuse - the match. None when nothing parses.""" - start = text.find("{") - while start != -1: - depth, in_str, esc = 0, False, False - for i in range(start, len(text)): - ch = text[i] - if in_str: - if esc: - esc = False - elif ch == "\\": - esc = True - elif ch == '"': - in_str = False - continue - if ch == '"': - in_str = True - elif ch == "{": - depth += 1 - elif ch == "}": - depth -= 1 - if depth == 0: - candidate = text[start : i + 1] - try: - obj = json.loads(candidate) - except json.JSONDecodeError: - break # try the next '{' - return obj if isinstance(obj, dict) else None - start = text.find("{", start + 1) - return None + self.manager.end(sub.id, "failed", f"(sub-agent stopped on an error: {cause})") __all__ = ["SubAgentRunner"] diff --git a/app/subagent/types.py b/app/subagent/types.py index 12aabb16..6510566a 100644 --- a/app/subagent/types.py +++ b/app/subagent/types.py @@ -1,11 +1,10 @@ # -*- coding: utf-8 -*- """ -Sub-agent runtime types. +Sub-agent runtime record. -Per-type configuration (system prompt, allowed actions, runtime caps) -lives in :mod:`app.subagent.definitions`, with one file per sub-agent -type registered via :mod:`app.subagent.registry`. This module holds -only the runtime objects that are agnostic to type. +Per-type configuration (system prompt, allowed actions, runtime caps) lives +in :mod:`app.subagent.definitions`, one file per type registered through +:mod:`app.subagent.registry`. This module holds only the record of one run. """ from __future__ import annotations @@ -15,21 +14,8 @@ from typing import List, Optional -# ============================================================================ -# Constants -# ============================================================================ - -# Subagent mode marker — anything that wants to detect sub-agent execution -# (state hooks, telemetry, etc.) can compare ``sub.mode == SUBAGENT_MODE``. -SUBAGENT_MODE = "subagent" - -# Terminal statuses. Anything else means the runner should keep looping. -SUBAGENT_TERMINAL_STATUSES = {"completed", "failed", "timeout", "error"} - - -# ============================================================================ -# SubAgent dataclass -# ============================================================================ +# Terminal statuses. Anything else means the sub-agent is still running. +SUBAGENT_TERMINAL_STATUSES = frozenset({"completed", "failed", "timeout", "error"}) @dataclass @@ -37,58 +23,40 @@ class SubAgent: """ A single sub-agent run. - Deliberately small. Not a Task. Not registered with TaskManager. Not - persisted across process restarts. - - Token usage is intentionally NOT tracked on this object — the LLM - layer's existing ``task_attribution`` mechanism already rolls each - sub-agent's tokens up to the parent task, which is the right - granularity for billing. A separate per-sub-agent counter would be - misleading because it would double-count cached tokens and miss - provider-specific accounting. + Not a Session: it is never persisted, never listed in the UI and lives + only until its run ends. Its LLM usage is attributed to the spawning + session by the LLM layer. """ id: str agent_type: str - parent_task_id: Optional[str] + # The session whose turn spawned it (None: none, the main session's + # workspace and browser are used). + parent_session_id: Optional[str] query: str compiled_actions: List[str] # Lifecycle. Allowed statuses: running | completed | failed | timeout | error. status: str = "running" result: Optional[str] = None + # Turns taken (each turn is one decision, which may batch actions). iterations: int = 0 created_at: str = field(default_factory=lambda: datetime.utcnow().isoformat()) ended_at: Optional[str] = None - # Mode marker — always ``SUBAGENT_MODE`` so downstream code can detect it. - mode: str = SUBAGENT_MODE - - @property - def bootstrap_message(self) -> str: - """The full diagnostic event, also used for exact prompt deduplication.""" - return f"Sub-agent of type '{self.agent_type}' started.\nQuery: {self.query}" - def is_terminal(self) -> bool: """True once the sub-agent has reached any terminal status.""" return self.status in SUBAGENT_TERMINAL_STATUSES def terminate(self, status: str, result: str) -> None: - """Set the terminal status, result, and ``ended_at`` atomically. - - This is the only mutation path used by :class:`SubAgentManager` to - finalize a sub-agent. Keeping the three writes in one place lets a - future change (e.g. emitting a state-change event) hook them as a - single transition. - """ + """Set the terminal status, result, and ``ended_at`` together.""" self.status = status self.result = result self.ended_at = datetime.utcnow().isoformat() __all__ = [ - "SUBAGENT_MODE", "SUBAGENT_TERMINAL_STATUSES", "SubAgent", ] diff --git a/tests/test_context_budget.py b/tests/test_context_budget.py index 014adb82..fa252ff4 100644 --- a/tests/test_context_budget.py +++ b/tests/test_context_budget.py @@ -147,7 +147,7 @@ def test_router_decides_on_the_request_and_restarts_without_ending(): first_call = src.index("if not has_synced_before:") send = src.index("generate_response_with_session_async", first_call) assert "reset_session_history" in src[first_call:send] - assert "end_session_cache" not in src[src.index("No delta events") : send] + assert "end_session_cache" not in src[delta_branch:send] assert "except LLMContextOverflowError" in src @@ -181,17 +181,6 @@ def test_a_restored_session_takes_the_session_path_like_a_new_one(tmp_path): StateSession.end(session_id) -def test_subagent_first_turn_resets_history(): - from pathlib import Path - - import app.subagent.runner as runner - - src = Path(runner.__file__).read_text(encoding="utf-8") - branch = src.index("if not stream.has_session_sync(_SUBAGENT_CALL_TYPE):") - build = src.index("make_first_turn_user_prompt", branch) - assert "_reset_session" in src[branch:build] - - # ------------------------------------------------------------ KV caching diff --git a/tests/test_decision_retries.py b/tests/test_decision_retries.py index df34f642..b7016d57 100644 --- a/tests/test_decision_retries.py +++ b/tests/test_decision_retries.py @@ -262,12 +262,14 @@ def test_a_full_request_carries_the_reason_of_its_reset(monkeypatch, reason): assert llm.sent[1]["metadata"] == {"request": "full", "reason": reason} -def test_no_new_events_starts_a_new_history_labeled_no_delta(monkeypatch): +def test_no_new_events_continue_the_history(monkeypatch): stream, llm = _Stream(), _LLM([END_TURN, END_TURN]) router = _router(monkeypatch, llm, stream) _decide(router) _decide(router) # nothing new since the last request - assert llm.sent[1]["metadata"] == {"request": "full", "reason": "no_delta"} + assert llm.resets == 1 # the first request only + assert llm.sent[1]["metadata"] == {"request": "delta"} + assert llm.sent[1]["user"] == router_module.NO_NEW_EVENTS_PROMPT # ── the event stream's reasons ─────────────────────────────────────────────── diff --git a/tests/test_error_catalog.py b/tests/test_error_catalog.py index 440a4649..388be8af 100644 --- a/tests/test_error_catalog.py +++ b/tests/test_error_catalog.py @@ -140,9 +140,7 @@ def test_llm_consecutive_failure_error_uses_immediate_message_when_flagged(): def test_llm_consecutive_failure_error_auto_derives_immediate_from_count(): """A raise site with failure_count=1 must never say "consecutive - failures" even if it forgot to pass is_immediate=True — e.g. the hard - per-call timeout in app/subagent/runner.py raises with count=1 and no - last_error_info, going through this same constructor.""" + failures" even if it forgot to pass is_immediate=True.""" from agent_core.core.impl.llm.errors import ( LLMConsecutiveFailureError, MSG_CONSECUTIVE_FAILURE, diff --git a/tests/test_fold_summary_on_history.py b/tests/test_fold_summary_on_history.py index f03d8c01..cd3078d2 100644 --- a/tests/test_fold_summary_on_history.py +++ b/tests/test_fold_summary_on_history.py @@ -191,5 +191,5 @@ def test_an_overflow_fold_stays_standalone(): src = inspect.getsource(router_module.ActionRouter._prompt_for_decision) overflow = src[src.index("except LLMContextOverflowError") :] overflow = overflow[: overflow.index("continue")] - assert "self._fold(stream, system_prompt, static_prompt)" in overflow + assert "self._fold, stream, system_prompt, static_prompt" in overflow assert "history=" not in overflow diff --git a/tests/test_general_subagent.py b/tests/test_general_subagent.py index 382e284c..3b82e7e2 100644 --- a/tests/test_general_subagent.py +++ b/tests/test_general_subagent.py @@ -1,22 +1,18 @@ -"""General worker wiring and execution with real tools and scripted LLM decisions.""" +"""General worker wiring: its definition, tools and platform-specific shell. + +Its runtime behaviour is pinned with every other type in +test_subagent_runtime.py. +""" -import asyncio -import json import platform import runpy -from collections import deque from pathlib import Path -from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock +from unittest.mock import Mock import pytest from agent_core import load_actions_from_directories, registry_instance -from agent_core.core.action import Action -from agent_core.core.impl.action.manager import ActionManager -from app.event_stream import EventStreamManager -from app.internal_action_interface import InternalActionInterface -from app.subagent import SubAgentManager, SubAgentRunner, get_subagent_definition +from app.subagent import get_subagent_definition REPO_ROOT = Path(__file__).resolve().parent.parent @@ -40,8 +36,8 @@ def test_definition_is_discovered_with_resolvable_tools(registry): assert not {"spawn_subagent", "send_message", "add_action_sets", "use_skill"} & set( definition.actions ) - prompt = definition.system_prompt.format(action_list="TOOLS", output_format="JSON") - assert "TOOLS" in prompt and "JSON" in prompt + # The type's own prompt only: the runtime appends and the format. + assert "{" not in definition.system_prompt spawn = registry.find_action_by_name("spawn_subagent") assert "general_agent" in spawn["input_schema"]["agent_type"]["enum"] assert definition.description in spawn["description"] @@ -58,124 +54,3 @@ def test_definition_only_offers_powershell_on_windows(monkeypatch, system): actions = register.call_args.kwargs["actions"] assert "run_shell" in actions assert ("run_powershell" in actions) == (system == "Windows") - - -@pytest.fixture -def runtime(registry, monkeypatch): - llm = Mock() - events = EventStreamManager(llm=llm) - manager = SubAgentManager(event_stream_manager=events, llm_interface=llm) - library = SimpleNamespace( - retrieve_action=lambda name: Action.from_dict( - registry.find_action_by_name(name) - ) - ) - actions = ActionManager( - action_library=library, - llm_interface=llm, - db_interface=Mock(), - event_stream_manager=events, - context_engine=Mock(), - state_manager=Mock(), - ) - runner = SubAgentRunner(manager, actions, library, events, llm) - monkeypatch.setattr(InternalActionInterface, "subagent_manager", manager) - return SimpleNamespace( - llm=llm, events=events, manager=manager, actions=actions, runner=runner - ) - - -@pytest.mark.parametrize( - ("peer_type", "peer_status"), - [ - ("general_agent", "completed"), - ("research_agent", "completed"), - ("general_agent", "failed"), - ], -) -def test_parallel_workers_use_real_tools_and_isolate_context( - runtime, monkeypatch, tmp_path, peer_type, peer_status -): - workers = [] - decisions = {} - prompts = {} - outputs = [] - for index, agent_type in enumerate(("general_agent", peer_type)): - marker = f"private-worker-{index}" - source = tmp_path / f"input-{index}.txt" - source.write_text(marker, encoding="utf-8") - output = tmp_path / f"output-{index}.txt" - sub = runtime.manager.spawn(agent_type, query=marker, parent_task_id="parent") - workers.append(sub) - prompts[sub.id] = [] - steps = [{"action_name": "read_file", "parameters": {"file_path": str(source)}}] - if agent_type == "general_agent": - steps.append( - { - "action_name": "write_file", - "parameters": {"file_path": str(output), "content": marker}, - } - ) - outputs.append((output, marker)) - steps.append( - { - "action_name": "sub_task_end", - "parameters": { - "status": peer_status if index else "completed", - "result": marker, - }, - } - ) - decisions[sub.id] = deque(steps) - - ready = set() - - async def invoke(sub, user_prompt, system_prompt): - prompts[sub.id].append(user_prompt) - # Neither worker can proceed unless the existing runner runs both - # concurrently; no live provider or timing-based assertion is needed. - ready.add(sub.id) - while len(ready) < len(workers): - await asyncio.sleep(0) - return json.dumps(decisions[sub.id].popleft()) - - monkeypatch.setattr(runtime.runner, "_invoke_llm", invoke) - - async def run(): - return await asyncio.wait_for( - asyncio.gather(*(runtime.runner.run_to_completion(sub) for sub in workers)), - timeout=15, - ) - - results = asyncio.run(run()) - assert [sub.status for sub in results] == ["completed", peer_status] - assert [sub.result for sub in results] == [sub.query for sub in workers] - for path, marker in outputs: - assert path.read_text(encoding="utf-8") == marker - for index, sub in enumerate(workers): - assert sub.query in prompts[sub.id][0] - assert workers[1 - index].query not in "\n".join(prompts[sub.id]) - assert not runtime.events.has_stream(sub.id) - runtime.llm.end_all_session_caches.assert_any_call(sub.id) - assert runtime.actions.inflight_ids() == set() - - -def test_general_worker_cannot_delegate_or_message(runtime): - sub = runtime.manager.spawn("general_agent", query="Read-only analysis") - execute = AsyncMock() - runtime.runner.action_manager = SimpleNamespace(execute_action=execute) - - async def run(): - for name in ("spawn_subagent", "send_message"): - await runtime.runner._dispatch_action( - sub, {"action_name": name, "parameters": {}} - ) - - try: - asyncio.run(run()) - execute.assert_not_awaited() - log = runtime.events.snapshot_by_id(sub.id) - assert "Disallowed action" in log - assert "spawn_subagent" in log and "send_message" in log - finally: - runtime.manager.release(sub.id) diff --git a/tests/test_mini_browser_agent_integration.py b/tests/test_mini_browser_agent_integration.py index 57760071..bc18ddc1 100644 --- a/tests/test_mini_browser_agent_integration.py +++ b/tests/test_mini_browser_agent_integration.py @@ -1098,6 +1098,9 @@ class _Context: def get_session_state(self, session_id=None): return "" + def get_compiled_actions(self, session_id=None): + return [] + def get_event_stream(self, session_id=None, up_to=None): return "" @@ -1107,7 +1110,6 @@ class _Stop(Exception): def run_selection(prompt_filter): seen = {} router = ActionRouter(object(), object(), _Context(), prompt_filter) - monkeypatch.setattr(router, "_get_session_compiled_actions", lambda **k: []) monkeypatch.setattr( router, "_build_candidates_from_compiled_list", lambda *a, **k: [] ) @@ -1290,14 +1292,11 @@ def test_browser_agent_is_registered_with_existing_actions(registry): registered = registry.list_all_actions() for name in actions: assert name in registered, f"browser_agent lists unknown action {name}" - assert set(definition.compact_actions) <= actions assert definition.max_iterations > 0 and definition.max_wall_seconds > 0 - prompt = definition.system_prompt.format( - action_list="", output_format="" - ) - assert "" in prompt and "" in prompt - assert '{"action_name": ""' in prompt + # The type's own prompt only: the runtime appends and the + # reply format (SUBAGENT_DECISION_INSTRUCTIONS). + assert "{" not in definition.system_prompt spawn = registry.find_action_by_name("spawn_subagent") assert "browser_agent" in spawn["input_schema"]["agent_type"]["enum"] diff --git a/tests/test_mini_browser_engine.py b/tests/test_mini_browser_engine.py index 9301cb11..26ed3fc1 100644 --- a/tests/test_mini_browser_engine.py +++ b/tests/test_mini_browser_engine.py @@ -163,7 +163,7 @@ def test_workspace_paths_follow_the_owner(monkeypatch, tmp_path): }, subagents={ "sub_1234abcd": types.SimpleNamespace( - parent_task_id="chat-1", + parent_session_id="chat-1", agent_type="browser_agent", created_at="2026-01-01T00:00:00", ) @@ -1045,7 +1045,7 @@ def test_release_owner_closes_its_tabs(eng, monkeypatch): sessions={}, subagents={ "sub_leaver01": types.SimpleNamespace( - parent_task_id=SESSION, + parent_session_id=SESSION, agent_type="browser_agent", created_at=datetime.utcnow().isoformat(), ) @@ -1084,7 +1084,7 @@ def test_owner_labels_and_kinds(eng, monkeypatch): }, subagents={ "sub_label01": types.SimpleNamespace( - parent_task_id="chat-7", + parent_session_id="chat-7", agent_type="browser_agent", created_at=datetime.utcnow().isoformat(), ) @@ -1601,10 +1601,10 @@ def test_revoked_subagents_get_stopped(eng, monkeypatch): before = (datetime.utcnow() - timedelta(minutes=1)).isoformat() subs = { "sub_known001": types.SimpleNamespace( - parent_task_id="chat-p", agent_type="browser_agent", created_at=before + parent_session_id="chat-p", agent_type="browser_agent", created_at=before ), "sub_unseen01": types.SimpleNamespace( - parent_task_id="chat-p", agent_type="browser_agent", created_at=before + parent_session_id="chat-p", agent_type="browser_agent", created_at=before ), } _fake_agent_runtime(monkeypatch, sessions={}, subagents=subs) @@ -1617,7 +1617,7 @@ def test_revoked_subagents_get_stopped(eng, monkeypatch): assert eng.op("sub_unseen01", "echo")["error_code"] == "MINI_BROWSER_STOPPED" # A sub-agent started after the stop (a new run), and the parent itself, carry on. subs["sub_later001"] = types.SimpleNamespace( - parent_task_id="chat-p", + parent_session_id="chat-p", agent_type="browser_agent", created_at=(datetime.utcnow() + timedelta(seconds=1)).isoformat(), ) diff --git a/tests/test_mini_browser_engine_fixes.py b/tests/test_mini_browser_engine_fixes.py index 7c88b575..c95cf5f5 100644 --- a/tests/test_mini_browser_engine_fixes.py +++ b/tests/test_mini_browser_engine_fixes.py @@ -1000,7 +1000,7 @@ def test_stop_before_the_host_starts_still_revokes_subagents(tmp_path, monkeypat sessions={"chat-x": types.SimpleNamespace(title="Chat X", workspace_dir=None)}, subagents={ "sub_early001": types.SimpleNamespace( - parent_task_id="chat-x", agent_type="browser_agent", created_at=created + parent_session_id="chat-x", agent_type="browser_agent", created_at=created ) }, ) diff --git a/tests/test_mini_browser_fleet.py b/tests/test_mini_browser_fleet.py index 6b20e4b3..cab63213 100644 --- a/tests/test_mini_browser_fleet.py +++ b/tests/test_mini_browser_fleet.py @@ -350,7 +350,7 @@ def test_a_sub_agent_browses_in_its_parent_sessions_browser(site, paths, monkeyp {"chat-a": session("Holiday plans")}, { "sub_child001": types.SimpleNamespace( - parent_task_id="chat-a", + parent_session_id="chat-a", agent_type="browser_agent", created_at=datetime.utcnow().isoformat(), ) diff --git a/tests/test_subagent_bootstrap_prompt.py b/tests/test_subagent_bootstrap_prompt.py deleted file mode 100644 index 7444010d..00000000 --- a/tests/test_subagent_bootstrap_prompt.py +++ /dev/null @@ -1,123 +0,0 @@ -"""T18: render an exact bootstrap duplicate by reference, without mutating it.""" - -import json -from unittest.mock import Mock - -import pytest - -from agent_core.core.event_stream.event import EventRecord -from agent_core.core.impl.event_stream.manager import EventStreamManager -from app.subagent.context_engine import SubAgentContextEngine -from app.subagent.manager import SubAgentManager -from app.subagent.runner import SubAgentRunner, _SUBAGENT_CALL_TYPE - - -@pytest.fixture -def runtime(): - llm = Mock() - events = EventStreamManager(llm=llm) - manager = SubAgentManager(events, llm) - query = "\n".join( - f"Constraint {i}: preserve C:/sources/{i}.txt and /tmp/source-{i}; do not send messages." - for i in range(40) - ) - sub = manager.spawn("general_agent", query) - runner = SubAgentRunner(manager, Mock(), Mock(), events, llm) - return sub, events, runner - - -def test_initial_prompt_keeps_query_once_and_records_remain_complete(runtime): - sub, events, runner = runtime - stream = events.get_stream_by_id(sub.id) - before = [r.to_dict() for r in stream.tail_events] - prompt, first = runner._build_user_prompt(sub, stream) - assert first and prompt.count(sub.query) == 1 - assert "Query: see QUERY FROM SPAWNING AGENT above." in prompt - assert [r.to_dict() for r in stream.tail_events] == before - assert sub.bootstrap_message in events.snapshot_by_id(sub.id) - - -@pytest.mark.parametrize( - "phase", - ["restore", "fold_removed_bootstrap", "fold_retained_bootstrap", "no_delta"], -) -def test_every_fresh_context_contains_the_complete_query(runtime, phase): - sub, events, runner = runtime - stream = events.get_stream_by_id(sub.id) - stream.mark_session_synced(_SUBAGENT_CALL_TYPE) - if phase == "restore": - records = [ - EventRecord.from_dict(json.loads(json.dumps(r.to_dict()))) - for r in stream.tail_events - ] - stream.clear() - stream.tail_events = records - elif phase.startswith("fold"): - stream.head_summary = "Previous work, with open items." - if phase == "fold_removed_bootstrap": - stream.tail_events = [] - stream.reset_session_sync(_SUBAGENT_CALL_TYPE, "fold") - prompt, first = runner._build_user_prompt(sub, stream) - assert first and prompt.count(sub.query) == 1 - assert all(f"Constraint {i}:" in prompt for i in range(40)) - if phase.startswith("fold"): - assert "Previous work, with open items." in prompt - - -def test_different_bootstrap_is_never_abbreviated(runtime): - sub, events, runner = runtime - stream = events.get_stream_by_id(sub.id) - record = next(r for r in stream.tail_events if r.event.kind == "subagent_start") - record.event.message += "\nDo not modify any source files." - original = record.event.message - prompt = runner.context_engine.make_first_turn_user_prompt(sub) - assert original in prompt - assert "Query: see QUERY" not in prompt - assert sub.query in prompt - - -def test_matching_text_in_another_event_is_not_rewritten(runtime): - sub, events, runner = runtime - events.log("quotation", sub.bootstrap_message, task_id=sub.id) - prompt = runner.context_engine.make_first_turn_user_prompt(sub) - assert sub.bootstrap_message in prompt - assert "Query: see QUERY" in prompt - - -def test_delta_does_not_resend_query_or_change_the_cached_first_turn(runtime): - sub, events, runner = runtime - stream = events.get_stream_by_id(sub.id) - first, _ = runner._build_user_prompt(sub, stream) - stream.mark_session_synced(_SUBAGENT_CALL_TYPE) - events.log("progress", "Read the source", task_id=sub.id) - delta, is_first = runner._build_user_prompt(sub, stream) - assert not is_first and sub.query not in delta - assert "Read the source" in delta - assert first.count(sub.query) == 1 - - -def test_long_query_needs_no_retrieval_and_keeps_every_constraint(): - events = EventStreamManager(llm=None) - manager = SubAgentManager(events, Mock()) - query = "\n".join( - f"Constraint {i}: " + ("source evidence, " * 25) for i in range(120) - ).rstrip() - sub = manager.spawn("general_agent", query) - engine = SubAgentContextEngine(Mock(), events) - prompt = engine.make_first_turn_user_prompt(sub) - assert len(query) > 42059 - assert prompt.count(query) == 1 - assert sub.query == query - assert sub.bootstrap_message in events.snapshot_by_id(sub.id) - - -def test_query_whitespace_is_not_normalized_to_force_a_match(): - events = EventStreamManager(llm=None) - manager = SubAgentManager(events, Mock()) - sub = manager.spawn("general_agent", "Preserve this exact query.\n\n") - prompt = SubAgentContextEngine(Mock(), events).make_first_turn_user_prompt(sub) - # Event logging strips surrounding whitespace. Equality cannot be proved, - # so keep its text and the complete standalone query, including newlines. - assert sub.query in prompt - assert "Query: see QUERY" not in prompt - assert prompt.count("Preserve this exact query.") == 2 diff --git a/tests/test_subagent_runtime.py b/tests/test_subagent_runtime.py new file mode 100644 index 00000000..e36182a9 --- /dev/null +++ b/tests/test_subagent_runtime.py @@ -0,0 +1,553 @@ +# -*- coding: utf-8 -*- +"""A sub-agent works like the main agent, on a context of its own. + +It decides with the main agent's ActionRouter and AgentStep and runs actions +with the same ActionManager, against a scripted LLM and real tools. These +tests pin: + +* its context: the type's prompt and actions, the query once in the first + request, then only new events; nothing of another agent's context; +* the main loop's behaviour it inherits: parallel batches, retry feedback as + the next turn, reasoning in the stream referred to (not repeated), folds; +* its own rules: only its actions run, the early-end guard (not on the final + turn), the budget statement and warning, the turn and time caps; +* its lifecycle: a workspace inside the spawning session's, Stop cancels it, + and a finished sub-agent is released and forgotten. +""" + +from __future__ import annotations + +import asyncio +import json +from collections import deque +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from agent_core import load_actions_from_directories, registry_instance +from agent_core.core.action import Action +from agent_core.core.event_stream.event import EventType +from agent_core.core.impl.action import router as router_module +from agent_core.core.impl.action.manager import ActionManager +from agent_core.core.impl.llm.interface import LLMContextOverflowError +from app import config as app_config +from app.event_stream import EventStreamManager +from app.internal_action_interface import InternalActionInterface +from app.subagent import ( + SubAgentDefinition, + SubAgentManager, + SubAgentRunner, + get_subagent_definition, + list_subagent_names, +) +from app.subagent import registry as registry_module + +REPO_ROOT = Path(__file__).resolve().parent.parent + + +def _reply(*actions, reasoning="Next step."): + return json.dumps( + { + "reasoning": reasoning, + "actions": [ + {"action_name": name, "parameters": params} for name, params in actions + ], + } + ) + + +def _end(result="done", status="completed"): + return _reply(("sub_task_end", {"status": status, "result": result})) + + +class _FakeLLM: + """Answers each sub-agent's requests from its script (``replies[sub_id]``, + else ``replies[None]``): a reply string, an exception to raise, or a + callable (sync or async) returning either.""" + + def __init__(self): + self.replies = {} + self.sent = {} + self.caches = {} + self.resets = 0 + self.fits = True + self.on_history = [] + self.standalone = 0 + self.ended = [] + + def create_session_cache(self, task_id, call_type, system_prompt): + self.caches[task_id] = system_prompt + return task_id + + def has_session_cache(self, task_id, call_type): + return task_id in self.caches + + def reset_session_history(self, task_id, call_type): + self.resets += 1 + + def fits_context(self, task_id, call_type, system_prompt, pending): + return self.fits + + def input_budget(self): + return 1_000_000 + + def session_turn_recorded(self, task_id, call_type): + return True + + def checkpoint_session(self, *args): + pass + + def end_all_session_caches(self, task_id): + self.ended.append(task_id) + self.caches.pop(task_id, None) + + async def generate_response_with_session_async( + self, + task_id, + call_type, + user_prompt, + system_prompt_for_new_session=None, + prompt_name=None, + call_metadata=None, + ): + self.sent.setdefault(task_id, []).append( + { + "user": user_prompt, + "system": system_prompt_for_new_session, + "metadata": call_metadata, + "prompt_name": prompt_name, + } + ) + script = self.replies.get(task_id) or self.replies[None] + reply = script.popleft() + if callable(reply): + reply = reply() + if asyncio.iscoroutine(reply): + reply = await reply + if isinstance(reply, BaseException): + raise reply + return reply + + def generate_side_response_with_session( + self, task_id, call_type, user_prompt, system_prompt, **kwargs + ): + self.on_history.append(task_id) + return '{"summary": "SUMMARY ON HISTORY"}' + + def generate_response(self, *args, **kwargs): + self.standalone += 1 + return "STANDALONE SUMMARY" + + def script(self, sub_id, *replies): + self.replies[sub_id] = deque(replies) + + +@pytest.fixture(scope="module") +def registry(): + load_actions_from_directories( + base_dir=str(REPO_ROOT), paths_to_scan=["app/data/action"] + ) + return registry_instance + + +@pytest.fixture +def runtime(registry, tmp_path, monkeypatch): + llm = _FakeLLM() + events = EventStreamManager(llm=llm) + # The router finds a session's stream through the global registry. + monkeypatch.setattr(router_module, "get_event_stream_manager", lambda: events) + + def retrieve(name): + found = registry.find_action_by_name(name) + return Action.from_dict(found) if found else None + + library = SimpleNamespace(retrieve_action=retrieve) + actions = ActionManager( + action_library=library, + llm_interface=llm, + db_interface=Mock(), + event_stream_manager=events, + context_engine=Mock(), + state_manager=Mock(), + ) + parent = SimpleNamespace(id="parent", workspace_dir=str(tmp_path / "parent")) + main = SimpleNamespace(id="main", workspace_dir=str(tmp_path / "main")) + sessions = SimpleNamespace( + get=lambda sid: parent if sid == "parent" else None, main=main + ) + manager = SubAgentManager(events, llm, library, actions, sessions) + monkeypatch.setattr(InternalActionInterface, "subagent_manager", manager) + + # What each stream held when it was released (streams go with the run). + released = {} + events.add_removal_listener( + lambda sid, stream: released.__setitem__(sid, list(stream.tail_events)) + ) + return SimpleNamespace( + llm=llm, events=events, manager=manager, actions=actions, released=released + ) + + +def _spawn(runtime, agent_type="general_agent", query="Read the file.", parent="parent"): + return runtime.manager.spawn(agent_type, query, parent_session_id=parent) + + +def _run(runtime, *subs): + async def go(): + return await asyncio.wait_for( + asyncio.gather(*(runtime.manager.run(sub) for sub in subs)), timeout=30 + ) + + return asyncio.run(go()) + + +def _tiny(monkeypatch, name="tiny_agent", **overrides): + """A test-only type: general_agent's actions with small caps.""" + general = get_subagent_definition("general_agent") + fields = { + "name": name, + "description": "test type", + "system_prompt": "You are a test sub-agent.", + "actions": general.actions, + "max_iterations": 10, + "max_wall_seconds": 60, + **overrides, + } + monkeypatch.setitem(registry_module._REGISTRY, name, SubAgentDefinition(**fields)) + return name + + +# ── context ────────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("agent_type", list_subagent_names()) +def test_every_type_decides_on_its_own_prompt_and_actions(runtime, agent_type): + sub = _spawn(runtime, agent_type) + try: + runner = SubAgentRunner(runtime.manager, sub) + system = runner.context.make_prompt()[0] + instructions = runner.router.decision_instructions(sub.id) + definition = get_subagent_definition(agent_type) + assert system.startswith(definition.system_prompt.strip()) + assert "" in system + for name in definition.actions: + assert f'"name":"{name}"' in instructions, name + assert '"actions": [' in instructions # the main agent's reply format + # Nothing of the main agent's own rules or catalog. + assert "Message Routing" not in system + instructions + assert "capability_catalog" not in system + instructions + finally: + runtime.manager.release(sub.id) + + +def test_the_first_request_holds_the_query_once_then_only_new_events( + runtime, tmp_path +): + source = tmp_path / "input.txt" + source.write_text("FILE-CONTENT-MARKER", encoding="utf-8") + query = "Read input.txt and report its content." + sub = _spawn(runtime, query=query) + runtime.llm.script( + sub.id, + _reply(("read_file", {"file_path": str(source)}), reasoning="Read it first."), + _end("FILE-CONTENT-MARKER"), + ) + _run(runtime, sub) + + first, second = runtime.llm.sent[sub.id] + assert first["metadata"] == {"request": "full", "reason": "first"} + assert first["user"].count(query) == 1 + assert "Budget: up to 40 turns and 15 minutes" in first["user"] + assert first["prompt_name"] == "SUBAGENT_GENERAL_AGENT" + assert "general-purpose sub-agent" in first["system"] + + assert second["metadata"] == {"request": "delta"} + assert query not in second["user"] + assert "FILE-CONTENT-MARKER" in second["user"] + # The reply the history ends with is referred to, not repeated. + assert "input as in your reply above" in second["user"] + assert "Read it first." not in second["user"] + assert runtime.llm.resets == 1 # only the first request started a history + + kinds = [r.event.event_type for r in runtime.released[sub.id]] + assert EventType.REASONING in kinds + assert (sub.status, sub.result, sub.iterations) == ( + "completed", + "FILE-CONTENT-MARKER", + 2, + ) + + +def test_parallel_sub_agents_keep_their_contexts_apart(runtime, tmp_path): + subs, ready = [], set() + for index in range(2): + marker = f"private-worker-{index}" + source = tmp_path / f"input-{index}.txt" + source.write_text(marker, encoding="utf-8") + output = tmp_path / f"output-{index}.txt" + sub = _spawn(runtime, query=marker) + subs.append((sub, output, marker)) + + async def first_turn(sub=sub, source=source, output=output, marker=marker): + # Neither proceeds until both are running: they run concurrently. + ready.add(sub.id) + while len(ready) < 2: + await asyncio.sleep(0) + return _reply( + ("read_file", {"file_path": str(source)}), + ("write_file", {"file_path": str(output), "content": marker}), + ) + + runtime.llm.script(sub.id, first_turn, _end(marker)) + + _run(runtime, *(sub for sub, _, _ in subs)) + + for index, (sub, output, marker) in enumerate(subs): + other = subs[1 - index][2] + sent = "\n".join(r["user"] for r in runtime.llm.sent[sub.id]) + assert other not in sent + assert output.read_text(encoding="utf-8") == marker + assert (sub.status, sub.result, sub.iterations) == ("completed", marker, 2) + assert runtime.actions.inflight_ids() == set() + + +# ── the main loop's behaviour ──────────────────────────────────────────────── + + +def test_a_reply_that_does_not_parse_is_corrected_as_the_next_turn(runtime): + sub = _spawn(runtime) + runtime.llm.script(sub.id, "not json at all", _end()) + _run(runtime, sub) + + first, retry = runtime.llm.sent[sub.id] + assert retry["metadata"] == {"request": "correction"} + assert retry["user"].startswith("Previous attempt 1 failed to parse") + assert sub.query not in retry["user"] + assert runtime.llm.resets == 1 + assert (sub.status, sub.iterations) == ("completed", 1) + + +def test_prose_around_the_reply_costs_no_retry(runtime): + sub = _spawn(runtime) + runtime.llm.script(sub.id, f"I'll finish now.\n```json\n{_end()}\n```") + _run(runtime, sub) + assert len(runtime.llm.sent[sub.id]) == 1 + assert sub.status == "completed" + + +def _work(runtime, sub, n=100): + for i in range(n): + runtime.events.log("action_end", f"page {i} " + "x " * 50, task_id=sub.id) + + +@pytest.fixture +def small_keep(monkeypatch): + settings = {"context": {"keep_recent_tokens": 500}} + monkeypatch.setattr(app_config, "get_settings", lambda *a, **k: settings) + + +def test_a_request_that_would_not_fit_folds_on_the_history( + runtime, tmp_path, small_keep +): + source = tmp_path / "input.txt" + source.write_text("content", encoding="utf-8") + read = _reply(("read_file", {"file_path": str(source)})) + sub = _spawn(runtime) + + def work_then_read(): + _work(runtime, sub) # carried by the next request + return read + + def overflow_next_then_read(): + runtime.llm.fits = False + return read + + runtime.llm.script( + sub.id, work_then_read, overflow_next_then_read, lambda: _end() + ) + _run(runtime, sub) + + folded = runtime.llm.sent[sub.id][2] + assert runtime.llm.on_history == [sub.id] and runtime.llm.standalone == 0 + assert folded["metadata"] == {"request": "full", "reason": "fold"} + assert "SUMMARY ON HISTORY" in folded["user"] + assert folded["user"].count(sub.query) == 1 + assert sub.status == "completed" + + +def test_a_refused_request_folds_once_and_is_resent_whole( + runtime, tmp_path, small_keep +): + source = tmp_path / "input.txt" + source.write_text("content", encoding="utf-8") + read = _reply(("read_file", {"file_path": str(source)})) + sub = _spawn(runtime) + + def work_then_read(): + _work(runtime, sub) + return read + + runtime.llm.script( + sub.id, + work_then_read, + read, + LLMContextOverflowError("request too large"), + _end(), + ) + _run(runtime, sub) + + resent = runtime.llm.sent[sub.id][3] + assert runtime.llm.standalone == 1 and runtime.llm.on_history == [] + assert resent["metadata"] == {"request": "full", "reason": "overflow"} + assert "STANDALONE SUMMARY" in resent["user"] + assert resent["user"].count(sub.query) == 1 + assert sub.status == "completed" + + +# ── its own rules ──────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("name", ["send_message", "spawn_subagent"]) +def test_an_action_outside_its_definition_never_runs(runtime, name): + sub = _spawn(runtime) + runtime.llm.script(sub.id, _reply((name, {"message": "hi"})), _end()) + _run(runtime, sub) + + delta = runtime.llm.sent[sub.id][1]["user"] + assert f"'{name}' is not one of your actions" in delta + assert f"Running action {name}" not in delta + assert sub.status == "completed" + + +def test_the_early_end_guard_refuses_until_the_final_turn(runtime, monkeypatch): + refused = "Return the verdict as JSON." + agent_type = _tiny( + monkeypatch, max_iterations=3, early_end_guard=lambda sub, params: refused + ) + sub = _spawn(runtime, agent_type) + runtime.llm.script(sub.id, _end("first"), _end("second"), _end("third")) + _run(runtime, sub) + + sent = runtime.llm.sent[sub.id] + assert refused in sent[1]["user"] and refused in sent[2]["user"] + # The final turn ends: the guard can never trap a run into the cap. + assert (sub.status, sub.result, sub.iterations) == ("completed", "third", 3) + + +def test_the_turn_cap_ends_the_run_and_warns_once_before(runtime, tmp_path, monkeypatch): + source = tmp_path / "input.txt" + source.write_text("content", encoding="utf-8") + sub = _spawn(runtime, _tiny(monkeypatch, max_iterations=10)) + runtime.llm.script( + sub.id, *[_reply(("read_file", {"file_path": str(source)}))] * 10 + ) + _run(runtime, sub) + + warned = [ + i + for i, r in enumerate(runtime.llm.sent[sub.id]) + if "Turn budget: 2 of 10 turns left" in r["user"] + ] + assert warned == [8] # turn 9: a fifth of the turns left + assert "Budget: up to 10 turns" in runtime.llm.sent[sub.id][0]["user"] + assert (sub.status, sub.iterations) == ("failed", 10) + assert "used all 10 turns" in sub.result + + +def test_the_time_cap_cancels_the_call_in_flight(runtime, monkeypatch): + sub = _spawn(runtime, _tiny(monkeypatch, max_wall_seconds=0.2)) + + async def never(): + await asyncio.sleep(30) + + runtime.llm.script(sub.id, never) + _run(runtime, sub) + assert sub.status == "timeout" + assert not runtime.events.has_stream(sub.id) + + +def test_an_unavailable_llm_ends_the_run_with_its_cause(runtime): + from agent_core.core.impl.llm.errors import LLMConsecutiveFailureError + + sub = _spawn(runtime) + runtime.llm.script(sub.id, LLMConsecutiveFailureError(5)) + _run(runtime, sub) + assert sub.status == "failed" and sub.iterations == 1 + assert "stopped on an error" in sub.result + + +# ── lifecycle ──────────────────────────────────────────────────────────────── + + +def test_its_workspace_is_inside_the_spawning_session(runtime, tmp_path): + child = _spawn(runtime) + orphan = _spawn(runtime, parent="unknown") + try: + streams = runtime.events + assert Path(streams.get_stream_by_id(child.id).temp_dir) == ( + tmp_path / "parent" / child.id + ) + assert Path(streams.get_stream_by_id(orphan.id).temp_dir) == ( + tmp_path / "main" / orphan.id + ) + assert (tmp_path / "parent" / child.id).is_dir() + finally: + runtime.manager.release(child.id) + runtime.manager.release(orphan.id) + + +def test_a_finished_sub_agent_is_released_and_forgotten(runtime): + sub = _spawn(runtime) + runtime.llm.script(sub.id, _end()) + _run(runtime, sub) + assert runtime.manager.get(sub.id) is None + assert not runtime.events.has_stream(sub.id) + assert sub.id in runtime.llm.ended + # Released after sub_task_end's own action_end, which follows the end. + kinds = [r.event.kind for r in runtime.released[sub.id]] + assert kinds[-2:] == ["subagent_end", "action_end"] + + +def test_stopping_the_spawning_run_stops_the_sub_agent(runtime): + sub = _spawn(runtime) + started = asyncio.Event() + + async def hang(): + started.set() + await asyncio.sleep(30) + + runtime.llm.script(sub.id, hang) + + async def go(): + task = asyncio.create_task(runtime.manager.run(sub)) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + asyncio.run(go()) + assert sub.status == "failed" + assert "stopped with the run that spawned it" in sub.result + assert runtime.manager.get(sub.id) is None + assert not runtime.events.has_stream(sub.id) + + +def test_spawn_subagent_runs_on_the_spawning_loop_and_returns_the_result(runtime): + from app.data.action.spawn_subagent import spawn_subagent + + runtime.llm.script(None, _end("THE RESULT")) + output = asyncio.run( + spawn_subagent( + { + "agent_type": "general_agent", + "query": "Answer.", + "_session_id": "parent", + } + ) + ) + assert output["status"] == "completed" + assert output["result"] == "THE RESULT" + assert output["iterations"] == 1 + assert runtime.manager.get(output["child_task_id"]) is None From 4842d833b4ff8a96c96c476e30e39fe27c509239 Mon Sep 17 00:00:00 2001 From: zfoong Date: Mon, 16 Nov 2026 10:43:48 +0900 Subject: [PATCH 6/6] rebuild subagents on the main agent's decision loop and stop requirement checks from blocking the event loop --- agent_core/core/impl/action/executor.py | 142 ++++++++++++--------- app/subagent/definitions/research_agent.py | 6 +- tests/test_action_requirements.py | 70 ++++++++++ 3 files changed, 154 insertions(+), 64 deletions(-) create mode 100644 tests/test_action_requirements.py diff --git a/agent_core/core/impl/action/executor.py b/agent_core/core/impl/action/executor.py index 083f3d7b..a6d27361 100644 --- a/agent_core/core/impl/action/executor.py +++ b/agent_core/core/impl/action/executor.py @@ -21,11 +21,12 @@ import subprocess import sys import tempfile +import threading import uuid import venv from pathlib import Path from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Set, Tuple from agent_core.utils.logger import logger from agent_core.utils.windows_process import hidden_console_kwargs @@ -47,6 +48,13 @@ # Base packages that must be installed in the sandbox venv (empty - venv isolation is the sandbox) _SANDBOX_BASE_PACKAGES = [] +# Requirements settled in this process, as (python_bin, entry): confirmed +# installed, or not a pip package at all. Installed packages stay installed, +# so each is checked once instead of on every call (a ``pip show`` costs +# ~1.5 s). The lock makes concurrent first calls wait for one check. +_SETTLED_REQUIREMENTS: Set[Tuple[Optional[str], str]] = set() +_REQUIREMENTS_LOCK = threading.Lock() + class _HiddenEnvBuilder(venv.EnvBuilder): """Keep ensurepip's interpreter and installer children hidden too.""" @@ -203,69 +211,78 @@ def _ensure_requirements( if not requirements: return - pip_python = python_bin or _find_system_python() - if not pip_python: - logger.warning( - "[REQUIREMENTS] No Python interpreter found on PATH; cannot install packages." - ) - return - - installed_any = False - for pkg in requirements: - pkg = pkg.strip() - if not pkg: - continue - - # Heuristic: skip entries that look like class names - # (e.g. "DDGS", "ClientSession", "build") rather than pip - # packages. Pip packages are lowercase and may contain - # hyphens/underscores/dots. - if not pkg[0].islower() and "-" not in pkg: - continue - - # Derive the importable module name for the quick check. - # Only useful when NOT frozen (in-process imports work). - import_name = pkg.replace("-", "_").split("[")[0] - - # First try a fast import check (works for most packages) - if not getattr(sys, "frozen", False): + with _REQUIREMENTS_LOCK: + pending = [ + pkg + for pkg in (entry.strip() for entry in requirements) + if pkg and (python_bin, pkg) not in _SETTLED_REQUIREMENTS + ] + if not pending: + return + + pip_python = python_bin or _find_system_python() + if not pip_python: + logger.warning( + "[REQUIREMENTS] No Python interpreter found on PATH; cannot install packages." + ) + return + + installed_any = False + for pkg in pending: + # Heuristic: skip entries that look like class names + # (e.g. "DDGS", "ClientSession", "build") rather than pip + # packages. Pip packages are lowercase and may contain + # hyphens/underscores/dots. + if not pkg[0].islower() and "-" not in pkg: + _SETTLED_REQUIREMENTS.add((python_bin, pkg)) + continue + + # Derive the importable module name for the quick check. + # Only useful when NOT frozen (in-process imports work). + import_name = pkg.replace("-", "_").split("[")[0] + + # First try a fast import check (works for most packages) + if not getattr(sys, "frozen", False): + try: + importlib.import_module(import_name) + _SETTLED_REQUIREMENTS.add((python_bin, pkg)) + continue # already installed + except ImportError: + pass + + # If import failed (or frozen), use pip show to check. + # This handles packages where pip name != import name + # (e.g., beautifulsoup4 -> bs4, Pillow -> PIL) try: - importlib.import_module(import_name) + subprocess.check_call( + [str(pip_python), "-m", "pip", "show", "--quiet", pkg], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=15, + **hidden_console_kwargs(), + ) + _SETTLED_REQUIREMENTS.add((python_bin, pkg)) continue # already installed - except ImportError: + except Exception: pass - # If import failed (or frozen), use pip show to check. - # This handles packages where pip name != import name - # (e.g., beautifulsoup4 -> bs4, Pillow -> PIL) - try: - subprocess.check_call( - [str(pip_python), "-m", "pip", "show", "--quiet", pkg], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=15, - **hidden_console_kwargs(), - ) - continue # already installed - except Exception: - pass - - try: - subprocess.check_call( - [str(pip_python), "-m", "pip", "install", "--quiet", pkg], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=120, - **hidden_console_kwargs(), - ) - installed_any = True - logger.info(f"[REQUIREMENTS] Installed '{pkg}'") - except Exception as e: - logger.warning(f"[REQUIREMENTS] Failed to install '{pkg}': {e}") + try: + subprocess.check_call( + [str(pip_python), "-m", "pip", "install", "--quiet", pkg], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=120, + **hidden_console_kwargs(), + ) + installed_any = True + _SETTLED_REQUIREMENTS.add((python_bin, pkg)) + logger.info(f"[REQUIREMENTS] Installed '{pkg}'") + except Exception as e: + logger.warning(f"[REQUIREMENTS] Failed to install '{pkg}': {e}") - # Refresh import caches so in-process exec() can find new packages. - if installed_any: - importlib.invalidate_caches() + # Refresh import caches so in-process exec() can find new packages. + if installed_any: + importlib.invalidate_caches() def _suppress_worker_stdio(): @@ -558,7 +575,7 @@ def _atomic_action_internal( ) -> dict: """ Executes an internal action in-process (sync version). - Requirements are pre-installed at startup via install_all_action_requirements(). + Requirements are ensured before the call (ActionExecutor.execute_atomic_action). """ try: import inspect @@ -730,10 +747,11 @@ async def execute_atomic_action( ) logger.debug(f"[EXECUTION CODE] {action.code}") - # Pre-install declared pip requirements + # Pre-install declared pip requirements, off the event loop: a first + # check runs pip (seconds; an install, up to minutes). requirements = getattr(action, "requirements", []) if requirements and execution_mode == "internal": - _ensure_requirements(requirements) + await asyncio.to_thread(_ensure_requirements, requirements) if execution_mode == "internal": # Use async executor which handles both sync and async action functions diff --git a/app/subagent/definitions/research_agent.py b/app/subagent/definitions/research_agent.py index bd7bebbb..cb16e81b 100644 --- a/app/subagent/definitions/research_agent.py +++ b/app/subagent/definitions/research_agent.py @@ -109,7 +109,9 @@ ], # Externalized outputs turn "read whole page inline" into # "pointer → grep → (maybe) read_file", costing 1-2 extra turns per - # large source — budgets sized accordingly. + # large source — budgets sized accordingly. The time cap cancels a call + # in flight, and writing the final brief alone took ~150 s (2026-11-16), + # so it leaves room for that last turn. max_iterations=30, - max_wall_seconds=450, + max_wall_seconds=900, ) diff --git a/tests/test_action_requirements.py b/tests/test_action_requirements.py new file mode 100644 index 00000000..8d5883f5 --- /dev/null +++ b/tests/test_action_requirements.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +"""An action's pip requirements are settled once per process, off the loop. + +Every web_fetch / web_search call used to run ``pip show`` on the event loop +for a package whose import name differs from its pip name (beautifulsoup4, +google-api-python-client): ~1.5 s per call with the UI frozen, and a batch of +ten parallel calls started 1.5 s apart (observed 2026-11-16). +""" + +from __future__ import annotations + +import asyncio +import threading +from types import SimpleNamespace + +from agent_core.core.impl.action import executor + + +def test_a_requirement_is_checked_once_per_process(monkeypatch): + monkeypatch.setattr(executor, "_SETTLED_REQUIREMENTS", set()) + calls = [] + monkeypatch.setattr( + executor.subprocess, "check_call", lambda cmd, **kw: calls.append(cmd) + ) + + for _ in range(3): + executor._ensure_requirements(["not-importable-pkg", "DDGS"]) + + # One pip show for the package; the class-like name is never a pip call. + assert [cmd[3:5] for cmd in calls] == [["show", "--quiet"]] + + +def test_a_failed_install_is_tried_again(monkeypatch): + monkeypatch.setattr(executor, "_SETTLED_REQUIREMENTS", set()) + calls = [] + + def fail(cmd, **kw): + calls.append(cmd[3]) + raise OSError("offline") + + monkeypatch.setattr(executor.subprocess, "check_call", fail) + executor._ensure_requirements(["not-importable-pkg"]) + executor._ensure_requirements(["not-importable-pkg"]) + assert calls == ["show", "install", "show", "install"] + + +def test_requirements_are_checked_off_the_event_loop(monkeypatch): + threads = [] + monkeypatch.setattr( + executor, + "_ensure_requirements", + lambda requirements: threads.append(threading.current_thread()), + ) + + async def run_action(*args): + return {"status": "success"} + + monkeypatch.setattr(executor, "_atomic_action_internal_async", run_action) + action = SimpleNamespace( + name="web_fetch", + code="", + execution_mode="internal", + mode="CLI", + requirements=["beautifulsoup4"], + timeout=None, + ) + + result = asyncio.run(executor.ActionExecutor().execute_atomic_action(action, {})) + assert result == {"status": "success"} + assert threads and threads[0] is not threading.main_thread()