Skip to content
Draft
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
28 changes: 28 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,34 @@ on:
pull_request:

jobs:
hub-v2:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
defaults:
run:
working-directory: v2
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '24'
cache: npm
cache-dependency-path: v2/package-lock.json
- run: npm ci
- run: npm test
- run: npm run smoke:package
- name: Real OpenCode with a local mock model (Linux)
if: runner.os == 'Linux'
shell: bash
env:
OPENCODE_SMOKE_BIN: ${{ runner.temp }}/opencode-smoke/node_modules/.bin/opencode
run: |
npm install --prefix "$RUNNER_TEMP/opencode-smoke" opencode-ai@1.19.5 --no-audit --no-fund
npm run smoke:opencode

test:
strategy:
fail-fast: false
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@

## English

The TypeScript + Node.js V2 now runs a shared Hub with managed Workers, task
queues, native-session resume and peer messaging. See the [V2 runtime](v2/README.md)
and [migration notes](v2/MIGRATION.md). V2 is an alpha pending live-product validation.
The installation instructions below still describe the current Python release.

Agent Bridge is a connector for local coding agents. A coordinator — Codex, Cursor, Kimi Code, ZCode, Grok Build, Claude Code, or Devin — directs Antigravity CLI, Grok Build, Kimi Code, DeepSeek Harness, OpenCode, Claude Code, Codex CLI, Devin CLI, ZCode, and MiniMax Code. The same product can be a coordinator and a worker; those are different processes. More agents will follow.

```text
Expand Down Expand Up @@ -168,6 +173,10 @@ uv run pytest

## 中文

中心化 TypeScript + Node.js V2 已实现共享 Hub、Worker 执行、会话续接和双向通信。
参见 [V2 运行时](v2/README.md)、[迁移说明](v2/MIGRATION.md)和[架构说明](v2/ARCHITECTURE.zh-CN.md)。
当前为待真实产品验证的 alpha;以下安装说明仍对应当前 Python 版本。

Agent Bridge 是一个联通各个本地 Agent 的连接器。由协调者——Codex、Cursor、Kimi Code、ZCode、Grok Build、Claude Code 或 Devin——指挥 Antigravity CLI、Grok Build、Kimi Code、DeepSeek Harness、OpenCode、Claude Code、Codex CLI、Devin CLI、ZCode、MiniMax Code 进行工作。同一个产品可以同时是协调者和 Worker,但那是不同进程。后续将推出更多 Agent 支持。

```text
Expand Down
5 changes: 5 additions & 0 deletions v2/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
dist/
*.db
*.db-shm
*.db-wal
67 changes: 67 additions & 0 deletions v2/ARCHITECTURE.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Agent Bridge V2:TypeScript + Node.js 中心运行时

当前实现为可执行 alpha:Hub 管理 Worker、任务、会话和通信,MCP 宿主只是
连接到 Hub 的客户端。真实产品 CLI 尚待环境验证;协议夹具测试已经覆盖主要
生命周期。Python 发布入口与数据保持独立,兼容差异见 [MIGRATION.md](MIGRATION.md)。

## 结构

一个 npm 包、一个常驻进程、一份本机 SQLite WAL 数据库。HTTP 接收命令,SSE
补收事件,stdio MCP 代理供宿主使用。没有 Redis、消息中间件、微服务或通用
插件框架。管理界面、托盘与远程节点不属于本轮运行时迁移。

| 模块 | 职责 |
| --- | --- |
| `contracts.ts`、`config.ts` | 领域对象、输入校验、TOML 覆盖与环境规则 |
| `store.ts` | SQLite 迁移、事务、去重、任务队列、事件与恢复 |
| `runtime.ts` | 会话串行调度、跨会话并发、取消、依赖等待、空闲卸载 |
| `adapters/` | ACP、Codex exec、Antigravity 的启动、选择、续接与结果转换 |
| `process.ts`、`worker-host.ts` | 命令发现、环境、Windows shim、进程树清理 |
| `api.ts`、`hub.ts` | 身份与项目约束、HTTP、SSE、单实例锁、生命周期 |
| `client.ts`、`tools.ts`、`mcp.ts` | 动态发现、工具契约、固定代理身份 |
| `daemon.ts`、`cli.ts` | 并发自动启动、后台/前台运行、命令行操作 |
| `workspace.ts` | Git 文件快照与变更归集 |

## 对象和交付语义

- Agent 是稳定的通信身份;Session 是 Hub 管理的原生会话,具有自己的 Agent。
注册不等于在线。外部桌面会话与 Hub 管理的 Worker 能力不同。
- Task 是持久化执行请求,状态为 queued、running、completed、failed、cancelled
或 interrupted。每个会话只有一个活动 turn,不同会话可并发。
- Message 记录发送者、接收者、线程和消费确认。发给托管会话且 `wake=true`
时,消息、对应任务和事件在一个事务里提交;忙碌会话排队,不偷换为实时插话。
- 消息以 senderId + requestId 去重,任务以 requesterId + requestId 去重。
相同键的冲突内容拒绝;幂等状态跨重启持久化。
- 读取不等于消费,消费不等于完成。外部身份显式确认收件,托管任务成功后
确认其源消息。回复需要显式发送,避免结果自动回流造成无限对话。
- 事件序号在 Hub 内单调递增。客户端保存已消费游标,通过查询或 SSE 重连补收;
不承诺外部模型执行恰好一次。

## 生命周期与委派

MCP 代理退出只断开自身连接。Hub 独立后台运行,所有代理共享同一 profile 的
地址发现和独占锁。每个 Worker 的守护进程观察 Hub IPC;Hub 崩溃也清理它负责的
进程树。Hub 恢复将未完成任务标记为 interrupted,不重放可能已修改文件的请求。

Worker 获取绑定身份、项目的 MCP 凭证与同一 Hub 地址,能发现同伴、发消息、
委派任务并查询结果。无法创建另一个中心,也不会被一刀切禁止委派。等待自身
会话或已知循环依赖会返回错误;消息可以异步发送。协议不支持唤醒外部桌面模型
时如实保留收件箱语义。

模型选择依据运行时返回的选项,切换模型后重新应用 effort;恢复时不把历史重放
混入本轮结果。Codex、Antigravity 各用其原生协议。原生会话不能恢复时返回明确
警告。取消终止执行,不撤销已发生的文件编辑。

## 约束与实现取舍

默认没有任务时长、并发量、消息大小、嵌套层数上限。页大小只是读取参数;完整
数据持久化。可选超时仅来自用户配置,退出宽限用于清理进程。Windows、macOS、
Linux 统一通过 Node 24 运行;Windows 命令 shim 使用 argv 执行,不拼 shell 字符串。

范围凭证约束 API 身份和项目,不能替代操作系统沙箱。运行环境属于同一受信任 OS
用户,服务只监听 loopback,不接受浏览器 Origin 请求。数据留在本机,不共享 SQLite
到网络目录。凭证保存在私有 profile 中,日志对已知环境凭证做脱敏。

同步 SQLite 保持短事务;输出以收到的协议块递增存储。事件当前不自动清理。是否
需要存储线程或批量写入,留给实际性能测量决定。额度查询、Python 历史导入和
管理界面不伪装为已完成,详见迁移说明及验证门槛。
21 changes: 21 additions & 0 deletions v2/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 FeiZhuLulu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
146 changes: 146 additions & 0 deletions v2/MIGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# V2 migration and verification

## Implemented

The TypeScript runtime owns execution end to end: profile ownership and discovery,
automatic detached startup, shared SQLite state, per-session FIFO scheduling,
parallel sessions, cancellation, recovery and process-tree cleanup. Managed
Workers receive the same Hub through identity-bound MCP/CLI tools and can delegate,
read events and reply. Communication does not depend on the originating host.

ACP adapters preserve the existing products' selection conventions, model-specific
effort updates, native restore methods and permission callbacks. Codex exec and
Antigravity use their own JSON transports. Configuration merges `agents.toml`
overlays, preserves explicit argv, supports Windows command shims, and applies
environment rules at the launch boundary.

There are no Bridge-wide quotas or hard concurrency, task duration, message size,
or delegation-depth caps. Explicit operator settings still apply.

## Moving a host

1. Install Node 24, run `npm ci && npm test` inside `v2`, then use the compiled
`dist/cli.js mcp` entry point or install an `npm pack` tarball.
2. Replace that host's Python MCP entry with the [V2 entry](README.md#connect-mcp-hosts).
Use one profile and project key across participating hosts and a distinct peer
ID for each native conversation. Avoid exposing both generations under the
same MCP tool name in one host.
3. Existing `~/.agent-bridge/agents.toml` settings are read as an overlay. For an
isolated trial, pass an explicit `--config` file and `--home` directory. Arrays
replace defaults; an empty array deliberately clears them.
4. Run the product's own login/setup first. `list_agents.available` only establishes
executable discovery. Start with a disposable project and a file-writing task,
then confirm the result from a second MCP host.
5. To revert, stop the V2 Hub and restore the Python MCP entry. Python's original
state and package entry point have not been rewritten.

## Compatibility differences

| Area | V2 behavior |
| --- | --- |
| Scope | Sessions, tasks and peers are shared by project in one Hub, rather than owned by a stdio server |
| Nested Workers | Bound to the same Hub and allowed to delegate; no nested registry or blanket refusal |
| Tool names | Existing dispatch/wait/result/session tools remain; peer/message/event tools are added |
| Tool shape | Task/session arguments and views use snake_case; message/event records and direct HTTP routes use camelCase |
| `list_agents` | Worker availability plus project peers and preferences; quota is explicitly `unknown` |
| Preferences | Hub-wide operator preferences; per-host `AGENT_BRIDGE_MODE` overrides are not used |
| Python state | `state.json`, transcript files and result files are not imported or shared; start new V2 sessions |
| Quota providers | Existing Python account-usage providers are not ported; V2 never invents remaining quota |
| Legacy DSH | Native `dsh --profile acp` is preferred. For old demos, provide a working command including `--config`; no legacy Cordis composition is silently rewritten |
| Environment | Hub process env, named Windows user/machine restoration and system proxy discovery; static PowerShell wrapper parsing is not ported |
| Startup | Explicit Node/bin path replaces Python/uv launch; no automatic login, CLI installation, OS service or update daemon |
| External hosts | Inbox reads are supported; waking an idle native desktop conversation requires host support |
| Crash recovery | All unfinished tasks become interrupted; no automatic replay of workspace mutations |
| Timeouts | Bridge task/startup/stall timeouts disabled by default; poll timeout does not stop work |
| UI | CLI and MCP only; no dashboard, tray or remote-node transport in this runtime change |

The legacy Python skills still describe Python-specific setup and tools. Their
product validation scenarios remain useful, but they are not installed as a V2
runtime instruction bundle. Use this directory's tool descriptions and docs for V2.

## Verification performed

The automated suite uses real MCP proxies, TCP HTTP/SSE, SQLite files and child
processes. Its independent protocol fixtures exercise ACP, Codex and Antigravity
wire events rather than calling adapter internals. It verifies:

- Two hosts share sessions/results after the submitting host disconnects.
- One session queues turns, restores its native ID, changes model and reapplies
the effort accepted by that model; invalid model selection fails visibly.
- A managed message wakes a Worker, which connects back, delegates to a second
Worker, waits for its result and replies in the original thread.
- Cancellation stops active work and removes queued work; later continuation can
restore the native session without leaking replayed history into the result.
- Killing the Hub stops a Worker grandchild; restart reports unfinished work as
interrupted instead of rerunning it.
- Message/task retries are deduplicated; inbox acknowledgement and SSE replay
survive restart. Larger payloads and caller-selected page sizes are accepted.
- Scoped credentials reject impersonation, cross-project access and owner-only
configuration. Manual routing also applies to message-triggered work.
- Simultaneous clients converge on one background Hub and survive their own exit.
- A packed tarball installs and runs its actual bin, discovers bundled config,
starts an independent Hub, calls a tool and shuts down.

CI defines Node 24 jobs on Linux, Windows and macOS, alongside unchanged Python
jobs. Local Linux results are not evidence that the other operating systems or
live product versions have passed; inspect the branch's CI before merging.

### Real CLI with a mock model

The opt-in smoke runs **OpenCode 1.19.5** against a loopback OpenAI-compatible
streaming endpoint. Only model responses are mocked: OpenCode executes its real
shell tools and injected MCP tools, using separate Hub and MCP proxy processes,
native session storage, and disposable Git workspaces. No real API key is needed.
The Linux CI job installs the same pinned CLI and runs this smoke.

On Linux, from `v2`:

```sh
npm install --prefix /tmp/bridge-opencode opencode-ai@1.19.5 --no-audit --no-fund
OPENCODE_SMOKE_BIN=/tmp/bridge-opencode/node_modules/.bin/opencode npm run smoke:opencode
```

Verified locally with Node 24.22.1 on Linux:

- File edits are made by actual CLI tool calls and appear in Bridge's result.
- Two MCP clients share work; disconnecting the submitter does not stop it.
- Repeated request IDs deduplicate; queued turns execute in order and switch
between mock model IDs. The model receives the earlier native history.
- Cancelling active and queued tasks aborts the model request; later turns retain
the native session ID and history after the worker process restarts.
- A message wakes a real CLI, which uses injected Bridge MCP tools to discover,
delegate to another real CLI, wait, read its result, and reply in the same thread.
- Abrupt Hub death stops an active shell tool, including a separate process group.
Restart retains completed results, marks unfinished work interrupted, and resumes
the original native conversation without repeating the file write.

This smoke found a process-cleanup defect: signalling only the CLI's process group
left OpenCode's shell process running. Cleanup now discovers descendants before
stopping the CLI and retains their IDs for forced cleanup. The regression also
uses a separate-group child that ignores SIGTERM. It fails before the fix and
passes after it. A background process already orphaned before shutdown cannot be
identified by its former ancestry and is not covered by this cleanup guarantee.

The mock scripts deterministic responses; it does not validate model reasoning,
provider authentication, billing, effort semantics, or other CLI versions/platforms.

## Live product release gate

Real OpenCode with a mock model is covered above. Authenticated providers and the
remaining product Agent CLIs have not yet been exercised in this environment.
Before promoting this alpha as the Python replacement, use each available real CLI:

1. Record CLI/version, selected model/effort and login route. Run a real file edit
in a disposable Git checkout; inspect both the file and returned result.
2. Reuse the session, change model/effort, unload/revive it and confirm the native
conversation continues. Inspect warnings rather than assuming restore worked.
3. Close the submitting MCP host during work; use another host to observe and
continue it. Cancel another turn and verify its process tree exits.
4. Have a managed Worker call the injected Bridge, delegate and send a same-thread
reply. For Antigravity exercise the documented CLI fallback as needed.
5. Check the installed tarball on Windows with npm `.cmd` commands and paths
containing spaces, then run the same flows on macOS/Linux.

Quota parity and historical state import remain separate compatibility work; neither
is necessary for fresh V2 execution, but both must be explicitly resolved or accepted
before replacing an installation that relies on them.
Loading
Loading