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
20 changes: 20 additions & 0 deletions HUB.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,26 @@ A wait timeout is not failure. Invoke returns only the first result page; check
status and retrieve further pages with get_result. Manual coordinator policy
still requires `user_requested:true` on dispatch/invoke (use `call invoke`).

### DSH Desktop baselines

After [installing the same-user connector](SETUP.md#worker-deepseek-harness-desktop),
finish an investigation in a DSH Desktop session and save it as an immutable
fork point. Use the admin Hub API. Scoped worker tokens and the separate
cloud gateway cannot select or inherit saved baselines:

| Operation | Route | Selection |
| --- | --- | --- |
| `create_baseline` | `POST /v1/baselines` | JSON `session_id`, `name`; optional `description`, `user_requested` |
| `list_baselines` | `GET /v1/baselines` | Query `cwd`; optional `agent` (default `dsh`) |
| `set_default_baseline` | `PUT /v1/baselines/default` | JSON `cwd`, `baseline_id` (`null` clears); optional `agent` |

Dispatch or invoke with an explicit `baseline` ID, omit it (or pass `"default"`)
to follow the project's default, or pass `"empty"` to start without history.
Pass `fork_label` to label a new fork. A continuation with `session_id` keeps
its original history. The same fields work with `agent-bridge ask dsh ... --baseline
ID --fork-label NAME` and `agent-bridge call`; the compatibility MCP tools proxy
the same operations to the Hub.

## Peer calls and security

### Headless CLI option and measurements
Expand Down
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ Close coordinators that are holding Bridge, then `agent-bridge upgrade`, then re
| `set_preferences` | Persist coordinator mode / routing preferences |
| `dispatch_task` | Start or resume a turn in the project `cwd` |
| `invoke_agent` | Call a worker until done, with MCP progress (optional timeout) |
| `create_baseline` | Save a named, immutable DSH fork point from a completed session |
| `list_baselines` | Find saved fork points and the project default |
| `set_default_baseline` | Select or clear the default for new DSH sessions |
| `wait_task` | Block up to `timeout_sec` (default 180) |
| `check_task` | Non-blocking status |
| `get_result` | Complete final result in pages + changed files |
Expand All @@ -148,6 +151,20 @@ Close coordinators that are holding Bridge, then `agent-bridge upgrade`, then re
| `list_sessions` | Known sessions |
| `end_session` | Shut down a worker process |

For DSH, finish the shared investigation in one session, then call
`create_baseline(session_id, name)` to save that point. Its returned
`baseline_id` is stable; `name` labels the fork point. Set it as the default
with `set_default_baseline(cwd, baseline_id)`. A new `dispatch_task` can override
this once with `baseline=<baseline_id>`, or use `baseline="empty"` to start
without history. Give each new branch a `fork_label`; `list_sessions` and task
results show both the branch label and its baseline. Passing `session_id`
continues that branch. Clearing the default with
`set_default_baseline(cwd, null)` keeps saved baselines available. Forking
requires a running Hub and the [DSH Desktop connector](SETUP.md#worker-deepseek-harness-desktop).
`list_agents` reports `desktop.connected` and `desktop.fork_available`.
When Desktop is unavailable, new ordinary DSH tasks use ACP; fork requests fail
clearly. Existing sessions stay on their original backend.

`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 Expand Up @@ -319,6 +336,9 @@ revivable = true
| `set_preferences` | 持久化协调者模式 / 路由偏好 |
| `dispatch_task` | 在项目 `cwd` 里开始或续上一次回合 |
| `invoke_agent` | 等到 worker 结束并发送 MCP 进度,可显式设置超时 |
| `create_baseline` | 从已完成的 DSH 会话保存带名称的不可变分叉点 |
| `list_baselines` | 查找已保存的分叉点与项目默认基线 |
| `set_default_baseline` | 为新 DSH 会话设置或清空默认基线 |
| `wait_task` | 最多等待 `timeout_sec`(默认 180) |
| `check_task` | 非阻塞状态查询 |
| `get_result` | 分页读取完整结果 + 改过的文件 |
Expand All @@ -327,6 +347,17 @@ revivable = true
| `list_sessions` | 已知会话 |
| `end_session` | 关掉 worker 进程 |

使用 DSH 时,先在一个会话中完成共同排查,再调用
`create_baseline(session_id, name)` 保存分叉点。返回的 `baseline_id` 是稳定标识,
`name` 是方便查找的标签。`set_default_baseline(cwd, baseline_id)` 将它设为项目默认基线。
新任务可用 `baseline=<baseline_id>` 临时指定其他版本,或用 `baseline="empty"`
从空白开始;用 `fork_label` 给每条新分支命名。`list_sessions` 和任务结果会同时显示
分支标签及来源基线。传入 `session_id` 会继续已有分支。
`set_default_baseline(cwd, null)` 只清空默认选择,不删除已保存的版本。
分叉需要运行 Hub 并安装 [DSH Desktop 连接插件](SETUP.md#worker-deepseek-harness-desktop)。
`list_agents` 会显示 `desktop.connected` 和 `desktop.fork_available`。
桌面断连时,新建普通 DSH 任务回退 ACP,分叉会明确报错;已有会话沿用原后端。

`get_result` 每次最多返回 60,000 个字符;`has_more` 为 true 时,用
`next_cursor` 继续读取。详细工作事件仍可通过 `get_transcript` 和
`~/.agent-bridge/transcripts/` 查询;任务生命周期及错误摘要写入
Expand Down
27 changes: 27 additions & 0 deletions SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,33 @@ disabled stall timeout and a 24-hour turn timeout, both configurable per agent.
Hub/Registry shutdown and idle unload only detach locally, leaving remote work
and billing intact. Explicitly cancel or end_session to stop cloud work.

## Worker: DeepSeek Harness Desktop

To enable named Desktop forks, run `agent-bridge serve` and install the
[`dsh-desktop-connector`](dsh-desktop-connector/) directory from the same checkout
as a local bundle in DSH Desktop's Plugins page. The bundle needs a Desktop Host
with the in-process Session Controller (introduced on the `0.1.7-rc.2` line).
No Desktop core patch is needed. Run both processes as the same OS user, not as
an administrator or service. With a custom `AGENT_BRIDGE_HOME`, set the bundle's
`bridgeHome` to the same absolute directory. On Windows the bundle invokes
`agent-bridge` from Desktop's PATH; set its `bridgeExecutable` to the absolute
path of the installed `agent-bridge.exe` if Desktop cannot find it.

If upgrading from the older standalone connector, disable/uninstall it, delete
the legacy `dsh-desktop.json` from the Bridge home, and fully restart Desktop
to rotate its old launch token. The new connector never reads that file. It
uses a Windows named pipe with a current-user-only ACL and remote clients
disabled, or a Unix socket (mode 0600 in a mode 0700 directory). It neither
opens a network port nor uses a token, URL or cookie for IPC.

`list_agents` reports `desktop.connected` and `desktop.fork_available`. When
connected, new DSH ACP-configured tasks use Desktop; when disconnected, new
ordinary turns use ACP and forks fail explicitly. Existing sessions stay on
their original backend, and an interrupted Desktop turn is not replayed. On
Unix, use a short Bridge home path within the OS socket path-length limit.
Desktop model selection uses `provider/model` and optional effort. See
[the Hub baseline workflow](HUB.md#dsh-desktop-baselines).

## Permissions

Use `agent-bridge callback-secret set NAME` to enter a signing secret (>=32
Expand Down
3 changes: 3 additions & 0 deletions dsh-desktop-connector/cordis.patch.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
- insert:
- id: agent-bridge-dsh-desktop-connector
name: agent-bridge-dsh-desktop-connector
128 changes: 128 additions & 0 deletions dsh-desktop-connector/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { spawn } from 'node:child_process'
import { once } from 'node:events'
import { lstat } from 'node:fs/promises'
import { createConnection } from 'node:net'
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import { createInterface } from 'node:readline'

export const name = 'agent-bridge-dsh-desktop-connector'
export const inject = ['sessionController']

const frameLimit = 16 * 1024 * 1024

async function connect(home, bridgeExecutable) {
if (process.platform === 'win32') {
const child = spawn(bridgeExecutable, ['_dsh-ipc', home], {
stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true,
})
child.on('error', () => {})
return { input: child.stdout, output: child.stdin, close: () => child.kill() }
}
const directory = join(home, 'dsh-ipc')
const endpoint = join(directory, 'desktop.sock')
const [root, dir, socket] = await Promise.all([lstat(home), lstat(directory), lstat(endpoint)])
const uid = process.getuid()
if (!root.isDirectory() || root.uid !== uid || (root.mode & 0o022) !== 0 ||
!dir.isDirectory() || dir.uid !== uid || (dir.mode & 0o777) !== 0o700 ||
!socket.isSocket() || socket.uid !== uid || (socket.mode & 0o777) !== 0o600) {
throw new Error('Agent Bridge Desktop IPC requires a private, current-user socket')
}
const stream = createConnection({ path: endpoint })
try {
await once(stream, 'connect')
} catch (error) {
stream.destroy()
throw error
}
return { input: stream, output: stream, close: () => stream.destroy() }
}

export async function serve(controller, transport, signal) {
const current = new Map()
const { input, output, close } = transport
const onError = () => close()
input.on('error', onError)
output.on('error', onError)
signal.addEventListener('abort', close, { once: true })
const lines = createInterface({ input, crlfDelay: Infinity })
lines.on('error', onError)
async function send(frame) {
const data = JSON.stringify(frame)
if (Buffer.byteLength(data) >= frameLimit) throw new Error('IPC frame too large')
await new Promise((done, fail) => output.write(data + '\n', error => error ? fail(error) : done()))
}

async function run(id, operation, args, active) {
const value = async payload => {
active.throwIfAborted()
await send({ id, type: 'value', value: payload })
}
try {
switch (operation) {
case 'create': await value(await controller.create(args)); break
case 'fork': await value(await controller.fork(args)); break
case 'rename': await value(await controller.rename(args)); break
case 'modelCatalog': await value(await controller.modelCatalog()); break
case 'selectModel': await value(await controller.selectModel(args)); break
case 'prompt': await value(await controller.prompt(args, active)); break
case 'cancel': await value(await controller.cancel(args)); break
case 'follow':
for await (const frame of controller.follow(args, active)) {
if (frame.type === 'snapshot') await value({ type: 'snapshot' })
else if (frame.type === 'event') await value({ type: 'event', event: frame.event })
}
break
default: throw new Error('Unsupported IPC operation')
}
if (!active.aborted) await send({ id, type: 'end' })
} catch {
if (!active.aborted) {
try { await send({ id, type: 'error' }) } catch { close() }
}
} finally {
current.delete(id)
}
}

try {
signal.throwIfAborted()
await send({ dsh_ipc: 1 })
for await (const line of lines) {
if (Buffer.byteLength(line) >= frameLimit) break
const { id, operation, args } = JSON.parse(line)
if (typeof id !== 'string') break
if (operation === 'close') {
current.get(id)?.abort()
} else if (!current.has(id)) {
const abort = new AbortController()
current.set(id, abort)
void run(id, operation, args, abort.signal)
}
}
} finally {
signal.removeEventListener('abort', close)
for (const abort of current.values()) abort.abort()
lines.close()
close()
}
}

export function apply(ctx, config = {}) {
const home = resolve(config.bridgeHome ?? process.env.AGENT_BRIDGE_HOME ?? join(homedir(), '.agent-bridge'))
const executable = config.bridgeExecutable ?? 'agent-bridge'
ctx.effect(() => {
const stop = new AbortController()
let retry
async function run() {
try {
await serve(ctx.sessionController, await connect(home, executable), stop.signal)
} catch {
// Hub and Desktop may start in either order; the transport carries no credentials.
}
if (!stop.signal.aborted) retry = setTimeout(run, 1000)
}
void run()
return () => { stop.abort(); clearTimeout(retry) }
}, 'agent-bridge: same-user Desktop IPC')
}
10 changes: 10 additions & 0 deletions dsh-desktop-connector/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "agent-bridge-dsh-desktop-connector",
"version": "0.2.0",
"private": true,
"type": "module",
"main": "./index.js",
"exports": { ".": "./index.js", "./cordis.patch.yml": "./cordis.patch.yml" },
"dsh": { "bundle": { "patch": "./cordis.patch.yml" } },
"scripts": { "test": "node --test" }
}
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ dependencies = [
"httpx2>=2.5.0",
"pydantic>=2.7",
"psutil>=6.0",
"pywin32>=306; sys_platform == 'win32'",
]

[project.optional-dependencies]
Expand Down
8 changes: 7 additions & 1 deletion src/agent_bridge/adapters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,21 @@
from agent_bridge.adapters.cli import CliAdapter
from agent_bridge.adapters.cloud import CloudAdapter
from agent_bridge.adapters.codex import CodexAdapter
from agent_bridge.adapters.dsh_desktop import DesktopAdapter
from agent_bridge.adapters.fake import FakeAdapter
from agent_bridge.config import AgentConfig, EnvConfig
from agent_bridge.desktop_ipc import DesktopIPC


def build_adapter(cfg: AgentConfig, home: Path, env_config: EnvConfig | None = None) -> Adapter:
def build_adapter(cfg: AgentConfig, home: Path, env_config: EnvConfig | None = None,
*, backend: str | None = None, desktop: DesktopIPC | None = None) -> Adapter:
if cfg.protocol == 'cloud':
return CloudAdapter(cfg, home, env_config)
if cfg.protocol == 'cli':
return CliAdapter(cfg, home, env_config)
if cfg.name == "dsh" and backend == "desktop":
assert desktop is not None
return DesktopAdapter(cfg, home, env_config, desktop)
if cfg.protocol == "fake":
return FakeAdapter(cfg, home, env_config)
if cfg.protocol == "agy":
Expand Down
10 changes: 10 additions & 0 deletions src/agent_bridge/adapters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ def _enforce_spawn_env(self, env: Mapping[str, str]) -> dict[str, str]:
set(self.env_config.set) | set(self.agent.env),
)

def can_fork(self) -> bool:
"""Whether this worker can create a derived session from a source one.

Defaults to False so a worker never silently produces a blank session
where the coordinator asked for an inherited one. Adapters that
implement forking override this and must still verify the capability
with the running worker before they fork.
"""
return False

@abstractmethod
async def ensure_session(self, session: Session) -> None: ...

Expand Down
Loading
Loading