diff --git a/HUB.zh-CN.md b/HUB.zh-CN.md index f021ebb..34e1db0 100644 --- a/HUB.zh-CN.md +++ b/HUB.zh-CN.md @@ -57,6 +57,23 @@ Hub 启动的 worker 仍通过环境获得凭证。重启后找不到签名密 远程调用只能使用独立网关。这是可信本机用户的接口,不是沙箱; 持有 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 上开放,不属于公网网关。Hub worker +凭自己的会话令牌发起搜索,受调用深度限制,只能查询、取消或续接自己提交的搜索; +执行原生搜索的 worker 本身不接收 Hub 令牌。 + ## 阻塞调用与异步回推 `invoke` / `ask` 默认等到终态,不再有 180 秒上限;显式 `timeout_sec` / diff --git a/src/agent_bridge/adapters/acp.py b/src/agent_bridge/adapters/acp.py index d7feac2..0db8edf 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 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": @@ -898,7 +920,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) ) @@ -1625,7 +1647,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 @@ -1672,12 +1696,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", @@ -1719,12 +1749,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): @@ -1758,6 +1793,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 @@ -1803,7 +1839,10 @@ async def cancel(self, session: Session) -> None: async def shutdown(self, session: Session) -> None: if self.worker_tokens is not None: self.worker_tokens.revoke(session.session_id) - 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 @@ -1813,10 +1852,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 0cab813..18c6c72 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 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,6 +108,15 @@ 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") + 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) @@ -113,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( @@ -145,7 +158,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: @@ -172,6 +185,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 {} @@ -258,9 +280,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) @@ -270,4 +293,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 242cdc2..52e909e 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/dashboard.py b/src/agent_bridge/dashboard.py index 520b89e..36285d1 100644 --- a/src/agent_bridge/dashboard.py +++ b/src/agent_bridge/dashboard.py @@ -130,7 +130,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, diff --git a/src/agent_bridge/hub.py b/src/agent_bridge/hub.py index 67ce6d6..9a892f9 100644 --- a/src/agent_bridge/hub.py +++ b/src/agent_bridge/hub.py @@ -103,7 +103,8 @@ async def handle(request: Request): if not owner and caller is None: return JSONResponse(_error(PermissionError('invalid bearer token')), status_code=401) if caller is not None and tool not in {'health', 'list_agents', 'dispatch_task', 'invoke', - 'check_task', 'wait_task', 'get_result', 'get_transcript', 'cancel_task'}: + 'check_task', 'wait_task', 'get_result', 'get_transcript', 'cancel_task', + 'call_capability', 'get_capability_result', 'cancel_capability'}: return JSONResponse(_error(PermissionError('worker token cannot access this tool')), status_code=403) if tool == 'health': return JSONResponse({'ok': True}) @@ -123,8 +124,10 @@ async def handle(request: Request): if caller is not None: if args.get('callback_secret_name') is not None: return JSONResponse(_error(PermissionError('callback_secret_name is admin-only')), status_code=403) - if tool in {'check_task', 'wait_task', 'get_result', 'cancel_task'}: - task = registry.tasks.get(args.get('task_id', '')) + if tool in {'check_task', 'wait_task', 'get_result', 'cancel_task', + 'get_capability_result', 'cancel_capability'}: + key = 'call_id' if tool in {'get_capability_result', 'cancel_capability'} else 'task_id' + task = registry.tasks.get(args.get(key, '')) if task is None or task.caller_session_id != caller: return JSONResponse(_error(PermissionError('task is not owned by caller')), status_code=403) if tool == 'get_transcript' or (tool in {'dispatch_task', 'invoke'} and args.get('session_id')): @@ -137,20 +140,23 @@ 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' 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_name', None) diff --git a/src/agent_bridge/hub_client.py b/src/agent_bridge/hub_client.py index 5301294..bb351f1 100644 --- a/src/agent_bridge/hub_client.py +++ b/src/agent_bridge/hub_client.py @@ -30,6 +30,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'), @@ -45,7 +48,7 @@ def __init__(self, url: str, token: str = '') -> None: async def call(self, tool: str, **kwargs: Any) -> dict[str, Any]: try: - if self.host_manual_mode and tool in {'dispatch_task', 'invoke'} and not kwargs.get('user_requested'): + if self.host_manual_mode and tool in {'dispatch_task', 'invoke', 'call_capability'} and not kwargs.get('user_requested'): raise RuntimeError('coordinator mode is manual: retry with user_requested=true only when the user explicitly requested a worker') return await self._call(tool, **kwargs) except Exception as exc: diff --git a/src/agent_bridge/models.py b/src/agent_bridge/models.py index df15099..dc9e970 100644 --- a/src/agent_bridge/models.py +++ b/src/agent_bridge/models.py @@ -102,6 +102,7 @@ def grok_effort(effort: str | None) -> str | None: class Session(BaseModel): + native_search: bool = False caller_session_id: str | None = None remote_origin: bool = False call_depth: int = 0 @@ -135,7 +136,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..058eac8 --- /dev/null +++ b/src/agent_bridge/native_search.py @@ -0,0 +1,236 @@ +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"} + + +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 36cea8c..99a5dfe 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 @@ -42,6 +43,7 @@ normalize_effort, validate_selection, ) +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, @@ -511,6 +513,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 @@ -737,6 +743,8 @@ async def dispatch_task( callback_secret_name: str | None = None, notification_source_task_id: str | None = None, remote_origin: bool = False, + _native_search: bool = False, + _previous_call_id: str | None = None, ) -> dict: if not self.dispatch_enabled: raise RuntimeError(NESTED_DISPATCH_ERROR) @@ -747,6 +755,8 @@ async def dispatch_task( 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 @@ -772,6 +782,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') @@ -790,8 +802,12 @@ async def dispatch_task( request: tuple = (agent, message, resolved_cwd, session_id, model, effort, title, user_requested) if cloud: request += (repo, ref) - legacy_request = request if not any((notify_caller, caller_session_id, callback_url, callback_secret_name)) else None + legacy_request = request if not _native_search and not any( + (notify_caller, caller_session_id, callback_url, callback_secret_name) + ) else None request += (notify_caller, caller_session_id, callback_url, callback_secret_name) + 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] @@ -810,10 +826,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 caller_session_id and caller_session_context.get() == caller_session_id and session.caller_session_id != caller_session_id: raise ValueError('session is not owned by caller') if session.agent != agent: @@ -838,6 +870,7 @@ async def dispatch_task( session.caller_session_id = None else: session = Session( + native_search=_native_search, caller_session_id=caller_session_id, call_depth=depth, session_id=_new_id("sess"), @@ -865,6 +898,9 @@ async def dispatch_task( if caller_session_id: session.call_depth = max(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, @@ -908,13 +944,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, @@ -925,6 +970,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] @@ -940,7 +1033,7 @@ async def _run_task(self, task_id: str) -> None: worker_context = None try: self.worker_tokens.active.add(session.session_id) - if session.remote_origin: + if session.remote_origin or session.native_search: worker_context = hub_worker_context.set({'AGENT_BRIDGE_HUB': 'off'}) elif self.worker_url is not None: env = {'AGENT_BRIDGE_HUB_URL': self.worker_url} @@ -966,6 +1059,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 @@ -1093,7 +1188,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) @@ -1109,7 +1211,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: @@ -1243,7 +1346,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) @@ -1556,6 +1662,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, @@ -1601,6 +1736,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) @@ -1616,7 +1754,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() @@ -1625,6 +1768,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 @@ -1642,6 +1789,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( @@ -1673,7 +1822,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}") self.worker_tokens.revoke(session_id) busy = self._busy_task(session_id) diff --git a/src/agent_bridge/server.py b/src/agent_bridge/server.py index 8b0ea07..a3779ec 100644 --- a/src/agent_bridge/server.py +++ b/src/agent_bridge/server.py @@ -204,6 +204,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/src/agent_bridge/share/ui/app.js b/src/agent_bridge/share/ui/app.js index 94e6f39..690e618 100644 --- a/src/agent_bridge/share/ui/app.js +++ b/src/agent_bridge/share/ui/app.js @@ -170,6 +170,11 @@ function renderMetadata(data) { } 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; @@ -188,7 +193,7 @@ async function loadResult(append = false) { if (selected?.task_id !== taskId) return; renderMetadata(data); 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/dashboard_ui.test.cjs b/tests/dashboard_ui.test.cjs index a4f0abc..3bb371e 100644 --- a/tests/dashboard_ui.test.cjs +++ b/tests/dashboard_ui.test.cjs @@ -74,6 +74,33 @@ test('metadata renders labeled values and pills, hiding empty remote/file fields assert.match(get('detail-meta').textContent, /变更文件app.js/); assert.match(get('detail-meta').textContent, /错误执行失败/); }); +test('native search detail shows partial results and errors without reading internal transcripts', async () => { + const {run, get, context} = setup(); + const result = {ok: true, task_id: 'task_search', agent: 'codex', status: 'failed', + error: 'Search requires attributable sources.'}; + const requests = []; + context.fetch = async url => { + requests.push(url); + const body = { + '/v1/tasks/task_search/result?cursor=0': {...result, result_text: 'Partial findings', next_cursor: 16, has_more: true}, + '/v1/tasks/task_search/result?cursor=16': {...result, result_text: ' with details'}, + '/ui/data': {ok: true, tasks: [], audit: [], approvals: [], remote: {agents: [], workspaces: {}}}, + '/v1/sessions': {ok: true, sessions: []}, + }[url]; + assert.ok(body, 'Unexpected request: ' + url); + return {ok: true, json: async () => body}; + }; + await run("openTask({task_id:'task_search',session_id:'sess_search',native_search:true})"); + assert.equal(get('result').textContent, 'Partial findings'); + assert.match(get('detail-meta').textContent, /Search requires attributable sources/); + assert.equal(get('more-transcript').hidden, true); + await run('loadResult(true)'); + assert.equal(get('result').textContent, 'Partial findings with details'); + assert.match(get('detail-meta').textContent, /Search requires attributable sources/); + await run('authenticated = true; refresh()'); + assert.equal(requests.filter(url => url.endsWith('cursor=0')).length, 2); + assert.equal(requests.some(url => url.includes('/transcript')), false); +}); test('gateway uses workspace list, audit columns and outcome pills instead of JSON', () => { const {run, get} = setup(); run(`snapshot.remote={enabled:true,require_approval:true,public_url:'',agents:['fake'],workspaces:{project:'/repo'}}; diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 81d2e18..230f94d 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -14,6 +14,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 @@ -151,6 +152,25 @@ 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.failed, result_text="Partial findings", + error="Search requires attributable sources.", + ) + 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 + result = (await client.get(f'/v1/tasks/{tid}/result', headers=UI)).json() + assert result['result_text'] == 'Partial findings' + assert result['error'] == 'Search requires attributable sources.' + + async def test_dashboard_workspace_paths_are_canonical(dashboard, tmp_path, monkeypatch): client, _, registry = dashboard monkeypatch.setenv('HOME', str(tmp_path)) diff --git a/tests/test_hub.py b/tests/test_hub.py index 622a43e..f279850 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -6,6 +6,7 @@ import os import sys import types +import uuid from pathlib import Path from unittest.mock import AsyncMock @@ -22,6 +23,8 @@ from agent_bridge.config import AgentConfig, CliConfig, EnvConfig, load_config from agent_bridge.hub import create_app, serve, 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 @@ -132,7 +135,7 @@ async def test_worker_cannot_use_owner_callback_secret(worker, tmp_path, route): assert registry.tasks[response.json()['task_id']].callback_signed -@pytest.mark.parametrize('route', ['/v1/tasks', '/v1/agents/fake/invoke']) +@pytest.mark.parametrize('route', ['/v1/tasks', '/v1/agents/fake/invoke', '/v1/capabilities']) async def test_worker_turn_ends_while_reading_body(worker, tmp_path, monkeypatch, route): client, registry, root, env = worker authenticated = asyncio.Event() @@ -146,11 +149,15 @@ def check(token): monkeypatch.setattr(registry.worker_tokens, 'authenticate', check) before = set(registry.tasks) + payload = {'agent': 'fake', 'message': 'late child', 'cwd': str(tmp_path)} + if route == '/v1/capabilities': + payload = {'agent': 'codex', 'capability': 'search', 'prompt': 'Search', 'cwd': str(tmp_path), + 'request_id': str(uuid.uuid4())} async def body(): await asyncio.wait_for(authenticated.wait(), 5) registry.worker_tokens.active.discard(root['session_id']) - yield json.dumps({'agent': 'fake', 'message': 'late child', 'cwd': str(tmp_path)}).encode() + yield json.dumps(payload).encode() response = await client.post(route, content=body(), headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + env['AGENT_BRIDGE_HUB_TOKEN']}) @@ -308,6 +315,77 @@ def handle(request): assert (await HubClient('http://hub', 'abw_' + 'h' * 43).call('list_agents'))['ok'] +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): + env = build_worker_env(worker_context=True, log_fill=False) + assert env["AGENT_BRIDGE_HUB"] == "off" + assert "AGENT_BRIDGE_HUB_TOKEN" not in env + 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 + registry.worker_tokens.active.update({"unknown", "test-root", "test-peer"}) + orphan_token = registry.worker_tokens.issue("unknown") + assert (await client.post("/v1/capabilities", json=body, headers={ + "Authorization": f"Bearer {orphan_token}", + })).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}) + root_token = registry.worker_tokens.issue(root.session_id) + peer_token = registry.worker_tokens.issue(peer.session_id) + response = await client.post("/v1/capabilities", json=body | {"callback_secret_name": "owner"}, + headers={"Authorization": f"Bearer {root_token}"}) + assert response.status_code == 403 and "admin-only" in response.json()["error"] + peer_headers = {"Authorization": f"Bearer {peer_token}", "X-Agent-Bridge-Caller": root.session_id} + response = await client.post("/v1/capabilities", json=body, headers=peer_headers) + 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)) + backend = HubClient("http://hub", root_token) + backend.host_manual_mode = True + ctx = types.SimpleNamespace(request_context=types.SimpleNamespace(lifespan_context=backend)) + blocked = await server.call_capability(ctx, **(body | {"user_requested": False})) + assert not blocked["ok"] and "manual" in blocked["error"] + assert not registry.tasks + 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 client.get(path + "/result", headers=peer_headers)).status_code == 403 + assert (await client.post(path + "/cancel", headers=peer_headers)).status_code == 403 + peer.call_depth = 0 + followup = body | {"request_id": str(uuid.uuid4()), "previous_call_id": task.task_id} + denied = await client.post("/v1/capabilities", json=followup, headers=peer_headers) + assert denied.status_code == 400 and "session is not owned by caller" in denied.json()["error"] + continued = await server.call_capability(ctx, **followup) + assert continued["ok"] + assert (await server.get_capability_result(ctx, continued["call_id"], wait_sec=5))["status"] == "completed" + 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..7862a7d --- /dev/null +++ b/tests/test_native_search.py @@ -0,0 +1,241 @@ +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" + "assert os.environ['AGENT_BRIDGE_HUB'] == 'off'\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','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" + "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": "https://example.org/native", "url": "https://example.org/native", "tool_call_id": "native_page", + }] + 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 + 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", "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() + + 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/"}] if structured_results else [], + }) + session.native_session_id = "thread" + return TurnResult(text="Prose claims a source at https://example.org/") + + 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"] == expected_status + 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 (