Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions HUB.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` /
Expand Down
50 changes: 46 additions & 4 deletions src/agent_bridge/adapters/acp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -521,13 +522,27 @@ 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 = []
self.files = set()
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,
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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)
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
38 changes: 33 additions & 5 deletions src/agent_bridge/adapters/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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(
Expand Down Expand Up @@ -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:
Expand All @@ -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 {}
Expand Down Expand Up @@ -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)
Expand All @@ -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)
52 changes: 52 additions & 0 deletions src/agent_bridge/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down
2 changes: 1 addition & 1 deletion src/agent_bridge/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading