From 7bf5e61ae5964b5808777084e0cde7f5755015ba Mon Sep 17 00:00:00 2001 From: Stull Caposole <1409908573@qq.com> Date: Mon, 23 Nov 2026 14:16:56 +0000 Subject: [PATCH 1/4] Port native search capabilities to the Hub Co-authored-by: klarkxy <278370456@qq.com> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- HUB.zh-CN.md | 15 ++ src/agent_bridge/adapters/acp.py | 53 ++++++- src/agent_bridge/adapters/codex.py | 30 +++- src/agent_bridge/api.py | 52 +++++++ src/agent_bridge/hub.py | 15 +- src/agent_bridge/hub_client.py | 3 + src/agent_bridge/models.py | 14 ++ src/agent_bridge/native_search.py | 237 +++++++++++++++++++++++++++++ src/agent_bridge/registry.py | 171 +++++++++++++++++++-- src/agent_bridge/server.py | 29 ++++ tests/test_hub.py | 51 +++++++ tests/test_native_search.py | 233 ++++++++++++++++++++++++++++ tests/test_server_tools.py | 19 +++ 13 files changed, 897 insertions(+), 25 deletions(-) create mode 100644 src/agent_bridge/native_search.py create mode 100644 tests/test_native_search.py diff --git a/HUB.zh-CN.md b/HUB.zh-CN.md index ac935b5..f2347ce 100644 --- a/HUB.zh-CN.md +++ b/HUB.zh-CN.md @@ -41,6 +41,21 @@ Hub 启动的 worker 仍通过环境获得凭证。重启后找不到签名密 远程监听必须显式使用 `--allow-remote`。这是可信本机用户的接口,不是沙箱; 持有 token 即可操作所有 session、启动 CLI。不要暴露到公网,远程使用需 TLS 隧道与防火墙。 +## 原生网页搜索 + +通过 MCP `call_capability` 或 Hub `POST /v1/capabilities` 启动搜索。传入 +`capability: "search"`、`agent`(Codex、Grok 或 MiniMax 对应的本地 CLI)、 +`prompt`、绝对 `cwd` 和 UUID `request_id`;手动模式下只有用户明确要求调用 +worker 时才传 `user_requested: true`。此接口不支持多媒体或云 worker。 + +查询用 `get_capability_result` / `GET /v1/capabilities/{call_id}/result`,可传 +`wait_sec`(0–60)和分页参数。结果必须有原生搜索证据和可归因来源; +`pending` 为真时继续查询同一个调用。请求失败或不确定时,用同一个 UUID +和相同参数查询或重放,不会重新执行保留的调用。使用新 UUID 和 `previous_call_id` +可续接同 agent、同工作区的最新成功搜索,但须等 worker 清理完成。 +`cancel_capability` / `POST /v1/capabilities/{call_id}/cancel` 只取消本地执行。 +这些路由只在需要 bearer token 的 Hub 上开放,不属于公网网关。 + ## 阻塞调用与异步回推 `invoke` / `ask` 默认等到终态,不再有 180 秒上限;显式 `timeout_sec` / diff --git a/src/agent_bridge/adapters/acp.py b/src/agent_bridge/adapters/acp.py index 362342a..a456434 100644 --- a/src/agent_bridge/adapters/acp.py +++ b/src/agent_bridge/adapters/acp.py @@ -41,6 +41,7 @@ resolve_minimax_model, ) from agent_bridge.models import Session, Task, TaskFailure, TurnResult, dsh_effort, grok_effort +from agent_bridge.native_search import HUB_PEER_ENV_KEYS, AcpNativeSearch from agent_bridge.opencode_meta import resolve_opencode_effort from agent_bridge.processes import ( drop_pid, @@ -521,6 +522,7 @@ def __init__(self, session_id: str, home: Path, permission_policy: str = "allow_ self.files: set[str] = set() self.usage: dict[str, Any] = {} self.tool_kinds: dict[str, str] = {} + self.native_search: AcpNativeSearch | None = None def reset_turn(self) -> None: self.text_parts = [] @@ -528,6 +530,19 @@ def reset_turn(self) -> None: self.usage = {} self.tool_kinds = {} + def observe_native_message(self, event: Any) -> None: + search = self.native_search + if search is None or str(getattr(event.direction, "value", event.direction)) != "incoming": + return + message = event.message + if not isinstance(message, dict) or message.get("method") != "session/update": + return + params = message.get("params") + if isinstance(params, dict) and params.get("sessionId") == search.native_id: + update = params.get("update") + if isinstance(update, dict) and update.get("sessionUpdate") in {"tool_call", "tool_call_update"}: + search.tool_name(update) + async def request_permission( self, session_id: str, @@ -558,6 +573,13 @@ async def request_permission( async def session_update(self, session_id: str, update: Any, **kwargs: Any) -> None: dumped = _dump(update) type_name = type(update).__name__ + search = self.native_search + if search and session_id == search.native_id and isinstance(dumped, dict) and (name := search.consume(dumped)): + append_event(self.session_id, dumped.get("sessionUpdate", "tool_call"), { + "tool_name": name, "status": dumped.get("status"), + "source_count": len(search.task.sources), + }, self.home) + return text = "" event_type = "raw" if type_name == "AgentMessageChunk": @@ -874,6 +896,9 @@ async def _spawn(self, session: Session) -> _Live: ) cmd = with_cursor_cli_model(cmd, session.model) env = self._enforce_spawn_env(env) + if session.native_search: + for key in HUB_PEER_ENV_KEYS: + env.pop(key, None) kwargs: dict[str, Any] = {} if sys.platform == "win32": kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP @@ -894,7 +919,7 @@ async def _spawn(self, session: Session) -> _Live: live.client = _BridgeClient( session.session_id, self.home, self.agent.permission_policy ) - live.conn = connect_to_agent(live.client, proc.stdin, proc.stdout) + live.conn = connect_to_agent(live.client, proc.stdin, proc.stdout, observers=[live.client.observe_native_message]) live.stderr_task = asyncio.create_task( self._drain_stderr(proc, session.session_id, live) ) @@ -1621,7 +1646,9 @@ async def _sync_dsh_selection(self, live: _Live, session: Session) -> None: current_effort, _offered = config_option_values(live.config_options, "reasoning_effort") live.applied_effort = current_effort or None - async def ensure_session(self, session: Session) -> None: + async def ensure_session(self, session: Session, *, strict_resume: bool = False) -> None: + if strict_resume and not session.native_session_id: + raise RuntimeError("native session is missing and cannot be resumed") live = self._live.get(session.session_id) if ( live @@ -1668,12 +1695,18 @@ async def ensure_session(self, session: Session) -> None: except AcpUnavailableError: raise except Exception as exc: + if strict_resume: + if isinstance(exc, AcpError): + raise + raise RuntimeError("native session could not be resumed") from None log.warning("session/load failed for %s; creating a new session: %s", session.session_id, _redact_diagnostic(str(exc))) load_failure = exc else: self._remember_config_options(live, revived) await self._sync_selection(live, session) return + if strict_resume: + raise RuntimeError("native session could not be resumed") created = await self._rpc( self._call_new_session(live.conn, session.cwd, self._new_session_meta(session)), "session/new", @@ -1715,12 +1748,17 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: if live is not None: live.stderr_tail = "" try: - await self.ensure_session(session) + if task.previous_call_id: + await self.ensure_session(session, strict_resume=True) + else: + await self.ensure_session(session) except Exception as exc: raise self._failure(exc, "process_start", session) from None live = self._live[session.session_id] assert live.conn is not None and live.client is not None live.client.reset_turn() + if task.native_search: + live.client.native_search = AcpNativeSearch(task, session.native_session_id) warnings: list[str] = live.pending_warnings live.pending_warnings = [] if self.agent.name not in _MODEL_EFFORT_AGENTS and (task.model or task.effort): @@ -1754,6 +1792,7 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: ) from None finally: live.prompt_task = None + live.client.native_search = None stop = getattr(response, "stop_reason", None) or "end_turn" if hasattr(stop, "value"): stop = stop.value @@ -1797,7 +1836,10 @@ async def cancel(self, session: Session) -> None: await self.shutdown(session) async def shutdown(self, session: Session) -> None: - live = self._live.pop(session.session_id, None) + live = ( + self._live.get(session.session_id) if session.native_search + else self._live.pop(session.session_id, None) + ) if live is None: drop_pid(self.home, session.session_id) session.pid = None @@ -1807,10 +1849,13 @@ async def shutdown(self, session: Session) -> None: await asyncio.wait_for(live.conn.close(), timeout=2) if live.proc is not None: await reap_subprocess(live.proc) + if session.native_search and live.proc.returncode is None: + raise RuntimeError("native search worker is still running") if live.stderr_task is not None: if not live.stderr_task.done(): live.stderr_task.cancel() with contextlib.suppress(asyncio.CancelledError): await live.stderr_task + self._live.pop(session.session_id, None) drop_pid(self.home, session.session_id) session.pid = None diff --git a/src/agent_bridge/adapters/codex.py b/src/agent_bridge/adapters/codex.py index bca1947..c502e4d 100644 --- a/src/agent_bridge/adapters/codex.py +++ b/src/agent_bridge/adapters/codex.py @@ -21,6 +21,7 @@ ) from agent_bridge.diagnostics import redact_diagnostic from agent_bridge.models import Session, Task, TurnResult +from agent_bridge.native_search import HUB_PEER_ENV_KEYS, observe_codex_search from agent_bridge.processes import ( drop_pid, interrupt_then_reap, @@ -62,7 +63,10 @@ def _build_cmd(self, session: Session, task: Task, env: dict[str, str] | None = effort=task.effort or session.effort, resume_id=session.native_session_id, yolo=yolo_requested(self.agent.session_meta), - config_overrides=self.agent.config_overrides, + config_overrides=[ + *self.agent.config_overrides, + *(['web_search="live"'] if task.native_search else []), + ], ) async def _drain_stderr(self, proc: asyncio.subprocess.Process, session_id: str) -> str: @@ -104,9 +108,14 @@ async def _write_prompt(self, proc: asyncio.subprocess.Process, message: str) -> proc.stdin.close() async def run_turn(self, session: Session, task: Task) -> TurnResult: + if task.previous_call_id and not session.native_session_id: + raise RuntimeError("native session is missing and cannot be resumed") env = self._worker_env() cmd = self._build_cmd(session, task, env) env = self._enforce_spawn_env(env) + if task.native_search: + for key in HUB_PEER_ENV_KEYS: + env.pop(key, None) kwargs: dict[str, Any] = {} if sys.platform == "win32": kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP @@ -170,6 +179,15 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: apply_codex_event(state, obj) event = str(obj.get("type") or "") event_type = "raw" + search_item = obj.get("item") + if (task.native_search and event in {"item.started", "item.updated", "item.completed"} + and isinstance(search_item, dict) and search_item.get("type") == "web_search"): + if event == "item.completed": + observe_codex_search(task, search_item) + append_event(session.session_id, "tool_call", { + "native_search": True, "source_count": len(task.sources), + }, self.home) + continue if event == "item.completed": raw_item = obj.get("item") item: dict[str, Any] = raw_item if isinstance(raw_item, dict) else {} @@ -256,9 +274,10 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: stderr_task.cancel() with contextlib.suppress(asyncio.CancelledError): await stderr_task - self._procs.pop(session.session_id, None) + if not task.native_search or proc.returncode is not None: + self._procs.pop(session.session_id, None) + drop_pid(self.home, session.session_id) self._cancelled.discard(session.session_id) - drop_pid(self.home, session.session_id) async def cancel(self, session: Session) -> None: self._cancelled.add(session.session_id) @@ -268,4 +287,9 @@ async def cancel(self, session: Session) -> None: async def shutdown(self, session: Session) -> None: await self.cancel(session) + proc = self._procs.get(session.session_id) + if session.native_search and proc is not None: + if proc.returncode is None: + raise RuntimeError("native search worker is still running") + drop_pid(self.home, session.session_id) self._procs.pop(session.session_id, None) diff --git a/src/agent_bridge/api.py b/src/agent_bridge/api.py index 76455b5..0256025 100644 --- a/src/agent_bridge/api.py +++ b/src/agent_bridge/api.py @@ -32,6 +32,58 @@ class BridgeService: def __init__(self, registry: Registry) -> None: self.registry = registry + async def call_capability( + self, agent: str, capability: str, prompt: str, cwd: str, request_id: str, + model: str | None = None, effort: str | None = None, user_requested: bool = False, + previous_call_id: str | None = None, + ) -> dict[str, Any]: + try: + if capability != "search": + raise ValueError("only the search capability is supported") + if not isinstance(request_id, str) or not request_id: + raise ValueError("request_id is required on the first capability call") + if not isinstance(user_requested, bool): + raise ValueError("user_requested must be a boolean") + if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 16000: + raise ValueError("prompt must contain between 1 and 16000 characters") + if previous_call_id is not None and (not isinstance(previous_call_id, str) or not previous_call_id.strip()): + raise ValueError("previous_call_id must be a capability call id") + message = ( + "Perform a native web search and use native page retrieval when needed to verify the findings. " + "Return findings and native sources. Do not generate media, delegate, edit project source, " + "or use shell/network scripts as a substitute. If native search is unavailable or uncertain, " + "report the condition and stop.\nRequest:\n" + prompt + ) + result = await self.registry.dispatch_task( + agent=agent, message=message, cwd=cwd, request_id=request_id, model=model, effort=effort, + user_requested=user_requested, caller_session_id=caller_session_context.get(), + _native_search=True, _previous_call_id=previous_call_id, + ) + task = self.registry.require_search(result["task_id"]) + return { + "ok": True, "call_id": task.task_id, "agent": task.agent, "capability": capability, + "status": task.status.value, "request_id": task.request_id, + "persisted": result["persisted"], "reused": result.get("reused", False), + } + except Exception as exc: + return _error(exc) + + async def get_capability_result( + self, call_id: str, wait_sec: float = 0, cursor: int = 0, max_chars: int = RESULT_PAGE_MAX_CHARS, + ) -> dict[str, Any]: + try: + return {"ok": True, **await self.registry.get_search_result(call_id, wait_sec, cursor, max_chars)} + except Exception as exc: + return _error(exc) + + async def cancel_capability(self, call_id: str) -> dict[str, Any]: + try: + task = self.registry.require_search(call_id) + await self.registry.cancel_task(task.task_id) + return await self.get_capability_result(task.task_id) | {"remote_cancellation_supported": False} + except Exception as exc: + return _error(exc) + async def invoke(self, agent: str, message: str, cwd: str | None = None, timeout_sec: float | None = None, **kwargs: Any) -> dict[str, Any]: if timeout_sec is not None and timeout_sec < 0: return _error(ValueError('timeout_sec must be non-negative')) diff --git a/src/agent_bridge/hub.py b/src/agent_bridge/hub.py index 7d5147a..64d3cbe 100644 --- a/src/agent_bridge/hub.py +++ b/src/agent_bridge/hub.py @@ -98,21 +98,24 @@ async def handle(request: Request): for key in ('cursor', 'max_chars', 'offset', 'limit'): if key in args: args[key] = int(args[key]) - if 'timeout_sec' in args: - args['timeout_sec'] = float(args['timeout_sec']) + for key in ('timeout_sec', 'wait_sec'): + if key in args: + args[key] = float(args[key]) if 'active_only' in args: if args['active_only'] not in ('true', 'false'): raise ValueError('active_only must be true or false') args['active_only'] = args['active_only'] == 'true' caller = request.headers.get('x-agent-bridge-caller') depth = 0 - if caller and tool in ('dispatch_task', 'invoke'): - if caller not in registry.sessions: - raise ValueError('unknown caller session') + if caller and caller not in registry.sessions and tool in ( + 'dispatch_task', 'invoke', 'call_capability', 'get_capability_result', 'cancel_capability', + ): + raise ValueError('unknown caller session') + if caller and tool in ('dispatch_task', 'invoke', 'call_capability'): if args.get('session_id') == caller: raise ValueError('cannot dispatch into caller session') caller_task = registry._busy_task(caller) - if caller_task and caller_task.notification_source_task_id: + if tool != 'call_capability' and caller_task and caller_task.notification_source_task_id: args['notify_caller'] = False args.pop('callback_url', None) args.pop('callback_secret', None) diff --git a/src/agent_bridge/hub_client.py b/src/agent_bridge/hub_client.py index 37521de..95aa58d 100644 --- a/src/agent_bridge/hub_client.py +++ b/src/agent_bridge/hub_client.py @@ -26,6 +26,9 @@ 'wait_task': ('GET', '/v1/tasks/{task_id}/wait', 'task_id'), 'get_result': ('GET', '/v1/tasks/{task_id}/result', 'task_id'), 'cancel_task': ('POST', '/v1/tasks/{task_id}/cancel', 'task_id'), + 'call_capability': ('POST', '/v1/capabilities', None), + 'get_capability_result': ('GET', '/v1/capabilities/{call_id}/result', 'call_id'), + 'cancel_capability': ('POST', '/v1/capabilities/{call_id}/cancel', 'call_id'), 'list_sessions': ('GET', '/v1/sessions', None), 'get_transcript': ('GET', '/v1/sessions/{session_id}/transcript', 'session_id'), 'end_session': ('DELETE', '/v1/sessions/{session_id}', 'session_id'), diff --git a/src/agent_bridge/models.py b/src/agent_bridge/models.py index 93bc06c..bf33698 100644 --- a/src/agent_bridge/models.py +++ b/src/agent_bridge/models.py @@ -90,6 +90,7 @@ def grok_effort(effort: str | None) -> str | None: class Session(BaseModel): + native_search: bool = False call_depth: int = 0 notification_receipts: dict[str, str] = Field(default_factory=dict) session_id: str @@ -121,7 +122,20 @@ class TaskFailure(BaseModel): stderr_summary: str | None = None +class SourceReference(BaseModel): + title: str + url: str + snippet: str | None = None + tool_call_id: str + + class Task(BaseModel): + native_search: bool = False + request_id: str | None = None + previous_call_id: str | None = None + search_finalized: bool = False + sources: list[SourceReference] = Field(default_factory=list) + native_calls: dict[str, str] = Field(default_factory=dict) call_depth: int = 0 caller_session_id: str | None = None notify_caller: bool = False diff --git a/src/agent_bridge/native_search.py b/src/agent_bridge/native_search.py new file mode 100644 index 0000000..717576e --- /dev/null +++ b/src/agent_bridge/native_search.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +import ipaddress +import json +from typing import Any +from urllib.parse import parse_qsl, urlsplit + +from agent_bridge.diagnostics import redact_diagnostic +from agent_bridge.models import SourceReference, Task +from agent_bridge.secrets import redact + +MAX_SOURCES = 32 +MAX_RAW_CHARS = 64 * 1024 +SEARCH_TOOLS = {"web_search", "web_fetch"} +SEARCH_PROTOCOLS = {"codex": "codex", "grok": "acp", "minimax": "acp"} +FORBIDDEN_TOOLS = {"image_gen", "image_edit", "image_to_video", "reference_to_video"} +HUB_PEER_ENV_KEYS = ("AGENT_BRIDGE_HUB_URL", "AGENT_BRIDGE_HUB_TOKEN", "AGENT_BRIDGE_CALLER_SESSION") + + +def observe_call(task: Task, call_id: Any, name: str) -> bool: + if not isinstance(call_id, str) or not call_id or len(call_id) > 128: + return False + prior = task.native_calls.get(call_id) + if prior is not None: + return prior == name + if len(task.native_calls) >= 64: + raise ValueError("native capability call evidence limit exceeded") + task.native_calls[call_id] = name + return True + + +def safe_url(value: Any) -> str | None: + if not isinstance(value, str) or not value or len(value) > 2048 or any(ord(c) < 32 for c in value): + return None + if redact(value) != value: + return None + try: + parsed = urlsplit(value) + if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password: + return None + if parsed.hostname.lower().rstrip(".") == "localhost": + return None + try: + if not ipaddress.ip_address(parsed.hostname).is_global: + return None + except ValueError: + pass + if any( + any(mark in key.lower() for mark in ("token", "signature", "credential", "password", "authorization")) + or key.lower() in {"sig", "key", "api_key", "expires"} + or key.lower().startswith("x-amz-") + for key, _ in parse_qsl(parsed.query) + ): + return None + except ValueError: + return None + return value + + +def add_source(into: list[SourceReference], value: Any, call_id: str) -> None: + if not isinstance(value, dict) or not call_id or len(call_id) > 128 or len(into) >= MAX_SOURCES: + return + url = safe_url(value.get("url")) + if url is None or any(s.url == url and s.tool_call_id == call_id for s in into): + return + title = value.get("title") + snippet = value.get("snippet") + into.append(SourceReference( + title=redact_diagnostic(title[:500]) if isinstance(title, str) and title else url, + url=url, snippet=redact_diagnostic(snippet[:2000]) if isinstance(snippet, str) else None, + tool_call_id=call_id, + )) + + +def extract_codex_sources(item: dict[str, Any], into: list[SourceReference]) -> None: + call_id = item.get("id") + action = item.get("action") + if not isinstance(call_id, str): + return + results = item.get("results") + if isinstance(results, list): + for result in results[:MAX_SOURCES]: + if isinstance(result, dict) and result.get("type") == "text_result": + add_source(into, result, call_id) + if isinstance(action, dict) and action.get("type") in {"open_page", "find_in_page", "openPage", "findInPage"}: + add_source(into, {"url": action.get("url")}, call_id) + + +def bounded_output(value: Any) -> dict[str, Any] | None: + if isinstance(value, str): + if len(value) > MAX_RAW_CHARS: + return None + try: + value = json.loads(value) + except json.JSONDecodeError: + return None + if not isinstance(value, dict): + return None + pending: list[tuple[Any, int]] = [(value, 0)] + budget = MAX_RAW_CHARS + nodes = 0 + while pending: + current, depth = pending.pop() + nodes += 1 + if nodes > 4096 or depth > 12: + return None + if isinstance(current, str): + budget -= len(current) * 6 + 2 + elif isinstance(current, dict): + if len(current) > 4096: + return None + budget -= 2 + len(current) + for key, nested in current.items(): + if not isinstance(key, str): + return None + pending.extend(((key, depth + 1), (nested, depth + 1))) + elif isinstance(current, list): + if len(current) > 4096: + return None + budget -= 2 + len(current) + pending.extend((nested, depth + 1) for nested in current) + elif current is None or isinstance(current, (int, float, bool)): + budget -= 32 + else: + return None + if budget < 0: + return None + return value + + +def observe_codex_search(task: Task, item: dict[str, Any]) -> None: + action = item.get("action") + if not isinstance(action, dict): + return + kind = action.get("type") + call_id = item.get("id") + if kind == "search": + name = "web_search" + elif kind in ("open_page", "find_in_page", "openPage", "findInPage"): + name = "web_fetch" + else: + return + if observe_call(task, call_id, name): + extract_codex_sources(item, task.sources) + + +class AcpNativeSearch: + def __init__(self, task: Task, native_id: str | None) -> None: + self.task = task + self.native_id = native_id + self.names: dict[str, str] = {} + self.urls: dict[str, str] = {} + self.completed: set[str] = set() + + def tool_name(self, update: dict[str, Any]) -> str | None: + call_id = update.get("toolCallId") + if not isinstance(call_id, str) or not call_id or len(call_id) > 128: + return None + field = "toolName" if self.task.agent == "grok" else "name" + name = update.get(field) + raw_input = update.get("rawInput") + if not isinstance(name, str) and self.task.agent == "grok" and isinstance(raw_input, dict): + variant_names = { + "WebSearch": "web_search", "WebFetch": "web_fetch", + "ImageGen": "image_gen", "ImageEdit": "image_edit", + "ImageToVideo": "image_to_video", "ReferenceToVideo": "reference_to_video", + } + variant = raw_input.get("variant") + name = variant_names.get(variant) if isinstance(variant, str) else None + if not isinstance(name, str) and self.task.agent == "grok": + vendor_meta = update.get("_meta") + if isinstance(vendor_meta, dict): + xai_tool = vendor_meta.get("x.ai/tool") + if isinstance(xai_tool, dict): + name = xai_tool.get("name") + if not isinstance(name, str): + return self.names.get(call_id) + if name not in SEARCH_TOOLS | FORBIDDEN_TOOLS: + return None + if call_id not in self.names and len(self.names) < 256: + self.names[call_id] = name + return name if self.names.get(call_id) == name else None + + def consume(self, update: dict[str, Any]) -> str | None: + name = self.tool_name(update) + if name is None: + return None + call_id = update["toolCallId"] + if name in FORBIDDEN_TOOLS: + observe_call(self.task, call_id, name) + return name + raw_input = update.get("rawInput") + if isinstance(raw_input, dict) and name == "web_fetch" and (url := safe_url(raw_input.get("url"))): + self.urls[call_id] = url + if update.get("status") == "completed" and call_id not in self.completed: + output = bounded_output(update.get("rawOutput")) + if output is not None and observe_call(self.task, call_id, name): + self._search(name, call_id, output) + self.completed.add(call_id) + return name + + def _search(self, name: str, call_id: str, output: dict[str, Any]) -> None: + if self.task.agent == "grok": + variant = output.get("type") + if name == "web_search" and variant == "WebSearch": + citations = output.get("citations") + if isinstance(citations, list): + for citation in citations[:MAX_SOURCES]: + add_source(self.task.sources, {"url": citation} if isinstance(citation, str) else citation, call_id) + if name == "web_fetch" and variant == "WebFetch": + # Historical native fixtures use a Content variant. Unknown + # current variants do not silently become successful fetches. + content = output.get("Content") + if isinstance(content, dict) and isinstance(content.get("status_code"), int) and 200 <= content["status_code"] < 400: + url = content.get("url") or self.urls.get(call_id) + text = content.get("content") + snippet = text[:2000] if isinstance(text, str) and "base64" not in text[:2000] else None + add_source(self.task.sources, {"url": url, "snippet": snippet}, call_id) + elif name == "web_search": + # Accept the official search service body only inside an identified + # successful ACP tool. Do not infer citations from arbitrary text. + body = output + content = output.get("content") + if isinstance(content, list) and content and isinstance(content[0], dict): + decoded = bounded_output(content[0].get("text")) + if decoded is not None: + body = decoded + if "code" in body and body["code"] != 0: + return + results = body.get("results") + if isinstance(results, list): + for result in results[:MAX_SOURCES]: + if isinstance(result, dict): + add_source(self.task.sources, { + "url": result.get("url") or result.get("href") or result.get("link"), + "title": result.get("title"), "snippet": result.get("snippet"), + }, call_id) diff --git a/src/agent_bridge/registry.py b/src/agent_bridge/registry.py index 0a4660a..707a95c 100644 --- a/src/agent_bridge/registry.py +++ b/src/agent_bridge/registry.py @@ -5,6 +5,7 @@ import hashlib import json import logging +import math import os import time import uuid @@ -41,6 +42,7 @@ iso, normalize_effort, ) +from agent_bridge.native_search import SEARCH_PROTOCOLS, SEARCH_TOOLS from agent_bridge.paths import ensure_home, result_path, state_path, transcript_path from agent_bridge.persist import ( atomic_write_json, @@ -506,6 +508,10 @@ async def start(self) -> None: task.status = TaskStatus.failed task.error = "bridge_restarted" task.finished_at = iso() + if task.native_search and not task.search_finalized and task.status == TaskStatus.completed: + task.status = TaskStatus.failed + task.stop_reason = "error" + task.error = "Bridge restarted before search worker cleanup was confirmed." if task.files_changed_state == FilesChangedState.pending and task.status in TERMINAL_STATUSES: task.files_changed_state = ( FilesChangedState.collected @@ -727,12 +733,16 @@ async def dispatch_task( callback_url: str | None = None, callback_secret: str | None = None, notification_source_task_id: str | None = None, + _native_search: bool = False, + _previous_call_id: str | None = None, ) -> dict: if not self.dispatch_enabled: raise RuntimeError(NESTED_DISPATCH_ERROR) caller_task = self._busy_task(caller_session_id) if caller_session_id else None if caller_session_id and caller_session_id not in self.sessions: raise ValueError('unknown caller session') + if caller_session_id and self.sessions[caller_session_id].native_search: + raise ValueError("native search workers cannot dispatch to other workers") if caller_session_id and session_id == caller_session_id: raise ValueError('cannot dispatch into caller session') depth = self.sessions[caller_session_id].call_depth + 1 if caller_session_id else 0 @@ -757,6 +767,8 @@ async def dispatch_task( except ValueError: raise ValueError("request_id must be a UUID") from None agent_cfg = self.config.get(agent) + if _native_search and SEARCH_PROTOCOLS.get(agent) != agent_cfg.protocol: + raise ValueError(f"{agent} does not have a supported native search integration for {agent_cfg.protocol}") cloud = agent_cfg.protocol == 'cloud' if not cloud and not cwd: raise ValueError('cwd is required for local agents') @@ -776,6 +788,8 @@ async def dispatch_task( if cloud: request += (repo, ref) request += (notify_caller, caller_session_id, callback_url, callback_secret) + if _native_search: + request += ("native_search", _previous_call_id) async with self._lock: if request_id is not None and request_id in self._requests: previous_fp, task_id = self._requests[request_id] @@ -792,10 +806,26 @@ async def dispatch_task( "reused": True, "persisted": await self.flush_state(), } + if _previous_call_id is not None: + previous = self.tasks.get(_previous_call_id) + if ( + previous is None or not previous.native_search or previous.status != TaskStatus.completed + or not previous.search_finalized or previous.agent != agent or previous.cwd != resolved_cwd + ): + raise ValueError("previous_call_id must identify a finalized successful search for the same agent and cwd") + session_id = previous.session_id + prior_session = self.sessions.get(session_id) + if prior_session is None or not prior_session.native_session_id: + raise ValueError("previous search has no resumable native session") + latest = next(t for t in reversed(self.tasks.values()) if t.session_id == session_id) + if latest is not previous: + raise ValueError("previous_call_id must identify the latest search in its session") if session_id: session = self.sessions.get(session_id) if session is None: raise KeyError(f"unknown session {session_id}") + if session.native_search != _native_search: + raise ValueError("native search sessions are not available to ordinary dispatch") if session.agent != agent: raise ValueError(f"session {session_id} belongs to agent {session.agent}, not {agent}") if cloud and repo is not None and repo != session.repo: @@ -816,6 +846,7 @@ async def dispatch_task( ) else: session = Session( + native_search=_native_search, call_depth=depth, session_id=_new_id("sess"), agent=agent, @@ -841,6 +872,9 @@ async def dispatch_task( if caller_session_id: session.call_depth = depth task = Task( + native_search=_native_search, + request_id=request_id if _native_search else None, + previous_call_id=_previous_call_id, call_depth=session.call_depth, task_id=_new_id("task"), session_id=session.session_id, @@ -884,13 +918,22 @@ async def dispatch_task( session.session_id, agent, ) - try: - persisted = await self.flush_state() - finally: - # Even when the caller cancels mid-flush, the registered task - # must still start — a request_id retry would otherwise reuse - # a row that never runs. - self._bg[task.task_id] = asyncio.create_task(self._run_task(task.task_id), name=f"task-{task.task_id}") + if _native_search: + initial_flush = asyncio.create_task(self.flush_state()) + try: + persisted = await asyncio.shield(initial_flush) + finally: + self._bg[task.task_id] = asyncio.create_task( + self._run_persisted_search(task, initial_flush), name=f"task-{task.task_id}", + ) + else: + try: + persisted = await self.flush_state() + finally: + # Even when the caller cancels mid-flush, the registered task + # must still start — a request_id retry would otherwise reuse + # a row that never runs. + self._bg[task.task_id] = asyncio.create_task(self._run_task(task.task_id), name=f"task-{task.task_id}") return { "task_id": task.task_id, "session_id": session.session_id, @@ -901,6 +944,54 @@ async def dispatch_task( **({"request_id": request_id, "reused": False} if request_id is not None else {}), } + async def _run_persisted_search(self, task: Task, initial_flush: asyncio.Task[bool]) -> None: + try: + persisted = await asyncio.shield(initial_flush) + except asyncio.CancelledError: + self._finish_unstarted_search(task, TaskStatus.cancelled) + return + if not persisted: + task.error = "Native search was not submitted: could not persist the request." + self._finish_unstarted_search(task, TaskStatus.failed) + return + await self._run_task(task.task_id) + + def _finish_unstarted_search(self, task: Task, status: TaskStatus) -> None: + task.status = status + task.stop_reason = "cancelled" if status == TaskStatus.cancelled else "error" + task.finished_at = iso() + task.files_changed_state = FilesChangedState.unavailable + task.search_finalized = True + self.sessions[task.session_id].proc_state = ProcState.idle_unloaded + self._cancel_requested.discard(task.task_id) + self._bg.pop(task.task_id, None) + self._done[task.task_id].set() + self.save() + + async def _finalize_search(self, task: Task, session: Session, adapter: Adapter) -> None: + if task.status == TaskStatus.completed and ( + "web_search" not in task.native_calls.values() or not set(task.native_calls.values()) <= SEARCH_TOOLS + or not task.sources or any(s.tool_call_id not in task.native_calls for s in task.sources) + ): + task.status = TaskStatus.failed + task.stop_reason = "error" + task.error = "Search requires completed native web_search evidence and attributable sources." + try: + await adapter.shutdown(session) + except Exception: + log.exception("native search worker shutdown failed for %s", task.task_id) + task.warnings.append("Native search worker shutdown could not be confirmed; continuation is blocked.") + if task.status == TaskStatus.completed: + task.status = TaskStatus.failed + task.stop_reason = "error" + task.error = task.warnings[-1] + return + self._adapters.pop(session.session_id, None) + forget_worker_activity(session.session_id, self.home) + session.proc_state = ProcState.idle_unloaded + session.pid = None + task.search_finalized = True + async def _run_task(self, task_id: str) -> None: started_monotonic = time.monotonic() task = self.tasks[task_id] @@ -935,6 +1026,8 @@ async def _run_task(self, task_id: str) -> None: _, instructions = self.remote.issue(task) turn_task = task.model_copy(update={'message': task.message + instructions}) result = await adapter.run_turn(session, turn_task) + if task.native_search: + result.text = redact(result.text) task.remote.update(result.remote) if result.native_session_id: session.native_session_id = result.native_session_id @@ -1053,7 +1146,14 @@ async def _run_task(self, task_id: str) -> None: flush_session(session.session_id, self.home) except OSError: log.exception("could not flush transcript for task %s", task.task_id) - self._done[task_id].set() + if task.native_search: + cleanup = asyncio.create_task(self._finalize_search(task, session, adapter)) + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError: + await cleanup + if not task.native_search or task.search_finalized: + self._done[task_id].set() self._bg.pop(task_id, None) self.save() duration_ms = int((time.monotonic() - started_monotonic) * 1000) @@ -1069,7 +1169,8 @@ async def _run_task(self, task_id: str) -> None: task.stop_reason, (task.error or "")[:500], ) - self._schedule_idle(session.session_id) + if not task.native_search: + self._schedule_idle(session.session_id) @staticmethod def _set_files_changed(task: Task, paths: list[str], outside: list[str] | None = None) -> None: @@ -1203,7 +1304,10 @@ def _sweep_orphan_results(self, foreign_task_ids: set[str]) -> None: log.info("removed orphan result %s (no task row)", orphan.name) def _drop_task(self, task_id: str) -> None: - if task_id in self.tasks and pending(self.tasks[task_id]): + if task_id in self.tasks and ( + pending(self.tasks[task_id]) + or (self.tasks[task_id].native_search and not self._done[task_id].is_set()) + ): return self.tasks.pop(task_id, None) self.deliveries.delete_secret(task_id) @@ -1516,6 +1620,35 @@ async def check_task(self, task_id: str) -> dict: task = self._require_task(task_id, allow_disk=True) return await self._with_persisted(task, self._task_snapshot(task)) + def require_search(self, call_id: str, *, allow_disk: bool = False) -> Task: + task = self._require_task(call_id, allow_disk=allow_disk) + if not task.native_search: + raise KeyError(f"unknown capability call {call_id}") + return task + + async def get_search_result(self, call_id: str, wait_sec: float, cursor: int, max_chars: int) -> dict: + if not math.isfinite(wait_sec) or not 0 <= wait_sec <= 60: + raise ValueError("wait_sec must be between 0 and 60") + task = self.require_search(call_id, allow_disk=True) + done = self._done.get(call_id) + if done is not None and not done.is_set() and wait_sec: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(done.wait(), timeout=wait_sec) + result = await self.get_result(call_id, cursor=cursor, max_chars=max_chars) + fields = ( + "status", "stop_reason", "error", "failure", "persisted", "warnings", + "model", "effort", "observed_model", "observed_effort", "created_at", + "started_at", "finished_at", "elapsed_sec", "usage", "result_text", + "result_offset", "result_total_chars", "next_cursor", "has_more", "result_complete", + ) + return redact({ + **{key: result[key] for key in fields if key in result}, + "call_id": call_id, "agent": task.agent, "capability": "search", "request_id": task.request_id, + "cwd": task.cwd, "sources": [source.model_dump(exclude_none=True) for source in task.sources], + "native_calls": task.native_calls, + "pending": (not done.is_set() if done is not None else not task.search_finalized), + }) + async def get_result( self, task_id: str, @@ -1561,6 +1694,9 @@ async def get_result( return await self._with_persisted(task, payload) def get_transcript(self, session_id: str, offset: int = 0, limit: int = 50, kinds: list[str] | None = None) -> dict: + session = self.sessions.get(session_id) + if session is not None and session.native_search: + raise KeyError(f"unknown session {session_id}") if session_id not in self.sessions and not transcript_path(session_id, self.home).is_file(): raise KeyError(f"unknown session {session_id}") events = read_events(session_id, self.home) @@ -1576,7 +1712,12 @@ async def cancel_task(self, task_id: str) -> dict: session = self.sessions[task.session_id] adapter = self._adapters.get(session.session_id) if adapter is not None: - await adapter.cancel(session) + try: + await adapter.cancel(session) + except Exception: + if not task.native_search: + raise + log.exception("cancel signal failed for native search %s", task_id) bg = self._bg.get(task_id) if bg is not None: bg.cancel() @@ -1585,6 +1726,10 @@ async def cancel_task(self, task_id: str) -> dict: with contextlib.suppress(TimeoutError): await asyncio.wait_for(self._done[task_id].wait(), timeout=15) if not self._done[task_id].is_set(): + if task.native_search: + if task.started_at is None and bg is not None and bg.cancelled(): + self._finish_unstarted_search(task, TaskStatus.cancelled) + return await self._with_persisted(task, self._task_snapshot(task)) # _run_task never ran (cancelled before its first step) or did not # finish in time; close the record here. task.status = TaskStatus.cancelled @@ -1602,6 +1747,8 @@ async def cancel_task(self, task_id: str) -> dict: def list_sessions(self, active_only: bool = False) -> list[dict]: rows = [] for session in self.sessions.values(): + if session.native_search: + continue if active_only and session.proc_state in {ProcState.dead, ProcState.idle_unloaded}: continue rows.append( @@ -1633,7 +1780,7 @@ async def end_session(self, session_id: str) -> dict: if not self.dispatch_enabled: raise RuntimeError(NESTED_END_SESSION_ERROR) session = self.sessions.get(session_id) - if session is None: + if session is None or session.native_search: raise KeyError(f"unknown session {session_id}") busy = self._busy_task(session_id) if busy is not None: diff --git a/src/agent_bridge/server.py b/src/agent_bridge/server.py index e7c2948..7155a95 100644 --- a/src/agent_bridge/server.py +++ b/src/agent_bridge/server.py @@ -199,6 +199,35 @@ async def cancel_task(ctx: Context, task_id: str) -> dict[str, Any]: return await _service(ctx).cancel_task(task_id=task_id) +@mcp.tool() +async def call_capability( + ctx: Context, agent: str, capability: str, prompt: str, cwd: str, request_id: str, + model: str | None = None, effort: str | None = None, user_requested: bool = False, + previous_call_id: str | None = None, +) -> dict[str, Any]: + """Start native search with Codex, Grok, or MiniMax. Provide an absolute cwd and a UUID; reuse that UUID with identical arguments when the outcome is uncertain. Set user_requested only if the user explicitly requested a worker. previous_call_id continues a finalized successful search.""" + return await _service(ctx).call_capability( + agent=agent, capability=capability, prompt=prompt, cwd=cwd, request_id=request_id, + model=model, effort=effort, user_requested=user_requested, previous_call_id=previous_call_id, + ) + + +@mcp.tool(annotations=READ_ONLY) +async def get_capability_result( + ctx: Context, call_id: str, wait_sec: float = 0, cursor: int = 0, max_chars: int = RESULT_PAGE_MAX_CHARS, +) -> dict[str, Any]: + """Read the search result and native sources. Poll while pending, including during worker cleanup; use next_cursor for additional text.""" + return await _service(ctx).get_capability_result( + call_id=call_id, wait_sec=wait_sec, cursor=cursor, max_chars=max_chars, + ) + + +@mcp.tool() +async def cancel_capability(ctx: Context, call_id: str) -> dict[str, Any]: + """Cancel the local native search worker. This does not confirm remote provider cancellation.""" + return await _service(ctx).cancel_capability(call_id=call_id) + + @mcp.tool(annotations=READ_ONLY) async def list_sessions(ctx: Context, active_only: bool = False) -> dict[str, Any]: """List sessions owned by this Bridge instance and report live siblings.""" diff --git a/tests/test_hub.py b/tests/test_hub.py index 00699d4..6b61be6 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -4,6 +4,7 @@ import os import sys import types +import uuid from pathlib import Path from unittest.mock import AsyncMock @@ -15,6 +16,8 @@ from agent_bridge.config import AgentConfig, EnvConfig, load_config from agent_bridge.hub import create_app, validate_host from agent_bridge.hub_client import HubClient, discover +from agent_bridge.models import Session, TurnResult +from agent_bridge.native_search import observe_codex_search from agent_bridge.registry import Registry from agent_bridge.worker_env import build_worker_env, enforce_env_deny, hub_worker_context @@ -77,6 +80,54 @@ async def test_depth_and_self_dispatch(hub, tmp_path): assert (await client.post('/v1/tasks', json=body, headers={'X-Agent-Bridge-Caller': 'unknown'})).status_code == 400 +async def test_native_search_auth_depth_and_mcp_proxy(hub, tmp_path, monkeypatch): + client, registry = hub + registry.config.agents["codex"] = AgentConfig(name="codex", protocol="codex", command=["unused"]) + + async def turn(self, session, task): + observe_codex_search(task, { + "id": "web", "action": {"type": "search"}, + "results": [{"type": "text_result", "url": "https://example.org/"}], + }) + return TurnResult(text="Native result", native_session_id="native-thread") + + monkeypatch.setattr("agent_bridge.adapters.codex.CodexAdapter.run_turn", turn) + body = dict(agent="codex", capability="search", prompt="Search", cwd=str(tmp_path), + request_id=str(uuid.uuid4()), user_requested=True) + assert (await client.post("/v1/capabilities", json=body, headers={"Authorization": ""})).status_code == 401 + assert (await client.post("/v1/capabilities", json=body, headers={ + "X-Agent-Bridge-Caller": "unknown", + })).json()["error"].endswith("unknown caller session") + assert not (await client.post("/v1/capabilities", json=body | {"user_requested": "false"})).json()["ok"] + assert not (await client.post("/v1/capabilities", json=body | {"capability": "image"})).json()["ok"] + assert not (await client.post("/v1/capabilities", json=body | {"agent": "opencode"})).json()["ok"] + root = Session(session_id="test-root", agent="fake", cwd=str(tmp_path)) + peer = Session(session_id="test-peer", agent="fake", cwd=str(tmp_path), call_depth=1) + registry.sessions.update({root.session_id: root, peer.session_id: peer}) + response = await client.post("/v1/capabilities", json=body, headers={"X-Agent-Bridge-Caller": peer.session_id}) + assert response.status_code == 400 and "max_depth" in response.json()["error"] + assert not registry.tasks + + original_client = httpx2.AsyncClient + monkeypatch.setattr(httpx2, "AsyncClient", lambda **kwargs: original_client(transport=client._transport, **kwargs)) + monkeypatch.setenv("AGENT_BRIDGE_CALLER_SESSION", root.session_id) + backend = HubClient("http://hub", "test-token") + ctx = types.SimpleNamespace(request_context=types.SimpleNamespace(lifespan_context=backend)) + call = await server.call_capability(ctx, **body) + result = await server.get_capability_result(ctx, call["call_id"], wait_sec=5, max_chars=6) + assert result["ok"] and not result["pending"] and result["status"] == "completed" + assert result["sources"][0]["url"] == "https://example.org/" + assert result["result_text"] == "Native" and result["has_more"] + task = registry.tasks[call["call_id"]] + assert task.call_depth == 1 and task.caller_session_id == root.session_id + assert "session_id" not in call and "session_id" not in result + path = f"/v1/capabilities/{task.task_id}" + assert (await client.get(path + "/result", headers={"Authorization": ""})).status_code == 401 + assert (await client.post(path + "/cancel", headers={"Authorization": ""})).status_code == 401 + assert (await server.cancel_capability(ctx, task.task_id))["remote_cancellation_supported"] is False + assert (await server.call_capability(ctx, **body))["reused"] + + async def test_lifecycle_cleanup(bridge_home): app = create_app(Registry.create(bridge_home)) async with app.router.lifespan_context(app): diff --git a/tests/test_native_search.py b/tests/test_native_search.py new file mode 100644 index 0000000..6211ac8 --- /dev/null +++ b/tests/test_native_search.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +import asyncio +import json +import sys +import uuid +from unittest.mock import AsyncMock + +import pytest + +from agent_bridge.adapters.codex import CodexAdapter +from agent_bridge.api import BridgeService +from agent_bridge.config import AgentConfig, AppConfig +from agent_bridge.models import Session, Task, TurnResult +from agent_bridge.native_search import AcpNativeSearch, observe_codex_search, safe_url +from agent_bridge.registry import Registry + + +def search_args(tmp_path): + return dict(agent="codex", capability="search", prompt="Find the source", + cwd=str(tmp_path), request_id=str(uuid.uuid4()), user_requested=True) + + +def search_config(): + cfg = AgentConfig(name="codex", protocol="codex", command=["unused"], stall_timeout_sec=0) + return AppConfig(agents={"codex": cfg}) + + +@pytest.mark.parametrize("url", [ + "https://example.org/?X-Amz-Signature=abc", + "https://user:secret@example.org/", + "http://127.0.0.1/", + "http://localhost./", + "https://example.org/?access_token=abc", +]) +def test_source_urls_do_not_export_credentials_or_signed_links(url): + assert safe_url(url) is None + + +@pytest.mark.parametrize("agent,identity,output", [ + ("grok", {"toolName": "web_search"}, {"type": "WebSearch", "citations": ["https://example.org/"]}), + ("grok", {"rawInput": {"variant": "WebSearch"}}, {"type": "WebSearch", "citations": ["https://example.org/"]}), + ("grok", {"_meta": {"x.ai/tool": {"name": "web_search"}}}, {"type": "WebSearch", "citations": ["https://example.org/"]}), + ("minimax", {"name": "web_search"}, {"content": [{"text": json.dumps({"code": 0, "results": [ + {"href": "https://example.org/", "title": "Native"} + ]})}]}), +]) +def test_acp_search_requires_tool_identity_and_success(tmp_path, agent, identity, output): + task = Task(task_id="test", session_id="sess", agent=agent, cwd=str(tmp_path), message="test", native_search=True) + collector = AcpNativeSearch(task, "native-sess") + update = {"toolCallId": "search", "status": "completed", "rawOutput": output} + collector.consume({**update, "toolCallId": "unverified", "title": "web_search"}) + collector.tool_name({"toolCallId": "search", **identity}) + collector.consume({**update, "status": "failed"}) + assert not task.native_calls and not task.sources + collector.consume(update) + collector.consume(update) + assert task.native_calls == {"search": "web_search"} + assert [(source.url, source.tool_call_id) for source in task.sources] == [("https://example.org/", "search")] + + +def test_codex_search_override_is_per_capability(tmp_path, monkeypatch): + cfg = search_config().get("codex") + cfg.config_overrides = ['web_search="cached"'] + adapter = CodexAdapter(cfg, tmp_path) + monkeypatch.setattr(adapter, "_base_cmd", lambda env: ["codex"]) + session = Session(session_id="sess", agent="codex", cwd=str(tmp_path)) + task = Task(task_id="test", session_id="sess", agent="codex", cwd=str(tmp_path), message="test") + ordinary = adapter._build_cmd(session, task) + task.native_search = True + search = adapter._build_cmd(session, task) + assert 'web_search="live"' not in ordinary + assert search.index('web_search="cached"') < search.index('web_search="live"') + assert cfg.config_overrides == ['web_search="cached"'] + + +async def test_codex_search_replay_continuation_and_sources_survive_restart(tmp_path, monkeypatch): + script = tmp_path / "offline_search.py" + script.write_text( + "import json, os, pathlib, sys\n" + "assert 'AGENT_BRIDGE_HUB_TOKEN' not in os.environ\n" + "sys.stdin.read()\n" + "with pathlib.Path('search-submissions.log').open('a') as log:\n" + " log.write(('resume' if 'resume' in sys.argv else 'new') + '\\n')\n" + "events = [\n" + " {'type':'thread.started','thread_id':'thread_search'},\n" + " {'type':'item.completed','item':{'type':'web_search','id':'search_native',\n" + " 'action':{'type':'search'},'results':[{'type':'text_result','url':'https://example.org/native',\n" + " 'title':'Native source'}]}},\n" + " {'type':'item.completed','item':{'type':'agent_message','text':'Offline search findings'}},\n" + " {'type':'turn.completed'},\n" + "]\n" + "for event in events: print(json.dumps(event), flush=True)\n", + encoding="utf-8", + ) + monkeypatch.setenv("AGENT_BRIDGE_HUB_TOKEN", "not-a-real-token") + monkeypatch.setattr(CodexAdapter, "_base_cmd", lambda self, env=None: [sys.executable, str(script)]) + config = search_config() + home = tmp_path / "bridge" + registry = Registry.create(home, config, runtime_context="coordinator") + args = search_args(tmp_path) + await registry.start() + try: + service = BridgeService(registry) + call = await service.call_capability(**args) + result = await service.get_capability_result(call["call_id"], wait_sec=5) + assert result["status"] == "completed" + assert not result["pending"] and result["persisted"] + assert result["sources"] == [{ + "title": "Native source", "url": "https://example.org/native", "tool_call_id": "search_native", + }] + assert result["native_calls"] == {"search_native": "web_search"} + assert result["result_text"] == "Offline search findings" + assert registry.list_sessions() == [] + sid = registry.tasks[call["call_id"]].session_id + assert not (await service.dispatch_task("codex", "ordinary", str(tmp_path), session_id=sid, + user_requested=True))["ok"] + assert not (await service.call_capability(**(args | {"prompt": "changed"})))["ok"] + finally: + await registry.stop() + + registry = Registry.create(home, config, runtime_context="coordinator") + await registry.start() + try: + service = BridgeService(registry) + replay = await service.call_capability(**args) + assert replay["reused"] and replay["call_id"] == call["call_id"] + recovered = await service.get_capability_result(replay["call_id"]) + assert recovered["sources"] == result["sources"] + followup = await service.call_capability(**( + args | {"request_id": str(uuid.uuid4()), "previous_call_id": replay["call_id"]} + )) + final = await service.get_capability_result(followup["call_id"], wait_sec=5) + assert final["status"] == "completed" and not final["pending"] + assert registry.tasks[followup["call_id"]].session_id == sid + assert (tmp_path / "search-submissions.log").read_text().splitlines() == ["new", "resume"] + finally: + await registry.stop() + + +async def test_native_failed_state_flush_submits_zero_calls(tmp_path, monkeypatch): + registry = Registry.create(tmp_path / "bridge", search_config(), runtime_context="coordinator") + await registry.start() + worker = AsyncMock() + monkeypatch.setattr(CodexAdapter, "run_turn", worker) + try: + with monkeypatch.context() as patch: + patch.setattr(registry, "flush_state", AsyncMock(return_value=False)) + service = BridgeService(registry) + call = await service.call_capability(**search_args(tmp_path)) + result = await service.get_capability_result(call["call_id"], wait_sec=5) + assert not call["persisted"] + assert result["status"] == "failed" and not result["pending"] + assert "not submitted" in result["error"] + worker.assert_not_awaited() + finally: + await registry.stop() + + +@pytest.mark.parametrize("action", ["search", "open_page"]) +async def test_pending_through_worker_cleanup_and_fetch_alone_fails(tmp_path, monkeypatch, action): + registry = Registry.create(tmp_path / "bridge", search_config(), runtime_context="coordinator") + entered = asyncio.Event() + gate = asyncio.Event() + + async def run_turn(self, session, task): + observe_codex_search(task, { + "id": "tool", "action": {"type": action, "url": "https://example.org/"}, + "results": [{"type": "text_result", "url": "https://example.org/"}], + }) + session.native_session_id = "thread" + return TurnResult(text="Result") + + async def shutdown(self, session): + entered.set() + await gate.wait() + + monkeypatch.setattr(CodexAdapter, "run_turn", run_turn) + monkeypatch.setattr(CodexAdapter, "shutdown", shutdown) + await registry.start() + try: + service = BridgeService(registry) + args = search_args(tmp_path) + call = await service.call_capability(**args) + await asyncio.wait_for(entered.wait(), timeout=5) + result = await service.get_capability_result(call["call_id"]) + assert result["pending"] + followup = args | {"request_id": str(uuid.uuid4()), "previous_call_id": call["call_id"]} + assert not (await service.call_capability(**followup))["ok"] + gate.set() + result = await service.get_capability_result(call["call_id"], wait_sec=5) + assert not result["pending"] + assert result["status"] == ("completed" if action == "search" else "failed") + finally: + gate.set() + await registry.stop() + + +async def test_cancel_keeps_search_pending_until_worker_closes(tmp_path, monkeypatch): + registry = Registry.create(tmp_path / "bridge", search_config(), runtime_context="coordinator") + started = asyncio.Event() + closing = asyncio.Event() + release = asyncio.Event() + + async def run_turn(self, session, task): + started.set() + await asyncio.Future() + + async def shutdown(self, session): + closing.set() + await release.wait() + + monkeypatch.setattr(CodexAdapter, "run_turn", run_turn) + monkeypatch.setattr(CodexAdapter, "shutdown", shutdown) + await registry.start() + cancelling = None + try: + service = BridgeService(registry) + call = await service.call_capability(**search_args(tmp_path)) + await asyncio.wait_for(started.wait(), timeout=5) + cancelling = asyncio.create_task(service.cancel_capability(call["call_id"])) + await asyncio.wait_for(closing.wait(), timeout=5) + result = await service.get_capability_result(call["call_id"]) + assert result["status"] == "cancelled" and result["pending"] + release.set() + result = await cancelling + assert result["status"] == "cancelled" and not result["pending"] + assert result["remote_cancellation_supported"] is False + finally: + release.set() + if cancelling is not None: + await cancelling + await registry.stop() diff --git a/tests/test_server_tools.py b/tests/test_server_tools.py index f287824..07f11af 100644 --- a/tests/test_server_tools.py +++ b/tests/test_server_tools.py @@ -5,9 +5,11 @@ import sys import time import types +import uuid import pytest +from agent_bridge import server from agent_bridge.processes import reap_subprocess from agent_bridge.registry import Registry from agent_bridge.server import INSTRUCTIONS, _error, _registry, list_sessions, mcp @@ -16,10 +18,13 @@ def test_tools_registered(): names = sorted(mcp._tool_manager._tools) assert names == [ + "call_capability", + "cancel_capability", "cancel_task", "check_task", "dispatch_task", "end_session", + "get_capability_result", "get_result", "get_transcript", "invoke_agent", @@ -30,6 +35,20 @@ def test_tools_registered(): ] +async def test_native_search_mcp_local_fallback(bridge_home, tmp_path, monkeypatch): + monkeypatch.setenv("AGENT_BRIDGE_HUB", "off") + async with server.lifespan(mcp) as backend: + assert isinstance(backend, Registry) + backend.config.coordinator.mode = "manual" + ctx = types.SimpleNamespace(request_context=types.SimpleNamespace(lifespan_context=backend)) + call = await server.call_capability(ctx, "codex", "search", "Find sources", str(tmp_path), str(uuid.uuid4())) + assert not call["ok"] + assert "manual" in call["error"] + assert not backend.tasks + assert not (await server.get_capability_result(ctx, "missing"))["ok"] + assert not (await server.cancel_capability(ctx, "missing"))["ok"] + + def test_handshake_instructions_carry_hard_rules(): assert mcp.instructions == INSTRUCTIONS for phrase in ( From 121222c6724611f44ce698df31cb5e719b51e49a Mon Sep 17 00:00:00 2001 From: Stull Caposole <1409908573@qq.com> Date: Mon, 23 Nov 2026 14:27:51 +0000 Subject: [PATCH 2/4] Request native page evidence in Codex searches Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/agent_bridge/adapters/codex.py | 11 +++++++++-- tests/test_native_search.py | 27 +++++++++++++++++---------- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/src/agent_bridge/adapters/codex.py b/src/agent_bridge/adapters/codex.py index 864486e..36b75e6 100644 --- a/src/agent_bridge/adapters/codex.py +++ b/src/agent_bridge/adapters/codex.py @@ -110,6 +110,13 @@ async def _write_prompt(self, proc: asyncio.subprocess.Process, message: str) -> async def run_turn(self, session: Session, task: Task) -> TurnResult: if task.previous_call_id and not session.native_session_id: raise RuntimeError("native session is missing and cannot be resumed") + prompt = task.message + if task.native_search: + prompt = ( + "Codex CLI may omit structured source URLs from search events. Use native page retrieval " + "to open at least one relevant result page before answering. A URL in the answer alone " + "is not native source evidence.\n\n" + prompt + ) env = self._worker_env() cmd = self._build_cmd(session, task, env) env = self._enforce_spawn_env(env) @@ -119,7 +126,7 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: append_event( session.session_id, "prompt_sent", - {"text": task.message, "cmd": cmd[:8]}, + {"text": prompt, "cmd": cmd[:8]}, self.home, ) proc = await asyncio.create_subprocess_exec( @@ -149,7 +156,7 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: observed_model = task.model or session.model observed_effort = codex_effort(task.effort or session.effort) try: - await self._write_prompt(proc, task.message) + await self._write_prompt(proc, prompt) assert proc.stdout is not None while True: try: diff --git a/tests/test_native_search.py b/tests/test_native_search.py index 16f030b..7862a7d 100644 --- a/tests/test_native_search.py +++ b/tests/test_native_search.py @@ -80,14 +80,15 @@ async def test_codex_search_replay_continuation_and_sources_survive_restart(tmp_ "import json, os, pathlib, sys\n" "assert 'AGENT_BRIDGE_HUB_TOKEN' not in os.environ\n" "assert os.environ['AGENT_BRIDGE_HUB'] == 'off'\n" - "sys.stdin.read()\n" + "assert 'open at least one relevant result page' in sys.stdin.read()\n" "with pathlib.Path('search-submissions.log').open('a') as log:\n" " log.write(('resume' if 'resume' in sys.argv else 'new') + '\\n')\n" "events = [\n" " {'type':'thread.started','thread_id':'thread_search'},\n" " {'type':'item.completed','item':{'type':'web_search','id':'search_native',\n" - " 'action':{'type':'search'},'results':[{'type':'text_result','url':'https://example.org/native',\n" - " 'title':'Native source'}]}},\n" + " 'action':{'type':'search','query':'offline search'}}},\n" + " {'type':'item.completed','item':{'type':'web_search','id':'native_page',\n" + " 'action':{'type':'open_page','url':'https://example.org/native'}}},\n" " {'type':'item.completed','item':{'type':'agent_message','text':'Offline search findings'}},\n" " {'type':'turn.completed'},\n" "]\n" @@ -108,9 +109,9 @@ async def test_codex_search_replay_continuation_and_sources_survive_restart(tmp_ assert result["status"] == "completed" assert not result["pending"] and result["persisted"] assert result["sources"] == [{ - "title": "Native source", "url": "https://example.org/native", "tool_call_id": "search_native", + "title": "https://example.org/native", "url": "https://example.org/native", "tool_call_id": "native_page", }] - assert result["native_calls"] == {"search_native": "web_search"} + assert result["native_calls"] == {"search_native": "web_search", "native_page": "web_fetch"} assert result["result_text"] == "Offline search findings" assert registry.list_sessions() == [] sid = registry.tasks[call["call_id"]].session_id @@ -158,8 +159,14 @@ async def test_native_failed_state_flush_submits_zero_calls(tmp_path, monkeypatc await registry.stop() -@pytest.mark.parametrize("action", ["search", "open_page"]) -async def test_pending_through_worker_cleanup_and_fetch_alone_fails(tmp_path, monkeypatch, action): +@pytest.mark.parametrize(("action", "structured_results", "expected_status"), [ + ("search", True, "completed"), + ("search", False, "failed"), + ("open_page", False, "failed"), +]) +async def test_pending_through_worker_cleanup_and_requires_native_sources( + tmp_path, monkeypatch, action, structured_results, expected_status, +): registry = Registry.create(tmp_path / "bridge", search_config(), runtime_context="coordinator") entered = asyncio.Event() gate = asyncio.Event() @@ -167,10 +174,10 @@ async def test_pending_through_worker_cleanup_and_fetch_alone_fails(tmp_path, mo async def run_turn(self, session, task): observe_codex_search(task, { "id": "tool", "action": {"type": action, "url": "https://example.org/"}, - "results": [{"type": "text_result", "url": "https://example.org/"}], + "results": [{"type": "text_result", "url": "https://example.org/"}] if structured_results else [], }) session.native_session_id = "thread" - return TurnResult(text="Result") + return TurnResult(text="Prose claims a source at https://example.org/") async def shutdown(self, session): entered.set() @@ -191,7 +198,7 @@ async def shutdown(self, session): gate.set() result = await service.get_capability_result(call["call_id"], wait_sec=5) assert not result["pending"] - assert result["status"] == ("completed" if action == "search" else "failed") + assert result["status"] == expected_status finally: gate.set() await registry.stop() From 4b587175601eb2b64856ff27349c08359a69265f Mon Sep 17 00:00:00 2001 From: Stull Caposole <1409908573@qq.com> Date: Mon, 23 Nov 2026 14:28:16 +0000 Subject: [PATCH 3/4] Show native search results in dashboard task detail Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/agent_bridge/dashboard.py | 2 +- src/agent_bridge/share/ui/app.js | 5 +++++ tests/test_dashboard.py | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/agent_bridge/dashboard.py b/src/agent_bridge/dashboard.py index 99fb27a..830538b 100644 --- a/src/agent_bridge/dashboard.py +++ b/src/agent_bridge/dashboard.py @@ -124,7 +124,7 @@ async def handle(self, request: Request) -> Response: continue return JSONResponse(redact({'ok': True, 'tasks': [task.model_dump(mode='json', include={'task_id', 'session_id', 'agent', 'status', - 'message', 'created_at', 'caller_delivery', 'callback_delivery'}) + 'message', 'created_at', 'caller_delivery', 'callback_delivery', 'native_search'}) for task in sorted(self.registry.tasks.values(), key=lambda t: t.created_at, reverse=True)][:500], 'remote': {'enabled': remote.enabled, 'public_url': remote.public_url, 'agents': remote.remote_callable_agents, 'workspaces': remote.remote_workspaces, diff --git a/src/agent_bridge/share/ui/app.js b/src/agent_bridge/share/ui/app.js index 231080a..8104fd6 100644 --- a/src/agent_bridge/share/ui/app.js +++ b/src/agent_bridge/share/ui/app.js @@ -72,6 +72,11 @@ function renderGateway() { } async function loadTranscript() { if (!selected) return; + if (selected.native_search) { + $('transcript').textContent = '原生搜索的内部会话不显示记录。'; + $('more-transcript').hidden = true; + return; + } const taskId = selected.task_id; const data = await api('/v1/sessions/' + selected.session_id + '/transcript?offset=' + transcriptOffset + '&limit=100'); if (selected?.task_id !== taskId) return; diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index f7f25a2..81b808b 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -10,6 +10,7 @@ from agent_bridge import cli from agent_bridge.dashboard import COOKIE, HEADERS from agent_bridge.hub import create_app +from agent_bridge.models import Session, Task, TaskStatus from agent_bridge.registry import Registry from agent_bridge.remote import create_remote_app @@ -137,6 +138,22 @@ async def test_ui_task_flow_and_redacted_audit(dashboard, tmp_path): assert (await client.get('/v1/agents', headers=UI)).json()['agents'][0]['protocol'] == 'fake' +async def test_ui_native_search_result_available_without_internal_transcript(dashboard, tmp_path): + client, _, registry = dashboard + _, response = await login(client) + assert response.status_code == 200 + sid, tid = "sess_search", "task_search" + registry.sessions[sid] = Session(session_id=sid, agent="codex", cwd=str(tmp_path), native_search=True) + registry.tasks[tid] = Task( + task_id=tid, session_id=sid, agent="codex", cwd=str(tmp_path), message="Find public sources", + native_search=True, search_finalized=True, status=TaskStatus.completed, result_text="Search result", + ) + data = (await client.get('/ui/data', headers=UI)).json() + assert data['tasks'][0]['native_search'] is True + assert (await client.get(f'/v1/sessions/{sid}/transcript', headers=UI)).status_code == 400 + assert (await client.get(f'/v1/tasks/{tid}/result', headers=UI)).json()['result_text'] == 'Search result' + + def test_cli_open_and_no_open(monkeypatch, capsys): client = AsyncMock() client.call.return_value = {'ok': True, 'url': ORIGIN + '/ui#code=single-use'} From 8e11107499b9c0dad0f1e23528bca112b0938341 Mon Sep 17 00:00:00 2001 From: Stull Caposole <1409908573@qq.com> Date: Mon, 23 Nov 2026 14:33:32 +0000 Subject: [PATCH 4/4] Show task errors alongside partial dashboard results Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/agent_bridge/share/ui/app.js | 5 ++-- tests/test_dashboard.py | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/agent_bridge/share/ui/app.js b/src/agent_bridge/share/ui/app.js index 8104fd6..60ad458 100644 --- a/src/agent_bridge/share/ui/app.js +++ b/src/agent_bridge/share/ui/app.js @@ -94,9 +94,10 @@ async function loadResult(append = false) { const data = await api('/v1/tasks/' + taskId + '/result?cursor=' + (append ? resultCursor : 0)); if (selected?.task_id !== taskId) return; $('detail-meta').textContent = '代理: ' + data.agent + ' · 状态: ' + (labels[data.status] || data.status) + '\n' + delivery(data) + - '\n远程: ' + JSON.stringify(data.remote || {}) + '\n文件: ' + JSON.stringify(data.files_changed || []); + '\n远程: ' + JSON.stringify(data.remote || {}) + '\n文件: ' + JSON.stringify(data.files_changed || []) + + (data.error ? '\n错误: ' + data.error : ''); if (append) $('result').textContent += data.result_text || ''; - else $('result').textContent = data.result_text || data.error || '任务尚未产生结果'; + else $('result').textContent = data.result_text || (data.error ? '' : '任务尚未产生结果'); resultCursor = data.next_cursor || 0; $('more-result').hidden = !data.has_more; } diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 81b808b..0017d93 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1,6 +1,10 @@ from __future__ import annotations +import asyncio import hashlib +import json +import shutil +import subprocess from unittest.mock import AsyncMock from urllib.parse import parse_qs, urlsplit @@ -154,6 +158,51 @@ async def test_ui_native_search_result_available_without_internal_transcript(das assert (await client.get(f'/v1/tasks/{tid}/result', headers=UI)).json()['result_text'] == 'Search result' +async def test_ui_renders_partial_result_and_error(dashboard, tmp_path): + node = shutil.which('node') + if node is None: + pytest.skip('Node.js is needed to execute dashboard JavaScript') + client, _, registry = dashboard + await login(client) + tid = 'task_failed_search' + registry.tasks[tid] = Task( + task_id=tid, session_id='sess_search', agent='codex', cwd=str(tmp_path), message='Find public sources', + native_search=True, search_finalized=True, status=TaskStatus.failed, result_text='Partial findings', + error='Search requires attributable sources.', + ) + script = (await client.get('/ui/app.js')).text + result = (await client.get(f'/v1/tasks/{tid}/result', headers=UI)).json() + run = await asyncio.to_thread(subprocess.run, [node, '-e', r""" +const {script, result} = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); +const elements = new Map(); +const document = { + querySelectorAll: () => [], + getElementById(id) { + if (!elements.has(id)) elements.set(id, {addEventListener() {}}); + return elements.get(id); + }, +}; +vm.runInNewContext(script.replace(/^initialize\(\);$/m, '') + ` + api = async path => { + assert.match(path, /result[?]/); + return result; + }; + (async () => { + await openTask({task_id: result.task_id, native_search: true}); + assert.equal($('result').textContent, 'Partial findings'); + assert.match($('detail-meta').textContent, /Search requires attributable sources/); + result.result_text = ' with details'; + await loadResult(true); + assert.equal($('result').textContent, 'Partial findings with details'); + assert.match($('detail-meta').textContent, /Search requires attributable sources/); + })(); +`, {assert, document, result, setInterval() {}}); +"""], input=json.dumps({'script': script, 'result': result}), text=True, capture_output=True, timeout=10, check=False) + assert run.returncode == 0, run.stderr + + def test_cli_open_and_no_open(monkeypatch, capsys): client = AsyncMock() client.call.return_value = {'ok': True, 'url': ORIGIN + '/ui#code=single-use'}