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
4 changes: 3 additions & 1 deletion ORCHESTRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Call `list_agents` first and re-read `coordinator` before every dispatch.

When the user states a **lasting** preference, persist it with `set_preferences`. Its `instructions` argument replaces the stored text — read the current value first and write the merge. One-off wishes are not preferences.

Workers are reached **only** through Agent Bridge MCP tools (`list_agents`, `dispatch_task`, `wait_task`, `check_task`, `get_result`, `get_transcript`, `cancel_task`, `list_sessions`, `end_session`). If those tools are missing, stop and say so. Do **not** run `kimi`, `grok`, `agy`, `dsh`, `opencode`, `claude`, `claude-agent-acp`, `codex`, `devin`, `zcode-acp-server`, or `mcode` yourself. `git` / `pytest` after a turn is review, not a substitute for dispatch.
Workers are reached **only** through Agent Bridge MCP tools (`list_agents`, `list_models`, `dispatch_task`, `wait_task`, `check_task`, `get_result`, `get_transcript`, `cancel_task`, `list_sessions`, `end_session`). If those tools are missing, stop and say so. Do **not** run `kimi`, `grok`, `agy`, `dsh`, `opencode`, `claude`, `claude-agent-acp`, `codex`, `devin`, `zcode-acp-server`, or `mcode` yourself. `git` / `pytest` after a turn is review, not a substitute for dispatch.

## Step 1 — dispatch, or do it yourself?

Expand Down Expand Up @@ -49,6 +49,8 @@ In `auto`/`eager`, tell the user after the fact. In `manual`, their explicit req

## How to dispatch

When `dispatch_enabled=true`, use supported workers' `list_models(agent,cwd)` before choosing a model. See SETUP.md for usage details.

1. `list_agents`. Read `coordinator.mode` / `instructions` / `dispatch_enabled` and `env.proxy` / `env.warnings`. A null proxy on a direct network is normal; if a worker fails with connect errors on a proxied machine, fix `[env.proxy]` instead of retrying.
2. `dispatch_task` with `cwd` = **this conversation's project folder** (absolute). Never the Agent Bridge install path (unless the user is editing Bridge). Never a temp dir. The `message` must be self-contained: background, absolute paths, acceptance criteria, things not to do. Leave `model`/`effort` unset unless you have a reason.
- Antigravity: `agy models` slugs; default `gemini-3.7-flash`.
Expand Down
4 changes: 4 additions & 0 deletions ORCHESTRATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,7 @@ ACP 失败保留字符串 `error`,并可附带 `failure`。`failure.prompt_may
需要重试去重时,在首次调用 `dispatch_task` 前生成 UUID `request_id`,首次调用就传入。重试须使用同一 ID 和原始参数;首次省略了 `session_id`,重试也保持省略。只在重试时补 ID 无法对首次调用去重。相同参数复用原任务(`reused=true`),不同参数直接拒绝。去重只在同一 Bridge 实例内、原任务仍保留时有效,仍须通过正常派发校验。重启 Bridge、切换实例或清理原任务后不再保留绑定;Worker 的外部副作用不保证 exactly-once。

对另一个 Bridge 实例拥有的任务,`check_task` / `get_result` 从 `state.json` 作答——带 `from_state: true`、`silent_for_sec: null`;`wait_task` / `cancel_task` 仍须由拥有它的实例调用。

## 按需查询模型目录

当 `dispatch_enabled=true` 时,选择模型前调用支持此功能的 worker 的 `list_models(agent,cwd)`;字段、缓存、effort 映射和会话行为见 SETUP.md。
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ Close coordinators that are holding Bridge, then `agent-bridge upgrade`, then re
| Tool | Role |
| --- | --- |
| `list_agents` | Probe workers, report remaining quota, proxy/env + coordinator policy |
| `list_models` | Discover advertised models for one worker/project, with cached results |
| `set_preferences` | Persist coordinator mode / routing preferences |
| `dispatch_task` | Start or resume a turn in the project `cwd` |
| `wait_task` | Block up to `timeout_sec` (default 180) |
Expand All @@ -114,6 +115,13 @@ Close coordinators that are holding Bridge, then `agent-bridge upgrade`, then re
| `list_sessions` | Known sessions |
| `end_session` | Shut down a worker process |

Call `list_models(agent="kimi", cwd="/absolute/project")` to discover a worker's
advertised models before choosing one. Supported workers are Kimi, DSH,
Claude Code, Antigravity, and Codex; check `list_agents.model_discovery` for support.
Results are cached per worker/project for one hour by default. Use
`refresh=true` for an immediate update. See [Model discovery](SETUP.md#model-discovery)
for result fields, configuration, and session behavior.

`get_result` returns up to 60,000 characters per call. Continue with
`next_cursor` while `has_more` is true. Detailed work events remain available
through `get_transcript` and `~/.agent-bridge/transcripts/`; sparse task
Expand Down
50 changes: 50 additions & 0 deletions SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,56 @@ uv run --no-sync python scripts/setup_lab.py

If a worker is missing, `list_agents` reports `available: false` and the coordinator should pick another worker or do the work itself.

### Model discovery

`list_agents` includes a `model_discovery` capability block. Query a supported
worker on demand, using this conversation's absolute project directory:

```text
list_models(agent="kimi", cwd="/absolute/project")
list_models(agent="antigravity", cwd="/absolute/project", refresh=true)
```

Supported workers and catalog sources:

| Worker | Source |
| --- | --- |
| Kimi, DSH, Claude Code | ACP `initialize` / `session/new` |
| Antigravity | `agy models` |
| Codex | app-server `model/list`, using app-server configuration and the worker's `config_overrides` |

Discovery uses a separate worker process, closed after the lookup. ACP discovery
denies permission requests and may leave an empty session in worker history.
`list_models` is available when `coordinator.dispatch_enabled=true`.

Result fields:

| Field | Meaning |
| --- | --- |
| `models` | Advertised choices with `id`, `name`, `is_default`, and `supported_efforts` |
| `default_model` | Default model ID reported by the query session; `null` when unknown |
| `supported_efforts` | Worker-native effort levels for a model; `null` means unknown, `[]` means explicitly no levels |
| `source` | Worker interface used for discovery |
| `agent`, `cwd` | Worker name and resolved project directory |
| `fetched_at`, `cached` | Fetch timestamp and whether this response came from cache |
| `availability="advertised"`, `invocation_verified=false` | Results describe the worker's catalog; successful model invocation is a separate check |
| `effort_vocabulary="worker_native"` | Effort names use the worker's vocabulary |
| `warnings` | Discovery diagnostics |

For dispatch, pass `off|low|medium|high|max` to `dispatch_task.effort`;
the adapter maps that value to the worker's effort settings.

```toml
[models]
cache_sec = 3600 # one hour; 0 disables reuse
timeout_sec = 30 # complete lookup deadline, including worker initialization
```

The cache is per worker and project, in memory for this Bridge instance.
Expired entries are refreshed on the next query. Use `refresh=true` after
changing accounts, worker configuration, or model access. A failed refresh
returns an error and preserves the last successful cache entry.

The coordinator can pin a worker model and thinking intensity on `dispatch_task`:

```text
Expand Down
5 changes: 5 additions & 0 deletions agents.toml
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,8 @@ command = ["codex"]
# session_meta = { yolo = true }
revivable = true
idle_unload_sec = 0

# On-demand worker model catalogs.
[models]
cache_sec = 3600
timeout_sec = 30
80 changes: 80 additions & 0 deletions scripts/smoke_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""Smoke-test list_models through an isolated MCP server.

uv run python scripts/smoke_models.py --cwd /absolute/project

Uses a temporary Bridge home under ignored lab/, preserving worker login homes.
ACP may leave empty discovery sessions in the worker's own history.
"""

from __future__ import annotations

import argparse
import asyncio
import json
import os
import shutil
import sys
import tempfile
from pathlib import Path
from typing import Any

from mcp.client.session import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client

from agent_bridge.paths import bridge_home


def payload(result: Any) -> dict:
structured = result.structured_content
if isinstance(structured, dict):
return structured
for content in result.content:
if getattr(content, "type", None) == "text":
return json.loads(content.text)
raise RuntimeError("MCP result contained no JSON payload")


async def run(cwd: Path, agents: list[str], config_home: Path, output: Path | None) -> int:
lab = Path(__file__).resolve().parents[1] / "lab"
lab.mkdir(exist_ok=True)
results = {}
with tempfile.TemporaryDirectory(prefix="model-discovery-", dir=lab) as scratch:
overlay = config_home / "agents.toml"
if overlay.is_file():
shutil.copyfile(overlay, Path(scratch) / "agents.toml")
params = StdioServerParameters(
command=sys.executable,
args=["-c", "from agent_bridge.server import mcp; mcp.run(transport='stdio')"],
cwd=str(cwd),
env={**os.environ, "AGENT_BRIDGE_HOME": scratch, "AGENT_BRIDGE_PARENT_CONTEXT": ""},
)
async with stdio_client(params) as streams, ClientSession(*streams, read_timeout_seconds=120) as session:
await session.initialize()
listing = await session.list_tools()
assert "list_models" in {tool.name for tool in listing.tools}
for agent in agents:
args = {"agent": agent, "cwd": str(cwd)}
discovered = payload(await session.call_tool("list_models", args))
if discovered.get("ok"):
cached = payload(await session.call_tool("list_models", args))
assert cached.get("cached") is True
assert cached["models"] == discovered["models"]
results[agent] = discovered
print(json.dumps({"agent": agent, "ok": discovered.get("ok"),
"models": len(discovered.get("models", [])),
"error": discovered.get("error")}, ensure_ascii=False), flush=True)
sessions = payload(await session.call_tool("list_sessions", {}))
assert sessions["sessions"] == [], "Discovery registered a Bridge work session"
if output:
output.write_text(json.dumps(results, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return 0 if all(result.get("ok") for result in results.values()) else 1


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cwd", type=Path, required=True)
parser.add_argument("--agents", nargs="+", default=["kimi", "dsh", "claude", "antigravity", "codex"])
parser.add_argument("--config-home", type=Path, default=bridge_home())
parser.add_argument("--output", type=Path)
args = parser.parse_args()
raise SystemExit(asyncio.run(run(args.cwd.resolve(), args.agents, args.config_home, args.output)))
6 changes: 5 additions & 1 deletion skills/agent-bridge/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Coordinate local worker agents (Grok Build, Kimi Code, Antigravity,

# Dispatching workers through Agent Bridge

You are the coordinator: users talk only to you, and you call the workers. Workers are reached **only** through the Agent Bridge MCP tools (`list_agents`, `set_preferences`, `dispatch_task`, `wait_task`, `check_task`, `get_result`, `get_transcript`, `cancel_task`, `list_sessions`, `end_session`). If those tools are missing from this session, stop and say so — never run `grok`, `kimi`, `agy`, `dsh`, `opencode`, `claude`, `claude-agent-acp`, `codex`, `devin`, `zcode-acp-server`, or `mcode` CLIs directly, and never drive their GUIs. The same product can be a coordinator and a worker; those are different processes.
You are the coordinator: users talk only to you, and you call the workers. Workers are reached **only** through the Agent Bridge MCP tools (`list_agents`, `list_models`, `set_preferences`, `dispatch_task`, `wait_task`, `check_task`, `get_result`, `get_transcript`, `cancel_task`, `list_sessions`, `end_session`). If those tools are missing from this session, stop and say so — never run `grok`, `kimi`, `agy`, `dsh`, `opencode`, `claude`, `claude-agent-acp`, `codex`, `devin`, `zcode-acp-server`, or `mcode` CLIs directly, and never drive their GUIs. The same product can be a coordinator and a worker; those are different processes.

## Before anything: read the policy

Expand All @@ -19,6 +19,10 @@ Call `list_agents` first. Its result carries:

Claude `status`: shared `5h`/`weekly` only. Before dispatch, even if `ok`, check the target model's `weekly:opus`/`weekly:sonnet`: 0% is exhausted; missing/null unknown. Report reset time or a user-permitted alternative. Model-only data leaves shared status unknown.

## Model discovery

When `coordinator.dispatch_enabled=true` and `list_agents.model_discovery.supported=true`, use `list_models(agent=..., cwd=...)` to obtain worker-advertised model IDs before explicitly selecting a model. Supply this conversation's absolute project directory; use `refresh=true` after changing accounts or worker configuration. `supported_efforts` reports worker-native levels; pass `off|low|medium|high|max` to `dispatch_task.effort` for adapter mapping. See SETUP.md for result fields, caching, and session behavior.

## Step 1 — dispatch, or do it yourself?

A cost question, not a category question; "it is implementation work" is never by itself a reason to dispatch.
Expand Down
129 changes: 129 additions & 0 deletions src/agent_bridge/adapters/acp.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
ClientCapabilities,
DeniedOutcome,
Implementation,
NewSessionResponse,
PermissionOption,
RequestPermissionResponse,
)
Expand Down Expand Up @@ -688,12 +689,140 @@ def __init__(self) -> None:
self.pending_warnings: list[str] = []


class _DiscoveryClient(_BridgeClient):
"""ACP discovery client that denies permission requests and discards updates."""

async def request_permission(
self,
session_id: str,
tool_call: Any,
options: list[Any] | None,
**kwargs: Any,
) -> RequestPermissionResponse:
return RequestPermissionResponse(outcome=DeniedOutcome(outcome="cancelled"))

async def session_update(self, session_id: str, update: Any, **kwargs: Any) -> None:
return None


def _acp_model_catalog(response: NewSessionResponse, agent_name: str) -> dict[str, Any]:
"""Extract model choices and current-model effort levels from an ACP snapshot."""
options = response.config_options or []
model_option_id = next(
(option.id for option in options if option.id == "model" or option.category == "model"),
"model",
)
current, _offered = config_option_values(options, model_option_id)

def model_id(value: str) -> str:
return (_dsh_native_model_label(value) or value) if agent_name == "dsh" else value

default = model_id(current) if current else None
choices = [(model_id(value), name) for value, name in _cursor_choices(options, model_option_id)]
efforts: list[str] | None = None
for option in options:
if option.category == "thought_level" or option.id in {
"thinking", "reasoning_effort",
}:
_current_effort, offered = config_option_values(options, option.id)
# A boolean switch describes thinking enablement, not effort levels.
if offered and set(offered) != {"true", "false"}:
efforts = offered
break
return {
"source": "acp",
"models": [
{
"id": value,
"name": name,
"is_default": value == default,
"supported_efforts": efforts if value == default else None,
}
for value, name in choices
],
"default_model": default,
"warnings": [] if choices else [
"Model discovery is unavailable: the ACP session did not advertise a model catalog."
],
}


async def _cleanup_discovery(live: _Live) -> None:
try:
if live.conn is not None:
with contextlib.suppress(Exception):
await asyncio.wait_for(live.conn.close(), timeout=2)
finally:
try:
if live.proc is not None:
await reap_subprocess(live.proc)
finally:
if live.stderr_task is not None:
live.stderr_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await live.stderr_task


class AcpAdapter(Adapter):
def __init__(self, agent: AgentConfig, home: Path, env_config=None) -> None:
super().__init__(agent, home, env_config)
self._live: dict[str, _Live] = {}
self._cursor_models_cache: dict[str, str] | None = None

async def list_models(self, cwd: str) -> dict[str, Any]:
"""Read a catalog through a separate ACP initialize/session-new handshake.

The caller controls the deadline; this method closes the process on exit.
"""
if self.agent.name == "dsh":
cmd = resolve_dsh_command(self.agent.command, self.agent.fallback_commands)
else:
cmd = resolve_command(self.agent.command, self.agent.fallback_commands)
env = self._env()
if self.agent.name == "dsh":
cmd, env = prepare_dsh_launch(cmd, env)
env = self._enforce_spawn_env(env)
kwargs: dict[str, Any] = {}
if sys.platform == "win32":
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
live = _Live()
try:
live.proc = await asyncio.create_subprocess_exec(
*cmd,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
cwd=self.agent.cwd or cwd or None,
limit=STDIO_LIMIT,
**kwargs,
)
proc = live.proc
client = _DiscoveryClient("model-discovery", self.home, permission_policy="deny")
live.conn = connect_to_agent(client, proc.stdin, proc.stdout)
live.stderr_task = asyncio.create_task(self._drain_stderr(proc, "model-discovery", live))
await live.conn.initialize(
protocol_version=PROTOCOL_VERSION,
client_info=Implementation(name="agent-bridge", version="0.1.0"),
client_capabilities=ClientCapabilities(),
)
created = await live.conn.new_session(cwd=cwd, mcp_servers=[])
return _acp_model_catalog(created, self.agent.name)
except Exception as exc:
raise self._failure(
exc, "model_discovery", proc=live.proc, stderr=live.stderr_tail,
) from None
finally:
# The outer deadline can fire during close(), after the handshake
# already succeeded. Keep cleanup alive and await the reap before
# propagating that cancellation to the registry.
cleanup = asyncio.create_task(_cleanup_discovery(live))
try:
await asyncio.shield(cleanup)
except asyncio.CancelledError:
await cleanup
raise

def _env(self) -> dict[str, str]:
env = build_worker_env(self.agent.env, config=self.env_config, worker_context=True, home=self.home)
if self.agent.name == "claude":
Expand Down
Loading