diff --git a/HUB.md b/HUB.md index 4e8215a..83d8f25 100644 --- a/HUB.md +++ b/HUB.md @@ -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 diff --git a/README.md b/README.md index 734d130..1f2d79d 100644 --- a/README.md +++ b/README.md @@ -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 | @@ -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=`, 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 @@ -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` | 分页读取完整结果 + 改过的文件 | @@ -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="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/` 查询;任务生命周期及错误摘要写入 diff --git a/SETUP.md b/SETUP.md index e68673f..bac329e 100644 --- a/SETUP.md +++ b/SETUP.md @@ -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 diff --git a/dsh-desktop-connector/cordis.patch.yml b/dsh-desktop-connector/cordis.patch.yml new file mode 100644 index 0000000..e5fb617 --- /dev/null +++ b/dsh-desktop-connector/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: agent-bridge-dsh-desktop-connector + name: agent-bridge-dsh-desktop-connector diff --git a/dsh-desktop-connector/index.js b/dsh-desktop-connector/index.js new file mode 100644 index 0000000..67f8c00 --- /dev/null +++ b/dsh-desktop-connector/index.js @@ -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') +} diff --git a/dsh-desktop-connector/package.json b/dsh-desktop-connector/package.json new file mode 100644 index 0000000..ed1d343 --- /dev/null +++ b/dsh-desktop-connector/package.json @@ -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" } +} diff --git a/pyproject.toml b/pyproject.toml index 4b2f8cf..853769e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,6 +15,7 @@ dependencies = [ "httpx2>=2.5.0", "pydantic>=2.7", "psutil>=6.0", + "pywin32>=306; sys_platform == 'win32'", ] [project.optional-dependencies] diff --git a/src/agent_bridge/adapters/__init__.py b/src/agent_bridge/adapters/__init__.py index d269829..73685c9 100644 --- a/src/agent_bridge/adapters/__init__.py +++ b/src/agent_bridge/adapters/__init__.py @@ -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": diff --git a/src/agent_bridge/adapters/base.py b/src/agent_bridge/adapters/base.py index daae4a9..005d312 100644 --- a/src/agent_bridge/adapters/base.py +++ b/src/agent_bridge/adapters/base.py @@ -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: ... diff --git a/src/agent_bridge/adapters/dsh_desktop.py b/src/agent_bridge/adapters/dsh_desktop.py new file mode 100644 index 0000000..6d75f58 --- /dev/null +++ b/src/agent_bridge/adapters/dsh_desktop.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import asyncio +import contextlib +import uuid +from pathlib import Path + +from agent_bridge.adapters.base import Adapter +from agent_bridge.config import AgentConfig, EnvConfig +from agent_bridge.desktop_ipc import DesktopIPC, DesktopUnavailable +from agent_bridge.models import Session, Task, TurnResult +from agent_bridge.transcript import append_event, mark_worker_activity + + +def _message_text(event: dict) -> str: + content = event.get("data", {}).get("message", {}).get("content", []) + return "".join(part.get("text", "") for part in content if part.get("type") == "text") + + +class DesktopAdapter(Adapter): + resident = False + + def __init__(self, agent: AgentConfig, home: Path, env_config: EnvConfig | None, ipc: DesktopIPC) -> None: + super().__init__(agent, home, env_config) + self.ipc = ipc + + def can_fork(self) -> bool: + return True + + async def ensure_session(self, session: Session) -> None: + if session.native_session_id: + return + if session.fork_source_id: + created = await self.ipc.call("fork", {"sessionId": session.fork_source_id}) + else: + created = await self.ipc.call("create", {"cwd": session.cwd}) + session.native_session_id = created["sessionId"] + if session.title or session.fork_label: + await self.ipc.call("rename", { + "sessionId": session.native_session_id, + "title": session.fork_label or session.title, + }) + + async def run_turn(self, session: Session, task: Task) -> TurnResult: + await self.ensure_session(session) + native_id = session.native_session_id + assert native_id is not None + if task.model or task.effort: + if task.model: + if "/" not in task.model: + raise ValueError("Desktop model selection must be provider/model") + provider, model = task.model.split("/", 1) + else: + default = (await self.ipc.call("modelCatalog", {}))["default"] + provider, model = default["provider"], default["model"] + selection = {"sessionId": native_id, "provider": provider, "model": model} + if task.effort: + selection["reasoningEffort"] = task.effort + await self.ipc.call("selectModel", selection) + + text_parts: list[str] = [] + completed_tool_calls: set[str] = set() + request_id = str(uuid.uuid4()) + active_turn: int | None = None + latest_turn: int | None = None + async with self.ipc.request("follow", {"address": {"kind": "session", "sessionId": native_id}}) as frames: + opening = await asyncio.wait_for(anext(frames, None), 10) + if opening != {"type": "snapshot"}: + raise RuntimeError("DeepSeek Harness follow stream did not open") + append_event(session.session_id, "prompt_sent", {"text": task.message}, self.home) + await self.ipc.call("prompt", {"requestId": request_id, "sessionId": native_id, + "mode": "queue", "content": [{"type": "text", "text": task.message}]}) + async for value in frames: + if value.get("type") != "event": + continue + event = value.get("event", {}) + kind = event.get("type") + data = event.get("data", {}) + if kind == "turn/start": + latest_turn = data.get("turn") + if kind == "user/message" and data.get("source", {}).get("rpcId") == request_id: + active_turn = latest_turn + if active_turn is None: + continue + mark_worker_activity(session.session_id, self.home) + if kind == "assistant/message": + text = _message_text(event) + text_parts.append(text) + if text: + append_event(session.session_id, "message_chunk", {"text": text}, self.home) + elif kind == "tool/call": + append_event(session.session_id, "tool_call", { + "tool_call_id": data.get("callId"), "title": data.get("name"), + }, self.home) + elif kind == "tool/result": + message = data.get("message", {}) + call_id = message.get("toolCallId") + surface_op = event.get("surfaceOp") + if isinstance(surface_op, dict) and surface_op.get("op") == "replace": + continue + if not isinstance(call_id, str) or call_id in completed_tool_calls: + continue + completed_tool_calls.add(call_id) + append_event(session.session_id, "tool_call_update", { + "tool_call_id": call_id, + "status": "failed" if message.get("isError") else "completed", + }, self.home) + elif kind == "turn/end" and data.get("turn") == active_turn: + reason = data.get("reason", {}) + stop = reason.get("kind", "completed") + if stop == "aborted": + stop = "cancelled" + append_event(session.session_id, "turn_end", {"stop_reason": stop}, self.home) + return TurnResult(text="".join(text_parts), stop_reason=stop, + native_session_id=native_id, observed_model=task.model, + observed_effort=task.effort, + error=reason.get("error", {}).get("message") if stop == "error" else None) + raise DesktopUnavailable("DeepSeek Harness follow stream closed before turn ended") + + async def cancel(self, session: Session) -> None: + if session.native_session_id: + with contextlib.suppress(DesktopUnavailable): + await self.ipc.call("cancel", {"sessionId": session.native_session_id}) + + async def shutdown(self, session: Session) -> None: + pass diff --git a/src/agent_bridge/api.py b/src/agent_bridge/api.py index 242cdc2..d3c7f4a 100644 --- a/src/agent_bridge/api.py +++ b/src/agent_bridge/api.py @@ -83,6 +83,8 @@ async def dispatch_task( notify_caller: bool = False, callback_url: str | None = None, callback_secret_name: str | None = None, + baseline: str | None = None, + fork_label: str | None = None, ) -> dict[str, Any]: """Start a worker turn. Local workers require an absolute existing cwd. Cloud workers ignore cwd and accept optional repo/ref overrides; follow-ups keep their repository/ref. Cloud Cursor model is a model ID; Devin model is a mode, or effort maps off/low/medium/high/max to fast/lite/normal/ultra/ultra. Remote results carry provider IDs, URLs and PRs rather than local file changes. Cancelling Devin terminates the remote session permanently. Local model/effort behavior is unchanged. Pass session_id to continue. Set user_requested=true only when the user explicitly asked for a worker (required in manual mode). Rejected when coordinator.dispatch_enabled is false. For retry deduplication, supply a UUID request_id on the first call and replay the same ID and original arguments; identical retries reuse the task, different arguments are rejected. Bindings are lost on restart and are not shared with other instances. Returns immediately.""" try: @@ -102,11 +104,34 @@ async def dispatch_task( caller_session_id=caller_session_context.get(), callback_url=callback_url, callback_secret_name=callback_secret_name, + baseline=baseline, + fork_label=fork_label, ) return {"ok": True, **result} except Exception as exc: return _error(exc) + async def create_baseline(self, session_id: str, name: str, description: str | None = None, + user_requested: bool = False) -> dict[str, Any]: + try: + return {"ok": True, **await self.registry.create_baseline( + session_id, name, description, user_requested=user_requested, + )} + except Exception as exc: + return _error(exc) + + async def list_baselines(self, cwd: str, agent: str = "dsh") -> dict[str, Any]: + try: + return {"ok": True, **self.registry.list_baselines(cwd, agent)} + except Exception as exc: + return _error(exc) + + async def set_default_baseline(self, cwd: str, baseline_id: str | None, agent: str = "dsh") -> dict[str, Any]: + try: + return {"ok": True, **await self.registry.set_default_baseline(cwd, agent, baseline_id)} + except Exception as exc: + return _error(exc) + async def wait_task(self, task_id: str, timeout_sec: float = DEFAULT_WAIT_SEC) -> dict[str, Any]: """Wait until a task finishes or timeout_sec elapses (default 180). Timeout is not failure; call wait_task again. Stay under the host MCP tool timeout (Codex tool_timeout_sec, typically 600). Payloads carry silent_for_sec / stall_timeout_sec and files_changed_state (pending, collected, or unavailable).""" try: diff --git a/src/agent_bridge/baselines.py b/src/agent_bridge/baselines.py new file mode 100644 index 0000000..df1e4bc --- /dev/null +++ b/src/agent_bridge/baselines.py @@ -0,0 +1,189 @@ +"""Immutable baseline records and persistent per-scope default selectors. + +Storage layout under the Bridge home:: + + baselines/records/.json # one immutable record per file + baselines/defaults/.json # selector for one project+agent scope + +Records are never rewritten: :meth:`BaselineStore.add` refuses an existing ID. +The default selector for a scope lives in its own file, so two Bridge +instances working on different projects (or with different workers) never +overwrite each other. Every read goes to disk on demand, which gives +independent instances cross-instance visibility without a lock or cache. +Corrupt files raise :class:`BaselineCorruptionError` instead of being folded +into an empty state. +""" + +from __future__ import annotations + +import hashlib +import os +import re +from pathlib import Path +from typing import Any + +from pydantic import BaseModel, Field, ValidationError + +from agent_bridge.models import iso +from agent_bridge.persist import atomic_write_json, read_json + +_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}") +_MISSING = object() +_SCOPE_SEPARATOR = "\x00" + + +class BaselineCorruptionError(RuntimeError): + """A baseline file exists but cannot be read as valid baseline state.""" + + +class Baseline(BaseModel): + """One immutable saved baseline, captured from a completed DSH turn.""" + + baseline_id: str + name: str + description: str | None = None + agent: str + backend: str | None = None + cwd: str + native_session_id: str + source_session_id: str + model: str | None = None + effort: str | None = None + created_at: str = Field(default_factory=iso) + + +def _validate_id(baseline_id: object) -> str: + """Reject anything that is not a safe single-segment filename component.""" + if not isinstance(baseline_id, str) or not _ID_PATTERN.fullmatch(baseline_id) or ".." in baseline_id: + raise ValueError(f"invalid baseline id {baseline_id!r}") + return baseline_id + + +def _canonical_cwd(cwd: str | os.PathLike[str]) -> str: + if isinstance(cwd, os.PathLike): + cwd = os.fspath(cwd) + if not isinstance(cwd, str) or not cwd.strip(): + raise ValueError("cwd must be a non-empty path") + return os.path.normcase(str(Path(cwd).expanduser().resolve())) + + +def _agent_key(agent: str) -> str: + if not isinstance(agent, str) or not agent.strip(): + raise ValueError("agent must be a non-empty name") + return agent.strip() + + +def _scope_identity(cwd: str | os.PathLike[str], agent: str) -> tuple[str, str]: + return _canonical_cwd(cwd), _agent_key(agent) + + +def _scope_filename(cwd: str | os.PathLike[str], agent: str) -> str: + material = f"{_canonical_cwd(cwd)}{_SCOPE_SEPARATOR}{_agent_key(agent)}" + return f"{hashlib.sha256(material.encode('utf-8')).hexdigest()}.json" + + +def _read_strict(path: Path) -> tuple[bool, Any]: + """Return ``(exists, payload)``; raise when the file is present but corrupt.""" + if not path.is_file(): + return False, None + payload = read_json(path, _MISSING) + if payload is _MISSING: + raise BaselineCorruptionError(f"unreadable baseline state: {path}") + return True, payload + + +class BaselineStore: + """File-backed store for baseline records and per-scope default selectors.""" + + def __init__(self, home: Path) -> None: + self.home = Path(home) + + @property + def records_dir(self) -> Path: + return self.home / "baselines" / "records" + + @property + def defaults_dir(self) -> Path: + return self.home / "baselines" / "defaults" + + def _record_path(self, baseline_id: str) -> Path: + return self.records_dir / f"{baseline_id}.json" + + def _default_path(self, cwd: str | os.PathLike[str], agent: str) -> Path: + return self.defaults_dir / _scope_filename(cwd, agent) + + def _load_record(self, path: Path) -> Baseline: + exists, payload = _read_strict(path) + if not exists: + raise KeyError(path.stem) + try: + return Baseline.model_validate(payload) + except ValidationError as exc: + raise BaselineCorruptionError(f"invalid baseline record {path}: {exc}") from exc + + @staticmethod + def _validate_record(record: Baseline) -> None: + if not record.name.strip(): + raise ValueError("baseline name must not be empty") + if not record.native_session_id.strip(): + raise ValueError("baseline native_session_id must not be empty") + if not record.source_session_id.strip(): + raise ValueError("baseline source_session_id must not be empty") + _scope_identity(record.cwd, record.agent) + + def add(self, record: Baseline) -> None: + """Persist a new immutable record; refuse to overwrite an existing ID.""" + baseline_id = _validate_id(record.baseline_id) + self._validate_record(record) + path = self._record_path(baseline_id) + if path.exists(): + raise FileExistsError(f"baseline {baseline_id} already exists") + atomic_write_json(path, record.model_dump(mode="json")) + + def get(self, baseline_id: str) -> Baseline: + """Return one record; a missing ID raises :class:`KeyError`.""" + validated = _validate_id(baseline_id) + path = self._record_path(validated) + if not path.is_file(): + raise KeyError(baseline_id) + return self._load_record(path) + + def list(self, cwd: str | os.PathLike[str], agent: str) -> list[Baseline]: + """Return every record for this canonical project+agent scope, oldest first.""" + scope = _scope_identity(cwd, agent) + records: list[Baseline] = [] + if self.records_dir.is_dir(): + for path in sorted(self.records_dir.glob("*.json")): + record = self._load_record(path) + if _scope_identity(record.cwd, record.agent) == scope: + records.append(record) + records.sort(key=lambda item: (item.created_at, item.baseline_id)) + return records + + def get_default(self, cwd: str | os.PathLike[str], agent: str) -> str | None: + """Return the saved default baseline id for a scope, or ``None``.""" + path = self._default_path(cwd, agent) + exists, payload = _read_strict(path) + if not exists: + return None + if not isinstance(payload, dict): + raise BaselineCorruptionError(f"invalid baseline default {path}") + baseline_id = payload.get("baseline_id") + if baseline_id is None: + return None + try: + return _validate_id(baseline_id) + except ValueError as exc: + raise BaselineCorruptionError(f"invalid baseline default {path}") from exc + + def set_default(self, cwd: str | os.PathLike[str], agent: str, baseline_id: str | None) -> None: + """Set or clear the default for one scope without touching any record.""" + path = self._default_path(cwd, agent) + if baseline_id is None: + atomic_write_json(path, {"baseline_id": None}) + return + validated = _validate_id(baseline_id) + record = self.get(validated) + if _scope_identity(record.cwd, record.agent) != _scope_identity(cwd, agent): + raise ValueError("baseline belongs to a different project or worker") + atomic_write_json(path, {"baseline_id": validated}) diff --git a/src/agent_bridge/cli.py b/src/agent_bridge/cli.py index f4e58b6..97481da 100644 --- a/src/agent_bridge/cli.py +++ b/src/agent_bridge/cli.py @@ -247,6 +247,8 @@ def hub_command(args: list[str]) -> None: parser.add_argument('--repo', default=argparse.SUPPRESS, help='cloud repository URL') parser.add_argument('--ref', default=argparse.SUPPRESS, help='cloud repository starting ref') parser.add_argument('--session-id', default=argparse.SUPPRESS, help='continue a Bridge session') + parser.add_argument('--baseline', default=argparse.SUPPRESS, help='DSH baseline ID, default or empty') + parser.add_argument('--fork-label', default=argparse.SUPPRESS, help='name a DSH fork') options = parser.parse_args(args[1:]) tool, values = 'invoke', vars(options) if values.pop('callback_secret', False): @@ -335,6 +337,11 @@ def main(argv: Sequence[str] | None = None) -> None: return command = args[0] + if command == '_dsh-ipc' and sys.platform == 'win32' and len(args) == 2: + from agent_bridge.desktop_pipe import relay_stdio + + relay_stdio(Path(args[1])) + return if command == 'ui': import asyncio import webbrowser diff --git a/src/agent_bridge/desktop_ipc.py b/src/agent_bridge/desktop_ipc.py new file mode 100644 index 0000000..99aa846 --- /dev/null +++ b/src/agent_bridge/desktop_ipc.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import asyncio +import contextlib +import json +import logging +import os +import stat +import uuid +from collections.abc import AsyncIterator +from pathlib import Path +from typing import Any + +log = logging.getLogger(__name__) +FRAME_LIMIT = 16 * 1024 * 1024 + + +class DesktopUnavailable(RuntimeError): + pass + + +class DesktopIPC: + def __init__(self) -> None: + self._peer: asyncio.StreamWriter | None = None + self._pending: dict[str, asyncio.Queue[dict[str, Any] | None]] = {} + + @property + def connected(self) -> bool: + return self._peer is not None and not self._peer.is_closing() + + async def attach(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + owns_peer = False + try: + hello = json.loads(await asyncio.wait_for(reader.readline(), 3)) + if self._peer is not None or hello != {"dsh_ipc": 1}: + return + self._peer = writer + owns_peer = True + while line := await reader.readline(): + frame = json.loads(line) + if not isinstance(frame, dict) or not isinstance(frame.get("id"), str): + break + if queue := self._pending.get(frame["id"]): + queue.put_nowait(frame) + except (OSError, ValueError, TimeoutError): + pass + finally: + writer.close() + if owns_peer: + self._peer = None + for queue in self._pending.values(): + queue.put_nowait(None) + with contextlib.suppress(OSError): + await writer.wait_closed() + + @contextlib.asynccontextmanager + async def request(self, operation: str, args: dict[str, Any]) -> AsyncIterator[AsyncIterator[dict[str, Any]]]: + peer = self._peer + if peer is None or peer.is_closing(): + raise DesktopUnavailable("DeepSeek Harness Desktop connector is unavailable") + request_id = uuid.uuid4().hex + queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue() + self._pending[request_id] = queue + + async def read() -> AsyncIterator[dict[str, Any]]: + while True: + frame = await queue.get() + if frame is None: + raise RuntimeError("DeepSeek Harness Desktop disconnected after the request was sent") + if frame.get("type") == "error": + raise RuntimeError(f"DeepSeek Harness Desktop rejected {operation}") + if frame.get("type") == "end": + return + value = frame.get("value") + if frame.get("type") != "value" or not isinstance(value, dict): + raise DesktopUnavailable("DeepSeek Harness Desktop sent an invalid IPC frame") + yield value + + try: + payload = json.dumps({"id": request_id, "operation": operation, "args": args}).encode() + if len(payload) >= FRAME_LIMIT: + raise ValueError("Desktop IPC request exceeds the frame limit") + peer.write(payload + b"\n") + await peer.drain() + yield read() + except OSError: + raise RuntimeError("DeepSeek Harness Desktop request delivery could not be confirmed") from None + finally: + self._pending.pop(request_id) + if not peer.is_closing(): + with contextlib.suppress(OSError): + peer.write(json.dumps({"id": request_id, "operation": "close"}).encode() + b"\n") + + async def call(self, operation: str, args: dict[str, Any]) -> dict[str, Any]: + async with asyncio.timeout(10), self.request(operation, args) as frames: + value = await anext(frames, None) + if value is None: + raise RuntimeError("DeepSeek Harness Desktop returned no response") + return value + + +@contextlib.asynccontextmanager +async def serve_desktop(home: Path, ipc: DesktopIPC) -> AsyncIterator[None]: + async with contextlib.AsyncExitStack() as stack: + try: + if os.name == "nt": + from agent_bridge.desktop_pipe import serve_pipe + + await stack.enter_async_context(serve_pipe(home, ipc)) + else: + await stack.enter_async_context(_serve_socket(home, ipc)) + except OSError as exc: + log.warning("DSH Desktop IPC unavailable (%s); ordinary new DSH tasks can use ACP", type(exc).__name__) + try: + yield + finally: + if ipc._peer is not None: + ipc._peer.close() + + +@contextlib.asynccontextmanager +async def _serve_socket(home: Path, ipc: DesktopIPC) -> AsyncIterator[None]: + import fcntl + + directory = home / "dsh-ipc" + directory.mkdir(mode=0o700, exist_ok=True) + info = directory.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o700: + raise PermissionError("DSH IPC directory must be owned by the current user with mode 0700") + info = home.stat() + if info.st_uid != os.getuid() or info.st_mode & 0o022: + raise PermissionError("Bridge home must not be writable by other users") + lock = os.open(directory / "lock", os.O_CREAT | os.O_NOFOLLOW | os.O_RDWR, 0o600) + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + endpoint = directory / "desktop.sock" + if endpoint.is_socket() and not endpoint.is_symlink(): + endpoint.unlink() + server = await asyncio.start_unix_server(ipc.attach, endpoint, limit=FRAME_LIMIT, start_serving=False) + try: + endpoint.chmod(0o600) + await server.start_serving() + yield + finally: + server.close() + await server.wait_closed() + endpoint.unlink(missing_ok=True) + finally: + os.close(lock) diff --git a/src/agent_bridge/desktop_pipe.py b/src/agent_bridge/desktop_pipe.py new file mode 100644 index 0000000..0e923bc --- /dev/null +++ b/src/agent_bridge/desktop_pipe.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +import asyncio +import contextlib +import hashlib +import importlib +import msvcrt +import os +import sys +import threading +from collections.abc import AsyncIterator +from pathlib import Path +from typing import Any, cast + +import pywintypes +import win32api +import win32con +import win32event +import win32file +import win32pipe +import win32security + +from agent_bridge.desktop_ipc import FRAME_LIMIT, DesktopIPC + +PIPE_REJECT_REMOTE_CLIENTS = 0x8 +FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000 +SECURITY_IDENTIFICATION = 0x00010000 +SECURITY_SQOS_PRESENT = 0x00100000 +BUFFER_SIZE = 65536 + + +def _user_sid() -> Any: + token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY) + try: + return win32security.GetTokenInformation(token, win32security.TokenUser)[0] + finally: + token.Close() + + +def _address(home: Path, sid: Any) -> str: + material = os.path.normcase(str(home.resolve())) + ":" + win32security.ConvertSidToStringSid(sid) + return "\\\\.\\pipe\\agent-bridge-dsh-" + hashlib.sha256(material.encode()).hexdigest() + + +def _private_pipe(address: str, sid: Any) -> Any: + acl = win32security.ACL() + acl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, sid) + security = pywintypes.SECURITY_ATTRIBUTES() + security.SECURITY_DESCRIPTOR.SetSecurityDescriptorDacl(True, acl, False) + security.SECURITY_DESCRIPTOR.SetSecurityDescriptorOwner(sid, False) + try: + return win32pipe.CreateNamedPipe( + address, win32pipe.PIPE_ACCESS_DUPLEX | win32con.FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_REJECT_REMOTE_CLIENTS, 1, BUFFER_SIZE, BUFFER_SIZE, 0, security, + ) + except pywintypes.error as exc: + raise OSError("Could not create a current-user Desktop named pipe") from exc + + +@contextlib.asynccontextmanager +async def serve_pipe(home: Path, ipc: DesktopIPC) -> AsyncIterator[None]: + if sys.platform != "win32": + raise OSError("Desktop named pipes are only available on Windows") + pipe_handle = importlib.import_module("asyncio.windows_utils").PipeHandle + + loop = cast(Any, asyncio.get_running_loop()) + if not hasattr(loop, "_proactor"): + raise OSError("Desktop named pipe requires the Windows Proactor event loop") + sid = _user_sid() + address = _address(home, sid) + first = _private_pipe(address, sid) + + async def accept() -> None: + raw = first + while True: + pipe = pipe_handle(raw.Detach()) + transport = None + try: + await loop._proactor.accept_pipe(pipe) + reader = asyncio.StreamReader(limit=FRAME_LIMIT) + protocol = asyncio.StreamReaderProtocol(reader) + transport = loop._make_duplex_pipe_transport(pipe, protocol) + writer = asyncio.StreamWriter(transport, protocol, reader, loop) + await ipc.attach(reader, writer) + finally: + if transport is not None: + transport.close() + else: + pipe.close() + raw = _private_pipe(address, sid) + + task = asyncio.create_task(accept()) + try: + yield + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + first.Close() + + +def relay_stdio(home: Path) -> None: + sid = _user_sid() + try: + handle = win32file.CreateFile( + _address(home, sid), win32con.GENERIC_READ | win32con.GENERIC_WRITE | win32con.READ_CONTROL, + 0, None, win32con.OPEN_EXISTING, + win32con.FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, None, + ) + except pywintypes.error: + return + try: + descriptor = win32security.GetSecurityInfo( + handle, win32security.SE_KERNEL_OBJECT, win32security.OWNER_SECURITY_INFORMATION, + ) + if descriptor.GetSecurityDescriptorOwner() != sid: + return + stdin = sys.stdin.fileno() + if sys.platform == "win32": + msvcrt.setmode(stdin, os.O_BINARY) + + def upstream() -> None: + write = pywintypes.OVERLAPPED() + write.hEvent = win32event.CreateEvent(None, True, False, None) + with contextlib.suppress(OSError, pywintypes.error): + while chunk := os.read(stdin, BUFFER_SIZE): + win32file.WriteFile(handle, chunk, write) + win32file.GetOverlappedResult(handle, write, True) + os._exit(0) + + read = pywintypes.OVERLAPPED() + read.hEvent = win32event.CreateEvent(None, True, False, None) + buffer = win32file.AllocateReadBuffer(BUFFER_SIZE) + threading.Thread(target=upstream, daemon=True).start() + with contextlib.suppress(OSError, pywintypes.error): + while True: + win32file.ReadFile(handle, buffer, read) + count = win32file.GetOverlappedResult(handle, read, True) + if not count: + break + sys.stdout.buffer.write(buffer[:count]) + sys.stdout.buffer.flush() + finally: + handle.Close() diff --git a/src/agent_bridge/hub.py b/src/agent_bridge/hub.py index 67ce6d6..762db8f 100644 --- a/src/agent_bridge/hub.py +++ b/src/agent_bridge/hub.py @@ -22,6 +22,7 @@ from agent_bridge.api import BridgeService, _error, wait_for_result from agent_bridge.dashboard import Dashboard, DashboardHeaders +from agent_bridge.desktop_ipc import serve_desktop from agent_bridge.hub_client import ROUTES from agent_bridge.paths import ensure_home from agent_bridge.persist import file_lock, read_json @@ -84,7 +85,8 @@ async def lifespan(app: Starlette): temporary = file.name json.dump(record, file) os.replace(temporary, path) - yield + async with serve_desktop(registry.home, registry.desktop): + yield finally: try: if read_json(path, {}) == record: diff --git a/src/agent_bridge/hub_client.py b/src/agent_bridge/hub_client.py index 5301294..399832d 100644 --- a/src/agent_bridge/hub_client.py +++ b/src/agent_bridge/hub_client.py @@ -26,6 +26,9 @@ 'list_agents': ('GET', '/v1/agents', None), 'set_preferences': ('PUT', '/v1/preferences', None), 'dispatch_task': ('POST', '/v1/tasks', None), + 'create_baseline': ('POST', '/v1/baselines', None), + 'list_baselines': ('GET', '/v1/baselines', None), + 'set_default_baseline': ('PUT', '/v1/baselines/default', None), 'check_task': ('GET', '/v1/tasks/{task_id}', 'task_id'), 'wait_task': ('GET', '/v1/tasks/{task_id}/wait', 'task_id'), 'get_result': ('GET', '/v1/tasks/{task_id}/result', 'task_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', 'create_baseline'} 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..2793466 100644 --- a/src/agent_bridge/models.py +++ b/src/agent_bridge/models.py @@ -108,11 +108,16 @@ class Session(BaseModel): notification_receipts: dict[str, str] = Field(default_factory=dict) session_id: str agent: str + backend: str | None = None cwd: str repo: str | None = None ref: str | None = None remote: dict[str, Any] = Field(default_factory=dict) native_session_id: str | None = None + fork_source_id: str | None = None + baseline_id: str | None = None + is_baseline: bool = False + fork_label: str | None = None proc_state: ProcState = ProcState.idle_unloaded model: Selection | None = None effort: EffortSelection | None = None @@ -152,6 +157,9 @@ class Task(BaseModel): repo: str | None = None ref: str | None = None remote: dict[str, Any] = Field(default_factory=dict) + baseline_id: str | None = None + fork_label: str | None = None + backend: str | None = None model: Selection | None = None effort: EffortSelection | None = None observed_model: str | None = None diff --git a/src/agent_bridge/registry.py b/src/agent_bridge/registry.py index 36cea8c..a531794 100644 --- a/src/agent_bridge/registry.py +++ b/src/agent_bridge/registry.py @@ -18,6 +18,7 @@ from agent_bridge.adapters.acp import AcpAdapter, AcpError from agent_bridge.adapters.base import Adapter from agent_bridge.adapters.cloud import CloudAdapter +from agent_bridge.baselines import Baseline, BaselineCorruptionError, BaselineStore from agent_bridge.config import ( COORDINATOR_MODE_HINTS, AgentConfig, @@ -27,6 +28,7 @@ write_coordinator_overlay, ) from agent_bridge.delivery import Deliveries, pending, validate_callback +from agent_bridge.desktop_ipc import DesktopIPC, DesktopUnavailable from agent_bridge.diagnostics import redact_diagnostic from agent_bridge.grok_observe import observe_grok_session from agent_bridge.kimi_observe import observe_kimi_session @@ -172,6 +174,8 @@ def __init__( ) -> None: self.home = home self.config = config + self.baselines = BaselineStore(home) + self.desktop = DesktopIPC() self.sessions: dict[str, Session] = {} self.tasks: dict[str, Task] = {} # request_id -> (request fingerprint, task_id). Fingerprints instead @@ -605,7 +609,8 @@ def _adapter_for(self, session: Session) -> Adapter: existing = self._adapters.get(session.session_id) if existing is not None: return existing - adapter = build_adapter(self.config.get(session.agent), self.home, self.config.env) + adapter = build_adapter(self.config.get(session.agent), self.home, self.config.env, + backend=session.backend, desktop=self.desktop) if self.worker_url is not None: adapter.worker_tokens = self.worker_tokens if isinstance(adapter, CloudAdapter): @@ -622,6 +627,11 @@ def _busy_task(self, session_id: str) -> Task | None: async def list_agents(self) -> list[dict]: async def describe(cfg: AgentConfig) -> dict: row = await probe_agent(cfg, self.config.env) + if cfg.name == "dsh" and cfg.protocol == "acp": + connected = self.desktop.connected + row["desktop"] = {"connected": connected, "fork_available": connected, + "new_task_backend": "desktop" if connected else "acp"} + row["available"] = bool(row.get("available")) or connected row["quota"] = await self._quota_for(cfg, available=bool(row.get("available"))) return row @@ -718,6 +728,116 @@ def set_preferences( ) return {"coordinator": self.coordinator_status(), "path": str(path), "notes": notes} + def _baseline_scope(self, cwd: str, agent: str) -> str: + self.config.get(agent) + path = Path(cwd) + if not path.is_absolute() or not path.is_dir(): + raise ValueError("cwd must be an existing absolute project directory") + return str(path.resolve()) + + def _resolve_baseline(self, cwd: str, agent: str, selection: str | None) -> Baseline | None: + if selection == "empty": + return None + baseline_id = self.baselines.get_default(cwd, agent) if selection in (None, "default") else selection + if baseline_id is None: + return None + record = self.baselines.get(baseline_id) + if record.agent != agent or Path(record.cwd).resolve() != Path(cwd).resolve(): + raise ValueError("baseline belongs to a different project or worker") + if agent != "dsh": + raise ValueError("baseline forks are currently supported only for dsh") + return record + + def list_baselines(self, cwd: str, agent: str = "dsh") -> dict: + cwd = self._baseline_scope(cwd, agent) + return { + "cwd": cwd, "agent": agent, + "default_baseline_id": self.baselines.get_default(cwd, agent), + "baselines": [record.model_dump(mode="json") for record in self.baselines.list(cwd, agent)], + } + + def _baseline_name(self, baseline_id: str | None) -> str | None: + if baseline_id: + with contextlib.suppress(KeyError, BaselineCorruptionError): + return self.baselines.get(baseline_id).name + return None + + async def set_default_baseline(self, cwd: str, agent: str, baseline_id: str | None) -> dict: + if not self.dispatch_enabled: + raise RuntimeError(NESTED_PREFERENCES_ERROR) + cwd = self._baseline_scope(cwd, agent) + async with self._lock: + if baseline_id is not None: + self._resolve_baseline(cwd, agent, baseline_id) + self.baselines.set_default(cwd, agent, baseline_id) + return {"cwd": cwd, "agent": agent, "default_baseline_id": baseline_id} + + async def create_baseline( + self, session_id: str, name: str, description: str | None = None, *, user_requested: bool = False, + ) -> dict: + if not self.dispatch_enabled: + raise RuntimeError(NESTED_DISPATCH_ERROR) + if self.config.coordinator.mode == "manual" and not user_requested: + raise RuntimeError("coordinator mode is manual: baseline creation requires user_requested=true") + if not name.strip(): + raise ValueError("baseline name must not be empty") + async with self._lock: + source = self.sessions.get(session_id) + if source is None: + raise KeyError(f"unknown session {session_id}") + if source.agent != "dsh": + raise ValueError("baseline forks are currently supported only for dsh") + if source.backend != "desktop": + raise ValueError("Desktop connection is required to create a DSH baseline") + if self._busy_task(session_id) is not None: + raise RuntimeError("source session is busy; wait_task before creating a baseline") + if not source.native_session_id or source.turns == 0: + raise ValueError("baseline source must have a completed turn") + source_tasks = [task for task in self.tasks.values() if task.session_id == session_id] + latest = max(source_tasks, key=lambda task: task.created_at, default=None) + if latest is None or latest.status != TaskStatus.completed: + raise ValueError("baseline source must end with a successfully completed task") + baseline_id = _new_id("base") + child = Session( + session_id=_new_id("sess"), agent=source.agent, cwd=source.cwd, + backend=source.backend, + fork_source_id=source.native_session_id, baseline_id=baseline_id, + is_baseline=True, model=source.model or latest.observed_model, + effort=source.effort or latest.observed_effort, + title=name.strip(), proc_state=ProcState.spawning, + ) + self._stamp_owner(child) + adapter = self._adapter_for(child) + saved = False + try: + if not adapter.can_fork(): + raise ValueError("configured worker does not support baseline forks") + self.sessions[child.session_id] = child + await adapter.ensure_session(child) + if not child.native_session_id: + raise RuntimeError("fork returned no native session id") + await adapter.shutdown(child) + record = Baseline( + baseline_id=baseline_id, name=name.strip(), description=description, + agent=child.agent, backend=child.backend, cwd=child.cwd, + native_session_id=child.native_session_id, + source_session_id=source.session_id, model=child.model, effort=child.effort, + ) + self.baselines.add(record) + saved = True + child.proc_state = ProcState.idle_unloaded + child.pid = None + return {"baseline": record.model_dump(mode="json"), "session_id": child.session_id} + finally: + self._adapters.pop(child.session_id, None) + if not saved: + try: + await adapter.shutdown(child) + finally: + self.sessions.pop(child.session_id, None) + self.save() + await self.flush_state() + async def dispatch_task( self, agent: str, @@ -736,6 +856,8 @@ async def dispatch_task( callback_url: str | None = None, callback_secret_name: str | None = None, notification_source_task_id: str | None = None, + baseline: str | None = None, + fork_label: str | None = None, remote_origin: bool = False, ) -> dict: if not self.dispatch_enabled: @@ -786,13 +908,30 @@ async def dispatch_task( resolved_cwd = '' if cloud else str(cwd_path.resolve()) if not cloud and (repo is not None or ref is not None): raise ValueError('repo and ref are only supported by cloud agents') + desktop_worker = agent == "dsh" and agent_cfg.protocol == "acp" + scoped_worker = caller_session_id is not None and caller_session_context.get() == caller_session_id + restricted_caller = remote_origin or scoped_worker + if restricted_caller and (baseline not in (None, "empty") or fork_label is not None): + raise ValueError("baseline forks are not available to restricted callers") + if not desktop_worker and (baseline is not None or fork_label is not None): + raise ValueError("baseline forks are currently supported only for dsh") + if session_id and baseline not in (None, "default"): + raise ValueError("baseline cannot be selected when continuing session_id") + if session_id and fork_label is not None: + raise ValueError("fork_label can only be supplied when creating a new session") + if fork_label is not None and not fork_label.strip(): + raise ValueError("fork_label must not be empty") # Compare supplied arguments, not selections inherited from a mutable session. 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 request += (notify_caller, caller_session_id, callback_url, callback_secret_name) + if baseline is not None or fork_label is not None: + request += (baseline, fork_label) + legacy_request = None async with self._lock: + desktop_connected = desktop_worker and self.desktop.connected if request_id is not None and request_id in self._requests: previous_fp, task_id = self._requests[request_id] if previous_fp != _request_fingerprint(request) and ( @@ -804,8 +943,11 @@ async def dispatch_task( "task_id": task.task_id, "session_id": task.session_id, "agent": task.agent, + "backend": task.backend, "model": task.model, "effort": task.effort, + "baseline_id": task.baseline_id, + "fork_label": task.fork_label, "request_id": request_id, "reused": True, "persisted": await self.flush_state(), @@ -814,8 +956,10 @@ async def dispatch_task( session = self.sessions.get(session_id) if session is None: raise KeyError(f"unknown session {session_id}") - if caller_session_id and caller_session_context.get() == caller_session_id and session.caller_session_id != caller_session_id: + if scoped_worker and session.caller_session_id != caller_session_id: raise ValueError('session is not owned by caller') + if session.is_baseline: + raise ValueError("a saved baseline is immutable; dispatch a new session from its baseline_id") if session.agent != agent: raise ValueError(f"session {session_id} belongs to agent {session.agent}, not {agent}") if cloud and repo is not None and repo != session.repo: @@ -837,16 +981,32 @@ async def dispatch_task( if session.caller_session_id != caller_session_id: session.caller_session_id = None else: + selected = self._resolve_baseline(resolved_cwd, agent, baseline) if desktop_worker and not restricted_caller else None + if fork_label is not None and selected is None: + raise ValueError("fork_label requires a selected baseline") + if selected is not None: + if selected.backend != "desktop": + raise ValueError("This baseline was created via ACP; create a new Desktop baseline") + if not desktop_connected: + raise ValueError("DeepSeek Harness Desktop is disconnected; fork is unavailable") + if model is not None and model != selected.model: + raise ValueError("baseline tasks must use the baseline model") + if effort is not None and effort != selected.effort: + raise ValueError("baseline tasks must use the baseline effort") session = Session( caller_session_id=caller_session_id, call_depth=depth, session_id=_new_id("sess"), agent=agent, + backend=selected.backend if selected else ("desktop" if desktop_connected else None), cwd=resolved_cwd, repo=repo if repo is not None else (agent_cfg.cloud.repo if agent_cfg.cloud else None), ref=ref if ref is not None else (agent_cfg.cloud.ref if agent_cfg.cloud else None), - model=None if cloud else model, - effort=None if cloud else effort, + model=selected.model if selected else (None if cloud else model), + effort=selected.effort if selected else (None if cloud else effort), + fork_source_id=selected.native_session_id if selected else None, + baseline_id=selected.baseline_id if selected else None, + fork_label=(fork_label.strip() if fork_label else title or f"{selected.name} · {message[:48]}") if selected else None, title=title, proc_state=ProcState.spawning, ) @@ -875,6 +1035,9 @@ async def dispatch_task( ref=session.ref, remote={key: value for key, value in session.remote.items() if key in {'provider', 'url', 'agent_id', 'session_id', 'devin_mode', 'resumable'}}, + baseline_id=session.baseline_id, + backend=(session.backend or agent_cfg.protocol) if agent == "dsh" else None, + fork_label=session.fork_label, model=model or session.model, effort=effort or session.effort, status=TaskStatus.queued, @@ -919,9 +1082,12 @@ async def dispatch_task( "task_id": task.task_id, "session_id": session.session_id, "agent": agent, + "backend": task.backend, "model": task.model, "effort": task.effort, "persisted": persisted, + "baseline_id": session.baseline_id, + "fork_label": session.fork_label, **({"request_id": request_id, "reused": False} if request_id is not None else {}), } @@ -965,7 +1131,20 @@ async def _run_task(self, task_id: str) -> None: if isinstance(adapter, CloudAdapter) and self.config.hub.remote.enabled: _, instructions = self.remote.issue(task) turn_task = task.model_copy(update={'message': task.message + instructions}) - result = await adapter.run_turn(session, turn_task) + try: + result = await adapter.run_turn(session, turn_task) + except DesktopUnavailable: + if session.backend != "desktop" or session.native_session_id or session.fork_source_id: + raise + # Host disappeared after dispatch probing but before creating a + # native Session. This task has no Desktop state to preserve. + await adapter.shutdown(session) + self._adapters.pop(session.session_id, None) + session.backend = None + task.backend = "acp" + adapter = self._adapter_for(session) + result = await adapter.run_turn(session, task) + result.warnings.append("Desktop Host disconnected before session creation; used ACP") task.remote.update(result.remote) if result.native_session_id: session.native_session_id = result.native_session_id @@ -1089,6 +1268,12 @@ async def _run_task(self, task_id: str) -> None: session.last_active_at = iso() if session.proc_state != ProcState.dead: session.proc_state = ProcState.ready if adapter.resident else ProcState.idle_unloaded + if session.backend == "desktop": + try: + await adapter.shutdown(session) + except Exception: + log.exception("could not close Desktop connection for %s", session.session_id) + self._adapters.pop(session.session_id, None) try: flush_session(session.session_id, self.home) except OSError: @@ -1452,6 +1637,7 @@ def _task_snapshot(self, task: Task, include_result: bool = False) -> dict: "task_id": task.task_id, "session_id": task.session_id, "agent": task.agent, + "backend": task.backend, "status": task.status.value, "stop_reason": task.stop_reason, "error": task.error, @@ -1473,6 +1659,9 @@ def _task_snapshot(self, task: Task, include_result: bool = False) -> dict: "effort": task.effort, "observed_model": task.observed_model, "observed_effort": task.observed_effort, + "baseline_id": task.baseline_id, + "baseline_name": self._baseline_name(task.baseline_id), + "fork_label": task.fork_label, "created_at": task.created_at, "started_at": task.started_at, "finished_at": task.finished_at, @@ -1648,11 +1837,17 @@ def list_sessions(self, active_only: bool = False) -> list[dict]: { "session_id": session.session_id, "agent": session.agent, + "backend": (session.backend or "acp") if session.agent == "dsh" else None, "cwd": session.cwd, "repo": session.repo, "ref": session.ref, "remote": session.remote, "native_session_id": session.native_session_id, + "baseline_id": session.baseline_id, + "fork_source_id": session.fork_source_id, + "fork_label": session.fork_label, + "baseline_name": self._baseline_name(session.baseline_id), + "is_baseline": session.is_baseline, "proc_state": session.proc_state.value, "turns": session.turns, "title": session.title, @@ -1681,7 +1876,8 @@ async def end_session(self, session_id: str) -> dict: await self.cancel_task(busy.task_id) adapter = self._adapters.pop(session_id, None) if adapter is None and self.config.get(session.agent).protocol == 'cloud': - adapter = build_adapter(self.config.get(session.agent), self.home, self.config.env) + adapter = build_adapter(self.config.get(session.agent), self.home, self.config.env, + backend=session.backend, desktop=self.desktop) if adapter is not None: if isinstance(adapter, CloudAdapter): await adapter.end_session(session) diff --git a/src/agent_bridge/server.py b/src/agent_bridge/server.py index 8b0ea07..9e99d51 100644 --- a/src/agent_bridge/server.py +++ b/src/agent_bridge/server.py @@ -78,7 +78,10 @@ async def lifespan(_server: MCPServer[Registry | HubClient]) -> AsyncIterator[Re "process — do not call dispatch_task, set_preferences, cancel_task, " "or end_session. When " "dispatch_enabled is true and the user states a lasting preference, " - "persist it with set_preferences." + "persist it with set_preferences. New DSH sessions automatically use the saved project baseline. " + "Use create_baseline, list_baselines and set_default_baseline to manage immutable versions. " + "dispatch_task baseline=empty starts blank once; baseline= overrides once; omitted follows default. " + "Clearing the default retains saved versions. fork_label names a new branch; list_sessions and results identify its saved baseline. Existing session_id continuation keeps its history." ) mcp = MCPServer[Registry | HubClient]("agent-bridge", instructions=INSTRUCTIONS, lifespan=lifespan) @@ -133,11 +136,37 @@ async def dispatch_task( callback_url: str | None = None, callback_secret_name: str | None = None, callback_secret: str | None = None, + baseline: str | None = None, + fork_label: str | None = None, ) -> dict[str, Any]: - """Start a worker turn. Local workers require an absolute existing cwd. Cloud workers ignore cwd and accept optional repo/ref overrides; follow-ups keep their repository/ref. Cloud Cursor model is a model ID; Devin model is a mode, or effort maps off/low/medium/high/max to fast/lite/normal/ultra/ultra. Remote results carry provider IDs, URLs and PRs rather than local file changes. Cancelling Devin terminates the remote session permanently. Local model/effort behavior is unchanged. Pass session_id to continue. Set user_requested=true only when the user explicitly asked for a worker (required in manual mode). Rejected when coordinator.dispatch_enabled is false. For retry deduplication, supply a UUID request_id on the first call and replay the same ID and original arguments; identical retries reuse the task, different arguments are rejected. Bindings are lost on restart and are not shared with other instances. Returns immediately.""" + """Start a worker turn. Local workers require an absolute existing cwd. Cloud workers ignore cwd and accept optional repo/ref overrides; follow-ups keep their repository/ref. Cloud Cursor model is a model ID; Devin model is a mode, or effort maps off/low/medium/high/max to fast/lite/normal/ultra/ultra. Remote results carry provider IDs, URLs and PRs rather than local file changes. Cancelling Devin terminates the remote session permanently. Local model/effort behavior is unchanged. Pass session_id to continue. Set user_requested=true only when the user explicitly asked for a worker (required in manual mode). Rejected when coordinator.dispatch_enabled is false. For retry deduplication, supply a UUID request_id on the first call and replay the same ID and original arguments; identical retries reuse the task, different arguments are rejected. Bindings are lost on restart and are not shared with other instances. DSH Desktop supports baseline IDs, default or empty for new sessions; fork_label names the child. Returns immediately.""" if callback_secret is not None: return _error(ValueError('raw callback_secret is not accepted; use callback_secret_name from the keyring')) - return await _service(ctx).dispatch_task(agent=agent, message=message, cwd=cwd, session_id=session_id, model=model, effort=effort, title=title, user_requested=user_requested, request_id=request_id, repo=repo, ref=ref, notify_caller=notify_caller, callback_url=callback_url, callback_secret_name=callback_secret_name) + return await _service(ctx).dispatch_task(agent=agent, message=message, cwd=cwd, session_id=session_id, model=model, effort=effort, title=title, user_requested=user_requested, request_id=request_id, repo=repo, ref=ref, notify_caller=notify_caller, callback_url=callback_url, callback_secret_name=callback_secret_name, baseline=baseline, fork_label=fork_label) + + +@mcp.tool() +async def create_baseline( + ctx: Context, session_id: str, name: str, description: str | None = None, + user_requested: bool = False, +) -> dict[str, Any]: + """Save an immutable DSH baseline from an idle completed Desktop session. Does not change the default. Requires a reachable Desktop Host. user_requested follows coordinator manual-mode rules.""" + return await _service(ctx).create_baseline(session_id=session_id, name=name, description=description, + user_requested=user_requested) + + +@mcp.tool(annotations=READ_ONLY) +async def list_baselines(ctx: Context, cwd: str, agent: str = "dsh") -> dict[str, Any]: + """List saved baseline versions and the persistent default for this project and worker.""" + return await _service(ctx).list_baselines(cwd=cwd, agent=agent) + + +@mcp.tool() +async def set_default_baseline( + ctx: Context, cwd: str, baseline_id: str | None, agent: str = "dsh", +) -> dict[str, Any]: + """Select a persistent default for new sessions. null clears the default without deleting saved versions. Existing sessions and accepted tasks keep their history.""" + return await _service(ctx).set_default_baseline(cwd=cwd, agent=agent, baseline_id=baseline_id) @mcp.tool(annotations=READ_ONLY) @@ -152,13 +181,15 @@ async def invoke_agent( session_id: str | None = None, model: str | None = None, effort: str | None = None, repo: str | None = None, ref: str | None = None, user_requested: bool = False, timeout_sec: float | None = None, + baseline: str | None = None, fork_label: str | None = None, ) -> dict[str, Any]: """Call a worker and wait for its terminal result, with periodic MCP progress. No default wait cap. Some clients impose absolute tool deadlines: use dispatch_task with async notification instead. A timeout returns the running task ID; it does not cancel work.""" if timeout_sec is not None and timeout_sec < 0: return _error(ValueError('timeout_sec must be non-negative')) service = _service(ctx) result = await service.dispatch_task(agent=agent, message=message, cwd=cwd, - session_id=session_id, model=model, effort=effort, repo=repo, ref=ref, user_requested=user_requested) + session_id=session_id, model=model, effort=effort, repo=repo, ref=ref, user_requested=user_requested, + baseline=baseline, fork_label=fork_label) if not result['ok']: return result diff --git a/tests/dsh_desktop_fixture.mjs b/tests/dsh_desktop_fixture.mjs new file mode 100644 index 0000000..707cb64 --- /dev/null +++ b/tests/dsh_desktop_fixture.mjs @@ -0,0 +1,57 @@ +import { EventEmitter, on } from 'node:events' + +import { apply } from '../dsh-desktop-connector/index.js' + +const histories = new Map() +const streams = new Map() +let nextId = 0 +function create(history) { + const sessionId = String(++nextId) + histories.set(sessionId, [...history]) + streams.set(sessionId, new EventEmitter()) + return { sessionId } +} + +const controller = { + create: () => create([]), + fork: ({ sessionId }) => create(histories.get(sessionId)), + rename: () => ({}), + async *follow({ address }, signal) { + const events = on(streams.get(address.sessionId), 'frame', { signal }) + try { + yield { type: 'snapshot', records: ['r'.repeat(17 * 1024 * 1024)] } + for await (const [event] of events) yield { type: 'event', event } + } finally { + await events.return() + } + }, + prompt({ sessionId, requestId, content }) { + const history = histories.get(sessionId) + const stream = streams.get(sessionId) + history.push(content[0].text) + const turn = history.length + stream.emit('frame', { type: 'turn/start', data: { turn } }) + stream.emit('frame', { type: 'user/message', data: { source: { rpcId: requestId } } }) + stream.emit('frame', { type: 'tool/call', data: { callId: 'example', name: 'list', arguments: '{}' } }) + stream.emit('frame', { type: 'tool/result', data: { message: { toolCallId: 'example', isError: false } } }) + stream.emit('frame', { type: 'tool/result', surfaceOp: { op: 'replace', startSeq: 12, endSeq: 12 }, + data: { message: { toolCallId: 'example', isError: false } } }) + stream.emit('frame', { type: 'tool/result', surfaceOp: { op: 'replace', startSeq: 4, endSeq: 4 }, + data: { message: { toolCallId: 'earlier-turn', isError: false } } }) + stream.emit('frame', { type: 'tool/result', data: { message: { toolCallId: 'example', isError: false } } }) + stream.emit('frame', { type: 'tool/call', data: { callId: 'other', name: 'read', arguments: '{}' } }) + stream.emit('frame', { type: 'tool/result', data: { message: { toolCallId: 'other', isError: true } } }) + stream.emit('frame', { type: 'assistant/message', data: { + message: { content: [{ type: 'text', text: history.join(' ') }] }, + } }) + stream.emit('frame', { type: 'turn/end', data: { turn, reason: { kind: 'completed' } } }) + return { accepted: true } + }, +} + +let dispose +apply({ sessionController: controller, effect(fn) { dispose = fn() } }, { + bridgeHome: process.argv[2], + bridgeExecutable: process.argv[3], +}) +process.on('SIGTERM', () => dispose()) diff --git a/tests/test_baseline_registry.py b/tests/test_baseline_registry.py new file mode 100644 index 0000000..a7298de --- /dev/null +++ b/tests/test_baseline_registry.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import pytest + +from agent_bridge.adapters.fake import FakeAdapter +from agent_bridge.baselines import Baseline +from agent_bridge.desktop_ipc import DesktopIPC +from agent_bridge.registry import Registry + + +@pytest.fixture +def dsh_home(bridge_home): + bridge_home.mkdir(parents=True, exist_ok=True) + (bridge_home / "agents.toml").write_text( + '[agents.dsh]\nprotocol = "acp"\ncommand = ["dsh"]\n', encoding="utf-8" + ) + return bridge_home + + +@pytest.mark.asyncio +async def test_named_forks_keep_origin_and_labels_across_restart(dsh_home, tmp_path, monkeypatch): + work = tmp_path / "project" + work.mkdir() + cwd = str(work.resolve()) + registry = Registry.create(dsh_home) + monkeypatch.setattr(DesktopIPC, "connected", property(lambda self: True)) + monkeypatch.setattr(registry, "_adapter_for", lambda session: FakeAdapter(registry.config.get("dsh"), dsh_home)) + baseline = Baseline( + baseline_id="base_v1", + name="查清初始化路径", + agent="dsh", + backend="desktop", + cwd=cwd, + native_session_id="native-baseline-v1", + source_session_id="sess_original", + ) + registry.baselines.add(baseline) + await registry.start() + try: + await registry.set_default_baseline(cwd, "dsh", baseline.baseline_id) + first = await registry.dispatch_task( + "dsh", "排查缓存", cwd, fork_label="缓存问题 A" + ) + assert first["baseline_id"] == baseline.baseline_id + assert first["fork_label"] == "缓存问题 A" + result = await registry.wait_task(first["task_id"], timeout_sec=5) + assert result["status"] == "completed" + assert result["baseline_name"] == baseline.name + assert result["fork_label"] == "缓存问题 A" + + second = await registry.dispatch_task( + "dsh", "独立排查", cwd, baseline="base_v1", fork_label="独立分支 B" + ) + await registry.wait_task(second["task_id"], timeout_sec=5) + empty = await registry.dispatch_task("dsh", "从空白开始", cwd, baseline="empty") + await registry.wait_task(empty["task_id"], timeout_sec=5) + assert empty["baseline_id"] is None + assert empty["fork_label"] is None + with pytest.raises(ValueError, match="requires a selected baseline"): + await registry.dispatch_task("dsh", "bad", cwd, baseline="empty", fork_label="bad") + with pytest.raises(ValueError, match="only be supplied"): + await registry.dispatch_task( + "dsh", "bad", cwd, session_id=first["session_id"], fork_label="bad" + ) + finally: + await registry.stop() + + reopened = Registry.create(dsh_home) + await reopened.start() + try: + rows = {row["session_id"]: row for row in reopened.list_sessions()} + assert rows[first["session_id"]]["baseline_name"] == baseline.name + assert rows[first["session_id"]]["fork_source_id"] == baseline.native_session_id + assert rows[first["session_id"]]["fork_label"] == "缓存问题 A" + assert rows[second["session_id"]]["fork_label"] == "独立分支 B" + assert reopened.list_baselines(cwd)["default_baseline_id"] == baseline.baseline_id + await reopened.set_default_baseline(cwd, "dsh", None) + assert reopened.list_baselines(cwd)["default_baseline_id"] is None + finally: + await reopened.stop() + + +@pytest.mark.asyncio +async def test_create_baseline_saves_an_independent_fork_without_changing_source( + dsh_home, tmp_path, monkeypatch +): + work = tmp_path / "project" + work.mkdir() + registry = Registry.create(dsh_home) + + class ForkingFakeAdapter(FakeAdapter): + def can_fork(self): + return True + + async def ensure_session(self, session): + if session.fork_source_id and session.native_session_id is None: + session.native_session_id = f"fork-of-{session.fork_source_id}" + await super().ensure_session(session) + + adapter = ForkingFakeAdapter(registry.config.get("dsh"), dsh_home) + monkeypatch.setattr(DesktopIPC, "connected", property(lambda self: True)) + monkeypatch.setattr(registry, "_adapter_for", lambda session: adapter) + await registry.start() + try: + source = await registry.dispatch_task("dsh", "调查公共信息", str(work.resolve())) + assert (await registry.wait_task(source["task_id"], timeout_sec=5))["status"] == "completed" + source_native = registry.sessions[source["session_id"]].native_session_id + assert registry.sessions[source["session_id"]].backend == "desktop" + saved = await registry.create_baseline(source["session_id"], "基线 1") + record = registry.baselines.get(saved["baseline"]["baseline_id"]) + assert record.source_session_id == source["session_id"] + assert record.native_session_id == f"fork-of-{source_native}" + assert registry.sessions[source["session_id"]].native_session_id == source_native + assert registry.sessions[saved["session_id"]].is_baseline is True + + await registry.set_default_baseline(str(work.resolve()), "dsh", record.baseline_id) + child = await registry.dispatch_task( + "dsh", "排查独立问题", str(work.resolve()), fork_label="分支 1" + ) + assert child["baseline_id"] == record.baseline_id + assert (await registry.wait_task(child["task_id"], timeout_sec=5))["status"] == "completed" + finally: + await registry.stop() diff --git a/tests/test_baselines.py b/tests/test_baselines.py new file mode 100644 index 0000000..8e321be --- /dev/null +++ b/tests/test_baselines.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +import json +import os +from datetime import datetime +from pathlib import Path + +import pytest + +from agent_bridge.baselines import Baseline, BaselineCorruptionError, BaselineStore + + +def make_record( + baseline_id: str, + cwd: Path | str, + *, + agent: str = "dsh", + name: str = "baseline", + description: str | None = None, + native_session_id: str = "native-1", + source_session_id: str = "sess-src", + created_at: str | None = None, +) -> Baseline: + fields: dict[str, object] = { + "baseline_id": baseline_id, + "name": name, + "description": description, + "agent": agent, + "cwd": str(cwd), + "native_session_id": native_session_id, + "source_session_id": source_session_id, + } + if created_at is not None: + fields["created_at"] = created_at + return Baseline(**fields) + + +@pytest.fixture +def project(tmp_path: Path) -> Path: + path = tmp_path / "project" + path.mkdir() + return path + + +def test_add_get_roundtrip_and_reload(tmp_path: Path, project: Path): + home = tmp_path / "home" + store = BaselineStore(home) + record = make_record("base_0001", project, description="first saved fork") + store.add(record) + + assert store.get("base_0001") == record + assert (home / "baselines" / "records" / "base_0001.json").is_file() + + # A second instance reads the record on demand from disk. + reopened = BaselineStore(home) + assert reopened.get("base_0001") == record + + +def test_created_at_defaults_to_iso_timestamp(tmp_path: Path, project: Path): + store = BaselineStore(tmp_path / "home") + store.add(make_record("base_iso", project)) + loaded = store.get("base_iso") + assert loaded.created_at + assert datetime.fromisoformat(loaded.created_at) + + +def test_add_refuses_to_overwrite_immutable_id(tmp_path: Path, project: Path): + home = tmp_path / "home" + store = BaselineStore(home) + store.add(make_record("base_dup", project, name="original", native_session_id="native-a")) + + with pytest.raises(FileExistsError): + store.add(make_record("base_dup", project, name="replacement", native_session_id="native-b")) + + assert store.get("base_dup").name == "original" + # Immutability holds across independent instances too. + assert BaselineStore(home).get("base_dup").native_session_id == "native-a" + + +def test_get_missing_id_raises_keyerror(tmp_path: Path): + store = BaselineStore(tmp_path / "home") + with pytest.raises(KeyError): + store.get("base_absent") + + +def test_list_filters_by_scope_and_sorts_by_created_at(tmp_path: Path): + home = tmp_path / "home" + project_a = tmp_path / "alpha" + project_b = tmp_path / "beta" + store = BaselineStore(home) + store.add(make_record("base_late", project_a, created_at="2024-01-02T00:00:00+00:00")) + store.add(make_record("base_early", project_a, created_at="2024-01-01T00:00:00+00:00")) + store.add(make_record("base_other_project", project_b)) + store.add(make_record("base_other_agent", project_a, agent="claude")) + + listed = store.list(project_a, "dsh") + assert [item.baseline_id for item in listed] == ["base_early", "base_late"] + assert [item.baseline_id for item in store.list(project_b, "dsh")] == ["base_other_project"] + assert [item.baseline_id for item in store.list(project_a, "claude")] == ["base_other_agent"] + + +def test_scope_uses_canonical_cwd(tmp_path: Path, project: Path): + store = BaselineStore(tmp_path / "home") + store.add(make_record("base_canon", project)) + + detoured = str(project / ".." / project.name) + os.sep + assert [item.baseline_id for item in store.list(detoured, "dsh")] == ["base_canon"] + + # A normcase-different spelling of the same directory is the same scope. + spelled = os.path.normcase(str(project)) + store.set_default(os.path.normcase(detoured), "dsh", "base_canon") + assert store.get_default(spelled, "dsh") == "base_canon" + + +def test_default_roundtrip_and_clear_retains_records(tmp_path: Path, project: Path): + store = BaselineStore(tmp_path / "home") + store.add(make_record("base_one", project)) + store.add(make_record("base_two", project)) + + assert store.get_default(project, "dsh") is None + store.set_default(project, "dsh", "base_two") + assert store.get_default(project, "dsh") == "base_two" + + store.set_default(project, "dsh", None) + assert store.get_default(project, "dsh") is None + assert [item.baseline_id for item in store.list(project, "dsh")] == ["base_one", "base_two"] + + +def test_defaults_are_persisted_per_scope_across_instances(tmp_path: Path): + home = tmp_path / "home" + project_a = tmp_path / "alpha" + project_b = tmp_path / "beta" + store_a = BaselineStore(home) + store_b = BaselineStore(home) + store_a.add(make_record("base_a", project_a)) + store_b.add(make_record("base_b", project_b)) + + store_a.set_default(project_a, "dsh", "base_a") + store_b.set_default(project_b, "dsh", "base_b") + + # Neither instance's selector overwrote the other scope's file. + assert store_a.get_default(project_a, "dsh") == "base_a" + assert store_b.get_default(project_b, "dsh") == "base_b" + assert store_a.get_default(project_b, "dsh") == "base_b" + assert store_b.get_default(project_a, "dsh") == "base_a" + + store_a.set_default(project_a, "dsh", None) + assert store_b.get_default(project_a, "dsh") is None + assert BaselineStore(home).get_default(project_b, "dsh") == "base_b" + assert len(list((home / "baselines" / "defaults").glob("*.json"))) == 2 + + +def test_add_does_not_touch_other_scope_default(tmp_path: Path): + home = tmp_path / "home" + project_a = tmp_path / "alpha" + project_b = tmp_path / "beta" + store = BaselineStore(home) + store.add(make_record("base_a", project_a)) + store.set_default(project_a, "dsh", "base_a") + + store.add(make_record("base_b", project_b, agent="claude")) + store.set_default(project_b, "claude", "base_b") + + assert store.get_default(project_a, "dsh") == "base_a" + assert store.get_default(project_b, "claude") == "base_b" + + +def test_set_default_rejects_missing_and_foreign_scope(tmp_path: Path): + home = tmp_path / "home" + project_a = tmp_path / "alpha" + project_b = tmp_path / "beta" + store = BaselineStore(home) + store.add(make_record("base_a", project_a)) + + with pytest.raises(KeyError): + store.set_default(project_a, "dsh", "base_missing") + with pytest.raises(ValueError): + store.set_default(project_b, "dsh", "base_a") + with pytest.raises(ValueError): + store.set_default(project_a, "claude", "base_a") + assert store.get_default(project_b, "dsh") is None + + +@pytest.mark.parametrize( + "bad_id", + ["", "..", "../evil", "a/b", "a\\b", ".hidden", "base id", "base..x", "base\n", "x" * 200], +) +def test_invalid_ids_are_rejected_before_touching_filenames(tmp_path: Path, project: Path, bad_id: str): + store = BaselineStore(tmp_path / "home") + with pytest.raises(ValueError): + store.add(make_record(bad_id, project)) + with pytest.raises(ValueError): + store.get(bad_id) + with pytest.raises(ValueError): + store.set_default(project, "dsh", bad_id) + assert not (tmp_path / "home" / "baselines").exists() + + +@pytest.mark.parametrize("field", ["name", "native_session_id", "source_session_id"]) +def test_add_rejects_blank_required_fields(tmp_path: Path, project: Path, field: str): + store = BaselineStore(tmp_path / "home") + record = make_record("base_blank", project) + setattr(record, field, " ") + with pytest.raises(ValueError): + store.add(record) + + +def test_corrupt_record_file_is_not_read_as_empty(tmp_path: Path, project: Path): + home = tmp_path / "home" + records = home / "baselines" / "records" + records.mkdir(parents=True) + (records / "base_bad.json").write_text("{not valid json", encoding="utf-8") + store = BaselineStore(home) + + with pytest.raises(BaselineCorruptionError): + store.get("base_bad") + with pytest.raises(BaselineCorruptionError): + store.list(project, "dsh") + + +def test_null_record_file_is_corruption_not_missing(tmp_path: Path): + home = tmp_path / "home" + records = home / "baselines" / "records" + records.mkdir(parents=True) + (records / "base_null.json").write_text("null", encoding="utf-8") + store = BaselineStore(home) + + with pytest.raises(BaselineCorruptionError): + store.get("base_null") + + +def test_corrupt_default_selector_is_not_read_as_none(tmp_path: Path, project: Path): + home = tmp_path / "home" + store = BaselineStore(home) + store.add(make_record("base_ok", project)) + store.set_default(project, "dsh", "base_ok") + + selector = next((home / "baselines" / "defaults").glob("*.json")) + selector.write_text(json.dumps({"baseline_id": 17}), encoding="utf-8") + with pytest.raises(BaselineCorruptionError): + store.get_default(project, "dsh") + + selector.write_text("{broken", encoding="utf-8") + with pytest.raises(BaselineCorruptionError): + BaselineStore(home).get_default(project, "dsh") diff --git a/tests/test_dsh_desktop.py b/tests/test_dsh_desktop.py new file mode 100644 index 0000000..d619020 --- /dev/null +++ b/tests/test_dsh_desktop.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +import asyncio +import os +import shutil +import socket +import stat +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +import httpx2 +import pytest + +from agent_bridge.adapters import dsh_desktop +from agent_bridge.adapters.fake import FakeAdapter +from agent_bridge.desktop_ipc import DesktopIPC +from agent_bridge.hub import create_app +from agent_bridge.registry import Registry + + +async def _wait_for_connection(ipc: DesktopIPC, connected: bool) -> None: + for _ in range(500): + if ipc.connected == connected: + return + await asyncio.sleep(0.02) + pytest.fail(f"Desktop IPC did not reach connected={connected}") + + +@pytest.mark.skipif(os.name == "nt", reason="stale Unix domain socket") +async def test_connector_retries_stale_socket(): + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is required to run the Desktop connector") + fixture = Path(__file__).with_name("dsh_desktop_fixture.mjs") + with TemporaryDirectory(prefix="ab-dsh-") as directory: + home = Path(directory).resolve() + ipc_dir = home / "dsh-ipc" + ipc_dir.mkdir(mode=0o700) + endpoint = ipc_dir / "desktop.sock" + with socket.socket(socket.AF_UNIX) as stale: + stale.bind(str(endpoint)) + endpoint.chmod(0o600) + proc = await asyncio.create_subprocess_exec(node, str(fixture), str(home)) + try: + with pytest.raises(TimeoutError): + await asyncio.wait_for(proc.wait(), 1.5) + registry = Registry.create(home) + app = create_app(registry, token="fixture-bearer") + async with app.router.lifespan_context(app): + await _wait_for_connection(registry.desktop, True) + finally: + if proc.returncode is None: + proc.terminate() + await proc.wait() + + +async def test_hub_lifecycle_through_desktop_connector(tmp_path): + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is required to run the Desktop connector") + fixture = Path(__file__).with_name("dsh_desktop_fixture.mjs") + with TemporaryDirectory(prefix="ab-dsh-") as directory: + home = Path(directory).resolve() + registry = Registry.create(home) + registry.config.coordinator.mode = "auto" + app = create_app(registry, token="fixture-bearer") + async with app.router.lifespan_context(app), httpx2.AsyncClient( + transport=httpx2.ASGITransport(app=app), base_url="http://test", + headers={"Authorization": "Bearer fixture-bearer"}, + ) as client: + if os.name != "nt": + endpoint = home / "dsh-ipc" / "desktop.sock" + assert stat.S_IMODE(endpoint.parent.stat().st_mode) == 0o700 + assert stat.S_IMODE(endpoint.stat().st_mode) == 0o600 + executable = str(Path(sys.executable).with_name("agent-bridge.exe")) + proc = await asyncio.create_subprocess_exec(node, str(fixture), str(home), executable) + try: + await _wait_for_connection(registry.desktop, True) + assert (await client.get('/v1/baselines', headers={"Authorization": "invalid"})).status_code == 401 + body = {"agent": "dsh", "cwd": str(tmp_path), "message": "seed"} + source = (await client.post('/v1/agents/dsh/invoke', json=body)).json() + assert source["result_text"] == "seed", (source["status"], source.get("stop_reason"), source.get("error")) + transcript = (await client.get(f'/v1/sessions/{source["session_id"]}/transcript')).json()["events"] + assert [(event["type"], event["data"]) for event in transcript if event["type"] in { + "message_chunk", "tool_call", "tool_call_update", + }] == [ + ("tool_call", {"tool_call_id": "example", "title": "list"}), + ("tool_call_update", {"tool_call_id": "example", "status": "completed"}), + ("tool_call", {"tool_call_id": "other", "title": "read"}), + ("tool_call_update", {"tool_call_id": "other", "status": "failed"}), + ("message_chunk", {"text": "seed"}), + ] + saved = (await client.post('/v1/baselines', json={ + "session_id": source["session_id"], "name": "Baseline", + })).json() + baseline_id = saved["baseline"]["baseline_id"] + assert (await client.put('/v1/baselines/default', json={ + "cwd": str(tmp_path), "baseline_id": baseline_id, + })).json()["ok"] + result = (await client.post('/v1/agents/dsh/invoke', json={ + **body, "message": "child", "fork_label": "Branch", + })).json() + assert result["result_text"] == "seed child", result + assert result["baseline_id"] == baseline_id + assert result["fork_label"] == "Branch" + listed = (await client.get('/v1/baselines', params={"cwd": str(tmp_path)})).json() + assert listed["default_baseline_id"] == baseline_id + assert (await client.put('/v1/baselines/default', json={ + "cwd": str(tmp_path), "baseline_id": None, + })).json()["default_baseline_id"] is None + assert not (home / "dsh-desktop.json").exists() + finally: + proc.terminate() + await proc.wait() + await _wait_for_connection(registry.desktop, False) + refused = (await client.post('/v1/tasks', json={**body, "baseline": baseline_id})).json() + assert "disconnected" in refused["error"] + if os.name != "nt": + assert not endpoint.exists() + + +@pytest.mark.skipif(os.name != "nt", reason="Windows named pipe ACL") +def test_windows_desktop_pipe_acl(tmp_path): + import win32security + + from agent_bridge.desktop_pipe import _address, _private_pipe, _user_sid + + sid = _user_sid() + pipe = _private_pipe(_address(tmp_path, sid), sid) + try: + descriptor = win32security.GetSecurityInfo( + pipe, win32security.SE_KERNEL_OBJECT, + win32security.DACL_SECURITY_INFORMATION | win32security.OWNER_SECURITY_INFORMATION, + ) + assert descriptor.GetSecurityDescriptorOwner() == sid + acl = descriptor.GetSecurityDescriptorDacl() + assert acl.GetAceCount() == 1 and acl.GetAce(0)[2] == sid + finally: + pipe.Close() + + +@pytest.mark.asyncio +async def test_disconnected_desktop_falls_back_to_acp_and_disables_fork(monkeypatch, tmp_path): + home = tmp_path / "bridge" + home.mkdir() + (home / "agents.toml").write_text('[agents.dsh]\nprotocol = "acp"\ncommand = ["dsh"]\n', encoding="utf-8") + project = tmp_path / "project" + project.mkdir() + registry = Registry.create(home) + monkeypatch.setattr(registry, "_adapter_for", lambda session: FakeAdapter(registry.config.get("dsh"), home)) + await registry.start() + try: + result = await registry.dispatch_task("dsh", "ordinary", str(project), baseline="empty") + assert registry.sessions[result["session_id"]].backend is None + assert (await registry.wait_task(result["task_id"], timeout_sec=5))["status"] == "completed" + with pytest.raises(ValueError, match="Desktop connection is required"): + await registry.create_baseline(result["session_id"], "baseline") + finally: + await registry.stop() + + +@pytest.mark.asyncio +async def test_host_drop_before_create_retries_ordinary_turn_on_acp(monkeypatch, tmp_path): + home = tmp_path / "bridge" + home.mkdir() + (home / "agents.toml").write_text('[agents.dsh]\nprotocol = "acp"\ncommand = ["dsh"]\n', encoding="utf-8") + project = tmp_path / "project" + project.mkdir() + monkeypatch.setattr(DesktopIPC, "connected", property(lambda self: True)) + registry = Registry.create(home) + + class DroppedDesktop(FakeAdapter): + async def run_turn(self, session, task): + raise dsh_desktop.DesktopUnavailable("Host down") + + def adapter_for(session): + return (DroppedDesktop if session.backend == "desktop" else FakeAdapter)(registry.config.get("dsh"), home) + + monkeypatch.setattr(registry, "_adapter_for", adapter_for) + await registry.start() + try: + sent = await registry.dispatch_task("dsh", "ordinary", str(project), baseline="empty") + result = await registry.wait_task(sent["task_id"], timeout_sec=5) + assert result["status"] == "completed" + assert result["backend"] == "acp" + assert "used ACP" in result["warnings"][0] + finally: + await registry.stop() diff --git a/tests/test_hub.py b/tests/test_hub.py index 622a43e..4ff8469 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -19,7 +19,9 @@ from agent_bridge.adapters.cli import CliAdapter from agent_bridge.adapters.codex import CodexAdapter from agent_bridge.adapters.fake import FakeAdapter +from agent_bridge.baselines import Baseline from agent_bridge.config import AgentConfig, CliConfig, EnvConfig, load_config +from agent_bridge.desktop_ipc import DesktopIPC from agent_bridge.hub import create_app, serve, validate_host from agent_bridge.hub_client import HubClient, discover from agent_bridge.registry import Registry @@ -95,6 +97,41 @@ async def run(adapter, session, task): await registry.wait_task(root['task_id'], timeout_sec=5) +async def test_worker_dsh_cannot_use_owner_baselines(worker, tmp_path, monkeypatch): + client, registry, _, env = worker + cwd = str(tmp_path.resolve()) + registry.baselines.add(Baseline(baseline_id='private', name='Private', agent='dsh', + backend='desktop', cwd=cwd, native_session_id='private-native', source_session_id='private-source')) + registry.baselines.set_default(cwd, 'dsh', 'private') + monkeypatch.setattr(DesktopIPC, 'connected', property(lambda self: True)) + monkeypatch.setattr(registry, '_adapter_for', lambda session: FakeAdapter(registry.config.get('fake'), registry.home)) + headers = {'Authorization': 'Bearer ' + env['AGENT_BRIDGE_HUB_TOKEN']} + body = {'agent': 'dsh', 'message': 'peer', 'cwd': cwd} + + for selection in ('default', 'private'): + denied = await client.post('/v1/tasks', json={**body, 'baseline': selection}, headers=headers) + assert denied.status_code == 400 + assert 'baseline forks are not available' in denied.json()['error'] + result = (await client.post('/v1/agents/dsh/invoke', json=body, headers=headers)).json() + assert result['ok'] and result['baseline_id'] is None + assert registry.sessions[result['session_id']].fork_source_id is None + for method, path, args in ( + ('GET', '/v1/baselines', {'params': {'cwd': cwd}}), + ('POST', '/v1/baselines', {'json': {'session_id': result['session_id'], 'name': 'worker'}}), + ('PUT', '/v1/baselines/default', {'json': {'cwd': cwd, 'baseline_id': None}}), + ): + response = await client.request(method, path, headers=headers, **args) + assert response.status_code == 403 and 'worker token cannot access' in response.json()['error'] + + owner = (await client.post('/v1/agents/dsh/invoke', json=body)).json() + assert owner['ok'] and owner['baseline_id'] == 'private' + assert registry.sessions[owner['session_id']].fork_source_id == 'private-native' + response = await client.get('/v1/sessions/' + owner['session_id'] + '/transcript', headers=headers) + assert response.status_code == 403 + response = await client.post('/v1/tasks', json={**body, 'session_id': owner['session_id']}, headers=headers) + assert response.status_code == 403 + + async def test_depth_and_self_dispatch(worker, tmp_path): client, registry, root, env = worker body = {'agent': 'fake', 'message': 'peer', 'cwd': str(tmp_path)} diff --git a/tests/test_remote.py b/tests/test_remote.py index a291828..9a8460b 100644 --- a/tests/test_remote.py +++ b/tests/test_remote.py @@ -18,7 +18,9 @@ from agent_bridge import cli from agent_bridge.adapters.fake import FakeAdapter +from agent_bridge.baselines import Baseline from agent_bridge.config import AgentConfig, AppConfig, HubConfig, RemoteConfig, load_config +from agent_bridge.desktop_ipc import DesktopIPC from agent_bridge.hub import create_app from agent_bridge.models import ProcState, Session, Task, TaskStatus from agent_bridge.registry import Registry @@ -30,9 +32,10 @@ @pytest.fixture async def gateway(bridge_home, tmp_path): config = load_config(bridge_home) + config.agents['dsh'].env['DSH_PERMISSION_MODE'] = 'workspace-write' config.hub.remote = RemoteConfig(enabled=True, public_url='http://127.0.0.1:8766', require_approval=False, - remote_callable_agents=['fake', 'cloud'], remote_workspaces={'project': str(tmp_path)}) + remote_callable_agents=['fake', 'cloud', 'dsh'], remote_workspaces={'project': str(tmp_path)}) config.agents['cloud'] = AgentConfig(name='cloud', protocol='cloud', cloud={'provider': 'devin', 'org_id': 'org'}) registry = Registry.create(bridge_home, config) await registry.start() @@ -54,6 +57,23 @@ def payload(**kwargs): return {'agent': 'fake', 'message': 'hello', 'workspace': 'project', **kwargs} +async def test_remote_dsh_starts_without_local_default_baseline(gateway, monkeypatch): + client, registry, scope, _ = gateway + cwd = scope.workspaces['project'] + registry.baselines.add(Baseline(baseline_id='private', name='Private', agent='dsh', + backend='desktop', cwd=cwd, native_session_id='private-native', source_session_id='private-source')) + registry.baselines.set_default(cwd, 'dsh', 'private') + monkeypatch.setattr(DesktopIPC, 'connected', property(lambda self: True)) + monkeypatch.setattr(registry, '_adapter_for', lambda session: FakeAdapter(registry.config.get('fake'), registry.home)) + + result = (await client.post('/v1/agents/dsh/invoke', json=payload(agent='dsh'))).json() + assert result['ok'] + assert result['baseline_id'] is None + assert registry.sessions[result['session_id']].fork_source_id is None + result = await client.post('/v1/tasks', json=payload(agent='dsh', baseline='private')) + assert result.status_code == 400 + + @pytest.mark.parametrize('turn_timeout', [0, 30, 86400]) async def test_remote_token_default_ttl_independent_of_turn_timeout(gateway, turn_timeout): _, registry, _, _ = gateway diff --git a/tests/test_server_tools.py b/tests/test_server_tools.py index f287824..3ee5405 100644 --- a/tests/test_server_tools.py +++ b/tests/test_server_tools.py @@ -5,12 +5,14 @@ import sys import time import types +from unittest.mock import AsyncMock import pytest +from agent_bridge.hub_client import HubClient from agent_bridge.processes import reap_subprocess from agent_bridge.registry import Registry -from agent_bridge.server import INSTRUCTIONS, _error, _registry, list_sessions, mcp +from agent_bridge.server import INSTRUCTIONS, _error, _registry, create_baseline, lifespan, list_sessions, mcp def test_tools_registered(): @@ -18,13 +20,16 @@ def test_tools_registered(): assert names == [ "cancel_task", "check_task", + "create_baseline", "dispatch_task", "end_session", "get_result", "get_transcript", "invoke_agent", "list_agents", + "list_baselines", "list_sessions", + "set_default_baseline", "set_preferences", "wait_task", ] @@ -52,6 +57,22 @@ def test_error_exposes_exception_type(): } +async def test_manual_mcp_host_requires_user_request_to_create_baseline(monkeypatch): + client = HubClient("http://hub") + monkeypatch.setenv("AGENT_BRIDGE_MODE", "manual") + monkeypatch.setattr("agent_bridge.server.discover", AsyncMock(return_value=client)) + forward = AsyncMock(return_value={"ok": True}) + monkeypatch.setattr(client, "_call", forward) + async with lifespan(mcp) as backend: + ctx = types.SimpleNamespace(request_context=types.SimpleNamespace(lifespan_context=backend)) + refused = await create_baseline(ctx, session_id="sess", name="Baseline") + assert not refused["ok"] and "coordinator mode is manual" in refused["error"] + forward.assert_not_awaited() + assert (await create_baseline(ctx, session_id="sess", name="Baseline", user_requested=True))["ok"] + forward.assert_awaited_once_with("create_baseline", session_id="sess", name="Baseline", + description=None, user_requested=True) + + def test_registry_from_lifespan_context_touches_activity(bridge_home): registry = Registry.create(bridge_home) registry._last_activity = registry._last_activity - 1 diff --git a/uv.lock b/uv.lock index 07585b0..88d2088 100644 --- a/uv.lock +++ b/uv.lock @@ -19,6 +19,7 @@ dependencies = [ { name = "mcp" }, { name = "psutil" }, { name = "pydantic" }, + { name = "pywin32", marker = "sys_platform == 'win32'" }, { name = "starlette" }, { name = "uvicorn" }, ] @@ -44,6 +45,7 @@ requires-dist = [ { name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0" }, { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.24" }, { name = "pytest-timeout", marker = "extra == 'dev'", specifier = ">=2.4.0" }, + { name = "pywin32", marker = "sys_platform == 'win32'", specifier = ">=306" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.16.5" }, { name = "starlette", specifier = ">=0.40" }, { name = "uvicorn", specifier = ">=0.30" },