# DualAI [![Cross-Platform CI](https://github.com/divyprj/dualai/actions/workflows/ci.yml/badge.svg)](https://github.com/divyprj/dualai/actions/workflows/ci.yml) Universal, cross-platform AI-to-AI communication and coordination layer. DualAI lets different AI coding assistants, CLI agents, and local/API models discover one another, exchange structured context, delegate work, compare independent outputs, and preserve conversation continuity over one shared MCP, CLI, and Python protocol. ## Technology Stack - **Language & Validation:** Python 3.10+, Pydantic v2 (`pyproject.toml`) - **MCP & Protocol Transport:** Official `mcp` SDK (`stdio`, `streamable-http`, `sse`), stdlib `urllib` HTTP client, `subprocess` (`shell=False`) - **Storage & OS Paths:** `filelock` advisory locking with atomic `os.replace`, `platformdirs`, `PyYAML`, `tomli-w` (`tomli` on Python < 3.11) - **Optional Browser Extra (`dualai[browser]`):** Playwright, isolated from core dependencies in `src/dualai/transports/chatgpt_web.py` ## Key Capabilities - **Standardized Core Protocol**: Typed Pydantic v2 request/response envelopes (`src/dualai/protocol/models.py`), explicit lifecycle states (`queued`, `dispatched`, `running`, `completed`, `failed`, `timed_out`, `cancelled`), idempotency keys, and conversation tracking. - **Honest Agent Discovery**: Distinguishes `registered`, `available`, `connected`, `actively_responsive`, and `unavailable` states rather than assuming configured tools have active sessions. - **MCP Server (`dualai-mcp` / `dualai mcp`)**: Supports `stdio`, `streamable-http`, and `sse` transports, exposing 11 coordination tools and 3 `dualai://` resources. - **Unified CLI (`dualai`)**: Manage discovery, single-target queries, multi-agent comparisons, async request tracking, relay mailboxes, legacy `bridge/` watching, diagnostics, and external agent integrations. - **Python Client (`DualAIClient`, `AsyncDualAIClient`)**: Programmatic sync/async access without requiring Playwright. - **Pluggable Transports**: - Headless CLI backends (`opencode`, `claude`, `codex`, `gemini`) when installed on `PATH` - HTTP backends (`ollama`, OpenAI-compatible APIs via env-var credentials) - Peer relay mailboxes (`antigravity`, `cursor`, `windsurf`, `claude-desktop`, `vscode-copilot`, `cline`, `roo-code`, `continue`, or custom sessions) - Isolated optional Playwright driver for ChatGPT Web (`dualai[browser]`) - **Declarative Agent Integrations (`dualai integrate`)**: Non-destructively configures MCP entries (creating `.bak` backups and preserving unrelated keys) and installs the consolidated `agentskills.io` skill (`skills/dualai/SKILL.md`). - **Cross-Platform Design**: Built for Linux, Windows, and macOS using `pathlib`, `platformdirs`, `filelock`, and atomic `os.replace` writes. ## Architecture ```mermaid flowchart LR Callers["MCP Clients / CLI / Python API"] --> Engine["DualAIEngine"] Engine --> Store["StateStore (FileLock + Atomic JSON)"] Engine --> CLI["CliAgentTransport (opencode, claude, codex, gemini)"] Engine --> HTTP["HttpAgentTransport (ollama, openai REST)"] Engine --> Mailbox["MailboxTransport (IDE / Desktop Relays)"] Engine --> Browser["ChatGPTWebTransport (Optional Playwright)"] ``` ```text dualai/ ├── .github/ # CI matrix, CODEOWNERS, PR and issue templates ├── docs/ # Architecture, ADRs, protocol, compatibility, cross-platform docs ├── examples/ # Example config and Python client script ├── skills/dualai/SKILL.md # Consolidated portable Agent Skill ├── src/dualai/ │ ├── cli/ # Unified `dualai` CLI and legacy bridge watcher │ ├── client/ # `DualAIClient` and `AsyncDualAIClient` │ ├── config/ # `platformdirs` paths and `DualAIConfig` │ ├── core/ # `DualAIEngine` and prompt builder │ ├── integrations/ # Extensible adapters (JSON, TOML, YAML, OpenCode, VS Code) │ ├── mcp/ # `dualai-mcp` server (stdio / streamable-http / sse) │ ├── protocol/ # Envelopes, enums, and domain exceptions │ ├── security/ # Path/ID guards, secret redaction, untrusted boundaries │ ├── storage/ # `filelock` + atomic JSON `StateStore` │ ├── transports/ # CLI, HTTP, Mailbox, Mock, isolated ChatGPT Web │ └── utils/ # Stderr logger and markdown-safe `TextCleaner` ├── tests/ # Unit, integration, and compatibility test suites └── CONTRIBUTING.md # Development setup, checks, and PR guidelines ``` See [docs/architecture.md](docs/architecture.md), [docs/architecture/decisions/](docs/architecture/decisions/), and [docs/protocol.md](docs/protocol.md) for system design and envelope details. ## Prerequisites & Installation Requires **Python 3.10+**. ### Core Installation (Recommended) ```bash # Linux / macOS python3 -m venv .venv source .venv/bin/activate pip install -e . ``` ```powershell # Windows (PowerShell) py -3 -m venv .venv .\.venv\Scripts\Activate.ps1 pip install -e . ``` Using `uv`: ```bash uv venv uv pip install -e ".[dev]" # Install dualai and dualai-mcp onto user PATH (~/.local/bin) uv tool install --editable . ``` ### Optional Browser Backend (ChatGPT Web) Playwright is optional and isolated from core DualAI: ```bash pip install -e ".[browser]" playwright install chromium dualai auth chatgpt ``` ## Quick Start ### 1. Check Environment and Available Agents ```bash dualai doctor dualai agents ``` ### 2. Connect Your AI Agents via MCP Preview or install DualAI's MCP entry and `SKILL.md` for supported tools: ```bash dualai integrate list dualai integrate show claude-code --scope project dualai integrate install antigravity --scope user dualai integrate install cursor --scope project --project-dir /path/to/repo dualai integrate verify ``` See [docs/compatibility-matrix.md](docs/compatibility-matrix.md) for all supported agents, config files, and limitations. ### 3. Send Requests and Compare Agents ```bash # Query a CLI or HTTP backend dualai ask opencode "Review this authentication flow for race conditions" --mode review # Compare multiple targets concurrently dualai compare "Propose a cache invalidation strategy" --targets claude,codex # Queue asynchronously for a connected relay IDE session dualai ask cursor "Audit src/api.py" --async dualai request get ``` ### 4. Run as an MCP Server ```bash # Default stdio transport (used by IDE/CLI MCP hosts) dualai mcp # or dualai-mcp # Streamable HTTP transport dualai mcp --transport streamable-http --host 127.0.0.1 --port 8765 ``` ### 5. Python API ```python from dualai.client import DualAIClient from dualai.protocol import RequestMode with DualAIClient() as client: agents = client.list_agents(only_available=True) ok, response = client.query( "Review this distributed lock implementation", target="claude", mode=RequestMode.REVIEW, ) ``` ## Using the DualAI Skill (`SKILL.md`) DualAI ships a single `agentskills.io`-compliant skill at [skills/dualai/SKILL.md](skills/dualai/SKILL.md) bundled inside the wheel (`dualai/_bundled_skills/dualai/SKILL.md`). It teaches coding agents to discover live targets before routing, choose appropriate reasoning modes, handle asynchronous relays, reuse `conversation_id`, and treat returned payloads as untrusted data. ### Installing the Skill & MCP Entry Running `dualai integrate install ` installs **both** the MCP server configuration (preserving existing entries with a `.bak` backup) and `SKILL.md` (pass `--no-skill` to install MCP config only): ```bash # Inspect supported agents and install status dualai integrate list # Install MCP config + SKILL.md for your IDE or CLI tool dualai integrate install antigravity --scope user dualai integrate install claude-code --scope project --project-dir /path/to/repo dualai integrate install codex-cli --scope user dualai integrate install cursor --scope user # Verify installed configurations dualai integrate verify ``` After running `install`, **reload MCP servers or restart your IDE/CLI session** so the host loads the `dualai` MCP tools and `SKILL.md`. Skill installation paths by tool: | Agent | User Scope Skill Dir | Project Scope Skill Dir | |---|---|---| | `antigravity` | `~/.gemini/config/skills` (fallback `~/.gemini/antigravity/skills`) | `.agents/skills` | | `claude-code` | `~/.claude/skills` | `.claude/skills` | | `codex` / `codex-cli` / `codex-ide` | `~/.agents/skills` | `.agents/skills` | | `cursor` | `~/.cursor/skills` | `.cursor/skills` | | `gemini-cli` | `~/.gemini/skills` | `.gemini/skills` | | `windsurf` | `~/.codeium/windsurf/skills` | `.windsurf/skills` | | `opencode` | `~/.config/opencode/skills` | `.opencode/skills` | ### Using the Skill in Chat Once installed, ask your host agent (Antigravity, Claude Code, Cursor, Codex, OpenCode, or Gemini CLI) using natural prompts: - *"Use `dualai` to list available agents, then ask `opencode` to review `src/auth.py` in `review` mode."* - *"Use `dualai` to compare `opencode` and `ollama` on caching options for this API."* - *"Register `antigravity` as a `dualai` relay session, poll pending inbox requests, and answer the top item."* Supported request modes (`RequestMode`): `standard`, `deep`, `review`, `architecture`, `research`, `debug`. ## Peer IDE Relay Workflow Interactive IDE/desktop assistants (`antigravity`, `cursor`, `windsurf`, `claude-desktop`, `vscode-copilot`, `cline`, `roo-code`, `continue`) cannot be spawned headlessly by another process. DualAI coordinates them through a shared mailbox relay: 1. **Sender queues asynchronously** (MCP `send_request(..., wait=false)` or CLI `dualai ask cursor "Review parser.py" --async`). 2. **Receiver registers its session** (MCP `register_agent_session(agent_id="cursor")` or CLI `dualai inbox register cursor`). 3. **Receiver polls and claims the next queued item** (MCP `poll_agent_inbox(agent_id="cursor", claim=true)` or CLI `dualai inbox poll cursor --claim`). 4. **Receiver submits its answer** (MCP `submit_agent_response(request_id="...", responder_agent="cursor", content="...")` or CLI `dualai inbox reply --agent cursor "..."`). 5. **Sender fetches completion** (MCP `get_request_status` / `get_response` or CLI `dualai request get `). ## MCP Tools & Resources Reference Start the server manually with `dualai-mcp` or `dualai mcp --transport {stdio,streamable-http,sse}`: | Tool | Purpose | Key Parameters | |---|---|---| | `list_agents` | List known agents and availability states | `only_available` | | `get_agent_status` | Probe a single agent backend | `agent_id` | | `send_request` | Send a prompt to a target agent | `target_agent`, `prompt`, `source_agent`, `mode`, `context`, `attachments`, `conversation_id`, `timeout_seconds`, `idempotency_key`, `wait` | | `get_request_status` | Inspect current request lifecycle state | `request_id` | | `get_response` | Retrieve response envelope and untrusted wrapper | `request_id`, `include_untrusted_boundary` | | `compare_agents` | Dispatch one prompt concurrently across targets | `targets`, `prompt`, `mode`, `context`, `timeout_seconds` | | `cancel_request` | Cancel a queued or running request | `request_id` | | `list_requests` | List recent tracked requests | `status`, `target_agent`, `limit` | | `register_agent_session` | Register or refresh an interactive IDE relay session | `agent_id`, `name`, `environment`, `capabilities` | | `poll_agent_inbox` | List or atomically claim queued relay work | `agent_id`, `claim` | | `submit_agent_response` | Complete or fail a claimed relay request | `request_id`, `responder_agent`, `content`, `failed`, `error_message`, `external_ref` | Exposed MCP resources: `dualai://agents`, `dualai://requests`, and `dualai://requests/{request_id}`. ## CLI Command Reference Global flags: `--version`, `--base-dir `, `--config `. | Command | Summary | |---|---| | `dualai agents [--available] [--json]` | List registered/live agents and availability states | | `dualai status [agent_id] [--json]` | Show DualAI runtime paths and status summary | | `dualai ask [--mode ...] [--deep] [--attach ...] [--conversation ...] [--async] [--timeout ...] [--idempotency-key ...] [--raw] [--json]` | Send a prompt to an agent | | `dualai compare --targets [--mode ...] [--timeout ...] [--raw] [--json]` | Query multiple agents concurrently | | `dualai request get \| list [--status ...] [--target ...] [--limit ...] \| cancel [--json]` | Inspect, filter, or cancel requests | | `dualai inbox register \| poll [--claim] \| reply --agent ` | Operate an interactive agent relay session | | `dualai integrate list \| show \| install \| uninstall \| verify` | Manage external agent MCP configs and `SKILL.md` | | `dualai mcp [--transport stdio\|streamable-http\|sse] [--host 127.0.0.1] [--port 8765]` | Run the DualAI MCP server | | `dualai auth chatgpt [--account default]` | Perform interactive Playwright login for `dualai[browser]` | | `dualai watch [--bridge-dir bridge] [--target chatgpt] [--interval 1.0]` | Watch legacy `bridge/prompt.md` and write `bridge/report.md` | | `dualai doctor [--json]` | Inspect environment, dependencies, browser binary, and agent probes | ## Configuration DualAI stores configuration and state outside the repository in OS-standard directories (`platformdirs`), with overrides via a project-local `.dualai/` directory or environment variables. See [examples/config.example.json](examples/config.example.json). ### Custom Providers (`~/.config/dualai/config.json`) Override built-in CLI or HTTP backends, switch OpenCode models/output format, or disable unused built-ins under `"providers"`: ```json { "version": "2.0.0", "providers": { "opencode": { "kind": "cli", "enabled": true, "command": "opencode", "args": ["run", "-m", "opencode/deepseek-v4.1-flash-free", "--format", "json"], "input_mode": "arg", "json_output": true }, "ollama": { "kind": "http", "enabled": true, "api_style": "ollama", "base_url": "http://localhost:11434", "model": "r1:latest" } } } ``` ### Environment Variables | Variable | Default | Purpose | |---|---|---| | `DUALAI_HOME` | Unset (`.dualai/` or `platformdirs`) | Override the root directory for config, data, state (`state/`), and cache (`cache/`). | | `DUALAI_STATE_DIR` | `/state` | Override runtime state storage (`requests/`, `responses/`, `agents/`, `conversations/`, `logs/`). | | `DUALAI_CONFIG` | `/config.json` | Override the configuration JSON file path. | | `DUALAI_ENABLE_MOCK` | Unset | Set to `1` to enable the built-in `mock` echo transport for offline testing. | | `OLLAMA_HOST` | `http://localhost:11434` | Base URL for the auto-registered `ollama` HTTP transport. | | `OLLAMA_MODEL` | Auto (`llama3.2` or first installed `/api/tags` model) | Override model identifier for the `ollama` HTTP transport. | | `OPENCODE_MODEL` | Unset (OpenCode default) | Optional `provider/model` passed via `-m` to built-in `opencode` CLI runs. | | `OPENAI_BASE_URL` | `https://api.openai.com/v1` | Base URL for the auto-registered `openai` OpenAI-compatible HTTP transport. | | `OPENAI_MODEL` | `gpt-4.1` | Default model identifier for the `openai` HTTP transport. | | `OPENAI_API_KEY` | Unset | Bearer token read dynamically via `api_key_env` for `openai` requests. | ## Security - External agent responses carry `untrusted=True` and are wrapped with explicit untrusted-data boundaries. - API keys are referenced by environment variable name (`api_key_env`), never committed in config files. - On POSIX systems, state/profile directories use `0700` permissions and sensitive files use `0600`. - See [SECURITY.md](SECURITY.md) for full details. ## Known Limitations - Interactive IDE/desktop relay agents require a live session heartbeat registered over MCP or `dualai inbox`; calling synchronous `ask(wait=True)` with no active session fails fast with `AgentUnavailableError`. - Automated lint, strict `mypy`, `pytest` (`test_posix_private_permissions` skipped on non-POSIX Windows), and CLI/MCP smoke checks run and pass across `ubuntu-latest`, `windows-latest`, and `macos-latest` (`Python 3.10` to `3.13`) in [Cross-Platform CI](.github/workflows/ci.yml); interactive IDE, Ollama, OpenCode, and browser runs were tested manually only on Linux (`x86_64`). See [docs/cross-platform.md](docs/cross-platform.md). ## Development & Verification ```bash ruff check src tests examples mypy src pytest -v ``` See [CONTRIBUTING.md](CONTRIBUTING.md) for development conventions and pull request requirements, and [docs/cross-platform.md](docs/cross-platform.md) for Linux, Windows, and macOS verification details. ## License Created by **Divyansh Prajapati**. Licensed under the [MIT License](LICENSE).