BeClaude

synapse-a2a

New
Community RegistryGeneralby s-hiraoku

Complete plugin for Synapse A2A multi-agent framework including inter-agent communication, task delegation, file safety, and history management

Community PluginView Source

Overview

Enable agents to collaborate on tasks without changing their behavior

![Python 3.10+](https://www.python.org/downloads/) ![License: MIT](LICENSE) ![Tests](#testing) ![Ask DeepWiki](https://deepwiki.com/s-hiraoku/synapse-a2a)

A framework that enables inter-agent collaboration via the Google A2A Protocol while keeping CLI agents (Claude Code, Codex, Gemini, OpenCode, GitHub Copilot CLI) exactly as they are

Quick Start

This golden path starts two background agents and sends one visible cross-agent message in four commands.

Prerequisites (not counted): run uv sync, and make sure authenticated claude and codex CLIs are installed on your PATH.

bash
uv run synapse start claude --port 8108

What to expect: Synapse starts a Claude A2A server in the background and prints a PID plus the log path.

bash
uv run synapse start codex --port 8122

What to expect: Synapse starts a Codex A2A server in the background and prints a PID plus the log path.

bash
uv run synapse list --plain

What to expect: the one-shot agent list includes synapse-claude-8108 and synapse-codex-8122; wait or answer any agent prompt until both show READY.

bash
uv run synapse send synapse-codex-8122 "Reply with exactly: SYNAPSE_GOLDEN_PATH_OK" --from synapse-claude-8108 --wait

What to expect: Codex receives an A2A message from Claude and the command prints a reply containing SYNAPSE_GOLDEN_PATH_OK. If the send call fails with a UDS or HTTP timeout, run uv run synapse list --plain again and wait until both agents show READY before rerunning. If the receiver pauses for approval, answer the prompt in the agent terminal.

Cleanup (not counted):

bash
uv run synapse kill claude-8108 -f
uv run synapse kill codex-8122 -f

See issue #604 for context.

Project Goals

text
┌─────────────────────────────────────────────────────────────────┐
│  ✅ Non-Invasive: Don't change agent behavior                   │
│  ✅ Collaborative: Enable agents to work together               │
│  ✅ Transparent: Maintain existing workflows                    │
└─────────────────────────────────────────────────────────────────┘

Synapse A2A transparently wraps each agent's input/output without modifying the agent itself. This means:

  • Leverage each agent's strengths: Users can freely assign roles and specializations
  • Zero learning curve: Continue using existing workflows
  • Future-proof: Resistant to agent updates

See Project Philosophy for details.

mermaid
flowchart LR
    subgraph Terminal1["Terminal 1"]
        subgraph Agent1["synapse claude :8100"]
            Server1["A2A Server"]
            PTY1["PTY + Claude CLI"]
        end
    end
    subgraph Terminal2["Terminal 2"]
        subgraph Agent2["synapse codex :8120"]
            Server2["A2A Server"]
            PTY2["PTY + Codex CLI"]
        end
    end
    subgraph External["External"]
        ExtAgent["Google A2A Agent"]
    end

    Server1 <-->|"POST /tasks/send"| Server2
    Server1 <-->|"A2A Protocol"| ExtAgent
    Server2 <-->|"A2A Protocol"| ExtAgent

Table of Contents


Features

CategoryFeature
A2A CompliantAll communication uses Message/Part + Task format, Agent Card discovery
Agent Card Context ExtensionPass system context (ID, routing rules, other agents) via x-synapse-context to keep PTY clean
CLI IntegrationTurn existing CLI tools into A2A agents without modification
synapse sendSend messages between agents via synapse send <agent> "message". Waits up to 30s for PROCESSING targets to finish before delivering, and delays briefly (default 2s, override via SYNAPSE_SEND_READY_DELAY) for READY targets so the user has time to commit input — if the target flips to PROCESSING during the window, the send fires immediately (#467 / #642). Both waits are skipped for --force, priority 5, and --silent
Sender IdentificationAuto-identify sender via SYNAPSE_AGENT_ID env var → metadata.sender + PID matching (process ancestry, fallback)
Readiness Gate/tasks/send returns 503 until agent initialization completes; priority 5 and replies bypass
Priority InterruptPriority 5 sends SIGINT before message (emergency stop)
Multi-InstanceRun multiple agents of the same type (automatic port assignment)
External IntegrationCommunicate with other Google A2A agents
File SafetyPrevent multi-agent conflicts with file locking and change tracking (visible in synapse list)
Agent NamingCustom names and roles for easy identification (synapse send my-claude "hello")
Agent SummaryPersistent 120-char agent summary (synapse set-summary). Manual text, --auto from git context, or --clear. Visible in Canvas, MCP list_agents, Agent Card extensions.synapse, and synapse list --columns SUMMARY
Agent MonitorReal-time status (READY/WAITING/PROCESSING/DONE), CURRENT task preview, terminal jump
Task HistoryAutomatic task tracking with search, export, and statistics (enabled by default)
Quality GatesConfigurable hooks (on_idle, on_task_completed) that control status transitions
Permission DetectionWAITING status maps to A2A input_required with x-permission-prompt metadata. Child agents send structured escalation metadata to their parent, which can auto-approve/deny via the Approval Gate or fall back to manual POST /tasks/{id}/permission/approve and /deny. In synapse send --wait, the sender now keeps polling until the parent intervenes or the timeout expires. Each profile defines a deny_response for rejection. See Permission Modes
Plan ApprovalPlan-mode workflow with synapse approve/reject for human-in-the-loop review
Graceful Shutdownsynapse kill sends shutdown request before SIGTERM (30s timeout, -f for force). Worktree branches are auto-merged back to the base branch on kill (uncommitted changes are WIP-committed first; conflicts preserve the branch with a warning). Use --no-merge to skip auto-merge
Delegate Mode--delegate-mode makes an agent a manager that delegates instead of editing files
Auto-Spawn Panessynapse team start — 1st agent takes over current terminal, others in new panes. Defaults to --worktree isolation (opt out with --no-worktree). --all-new to start all in new panes. Supports profile:name:role:skill_set:port spec (tmux/iTerm2/Terminal.app/Ghostty/zellij)
Soft Interruptsynapse interrupt <target> "message" — Ergonomic shorthand for synapse send -p 4 --silent to quickly interrupt an agent
Token/Cost TrackingSkeleton for per-agent token usage tracking; synapse history stats shows TOKEN USAGE section when data exists
Saved Agent Definitionssynapse agents add/list/show/delete plus agents set/unset/roles — Save reusable agent templates or profile defaults (profile + name + role + skill set). synapse spawn accepts Agent IDs/names, synapse <profile> can load .synapse/agents.json defaults, and running agents expose the saved petname as agent_definition_id so commands can target the stable ID instead of the port-based runtime ID
Spawn Single Agent`synapse spawn <profile\saved-agent> — Spawn a single agent in a new terminal pane or window. Accepts profile names or saved agent IDs/names. **Auto-tiles (tmux)**: when a second or subsequent agent is spawned, tmux select-layout tiled is automatically applied for even pane distribution (no flags needed). Use --worktree / -w for Synapse-native git worktree isolation (all agents, .synapse/worktrees/). --branch / -b auto-enables --worktree and sets the base branch (defaults to origin/main). Use --no-worktree to opt out. --task "message" / --task-file path auto-sends a task after the agent becomes READY (with --task-timeout, --wait/--notify/--silent). **Recommended pattern**: synapse spawn <profile> --task-file <path> --task-timeout 600 --notify. Legacy -- --worktree` also supported for Claude Code only
CI AutomationPostToolUse hooks detect git push/gh pr create and auto-poll CI status, merge conflicts, and CodeRabbit reviews. Skills: /check-ci, /fix-ci, /fix-conflict, /fix-review
Issue Bootstrap/dev-issue <number> slash command bootstraps issue implementation in one step — fetches the issue from GitHub, generates a task brief, creates a feature branch (feat/<slug>-<number>), and spawns a Codex agent on it (#643)
Learning ModeTwo independent flags: SYNAPSE_LEARNING_MODE_ENABLED=true enables Prompt Improvement section; SYNAPSE_LEARNING_MODE_TRANSLATION=true enables JP-to-EN Learning section. Either flag activates learning.md injection and Tips. Response uses normal formatting (no separators); structured formatting (━━━ separators, section headers) applies only to feedback sections (Prompt Improvement, JP-to-EN Learning, Tips)
Proactive ModeSYNAPSE_PROACTIVE_MODE_ENABLED=true guides agents to use Synapse features (shared memory, canvas, file safety, delegation, broadcast) based on a task-size x feature matrix. Small tasks skip most features; medium tasks use them selectively; large tasks require full coordination. Per-feature skip conditions prevent unnecessary overhead. Follows the learning_mode pattern: env var activation + .synapse/proactive.md instruction file appended at startup. Off by default
Shared MemoryDeprecated — superseded by LLM Wiki (see below). User-global SQLite knowledge base (~/.synapse/memory.db) for cross-agent knowledge sharing. Agents save, search, and retrieve learned knowledge across sessions (synapse memory save/list/search/show/delete/stats). API endpoints at /memory/*. Enabled by default (SYNAPSE_SHARED_MEMORY_ENABLED=true). New knowledge should use synapse wiki instead. See Shared Memory vs LLM Wiki
LLM WikiKnowledge accumulation layer inspired by Karpathy's LLM Wiki pattern. Agents build and maintain a structured, interlinked Markdown knowledge base with frontmatter metadata, [[wikilink]] cross-references, and confidence scores. Two scopes: .synapse/wiki/ (project) and ~/.synapse/wiki/ (global). CLI: synapse wiki ingest/query/lint/status/refresh/init. Living Docs: pages track source_files and source_commit in frontmatter; lint/status detect stale pages when tracked files change; refresh --apply updates commit SHAs. Page types: entity, concept, decision, comparison, synthesis, learning. Canvas Knowledge view at #/knowledge; GET /api/wiki/graph returns a Mermaid diagram of page links. MCP instruction synapse://instructions/wiki. Config: wiki.enabled (default true). See LLM Wiki Design
Session Save/RestoreSave running team configurations as named snapshots and restore them later (synapse session save/list/show/restore/delete/sessions). session publish/import syncs snapshots through SYNAPSE_SHARED_SESSION_DIR for team handoff. Each agent's CLI conversation session_id is automatically captured and stored in the registry at startup. Restoring with --resume uses the saved session_id to resume each agent's conversation history, with an automatic 10-second timeout fallback if resume fails (see the Resume Mode section in the guide for details)
WorkflowDefine reusable YAML-based message sequences and execute them with synapse workflow run. Each workflow is a named list of steps (target, message, priority, response_mode). Supports --dry-run to preview, --continue-on-error for resilient execution, --auto-spawn for automatic agent spawning, and --async for background execution (returns run_id; check progress with synapse workflow status <run_id>). `target: self`: steps can target the calling agent itself; a helper agent is auto-spawned to avoid deadlock (nested workflow execution from helpers is forbidden, max depth 1). Bare-type targets respect caller CWD: target: claude resolves only to agents in the workflow runner's working directory, so it never dispatches to a same-type agent in a different project; combine with auto_spawn to start a fresh one when none exists (#568 / #645). Persistent execution history: completed runs are stored in SQLite (.synapse/workflow_runs.db) and survive server restarts; active runs are cached in memory with DB fallback. Workflow-level trigger and auto_spawn fields enable skill auto-generation: creating or syncing a workflow produces a SKILL.md (marked <!-- synapse-workflow-autogen -->) in .claude/skills/ and .agents/skills/, making workflows discoverable as slash-command skills. Use synapse workflow sync to regenerate all skills and remove orphans. Stored in .synapse/workflows/ (project) or ~/.synapse/workflows/ (user). See Workflow Self-Target
CanvasShared visual output surface for agents. Renders diagrams (Mermaid with theme-synced palettes), tables, charts, code, diffs, and 25 content formats in a browser UI. Enhanced markdown rendering with tables, blockquotes, ordered lists, and inline formatting via a built-in state-machine parser. Includes progress, terminal, dependency-graph, and cost card types. Supports 6 layout templates: briefing, comparison, dashboard, steps, slides, plan for structured multi-block cards. Plan Card template visualizes task plans with Mermaid DAG + step list, status tracking (proposed/active/completed/cancelled). Task card expand/collapse state persists across dashboard polling updates. HTML Artifact Support: format: "html" sandboxed iframes with parent-iframe theme sync (CSS variables --bg, --fg, --border via postMessage), auto-resize (ResizeObserver), dark mode CSS, and full document normalization (extracts head/body from <!doctype html> documents). CLI shortcuts: synapse canvas mermaid/markdown/table/chart/briefing/plan/.... Server: synapse canvas serve (port 3000). Agent Control: interactive Agent Control tab (formerly "Admin") for sending messages to agents, viewing responses, and managing the fleet from the browser. Agent selection via clickable table rows (double-click to jump to agent's terminal, right-click context menu with Kill Agent action and confirm modal), multi-line textarea with Cmd+Enter, IME support, multi-artifact response extraction, terminal junk stripping. Card Download: export any card via GET /api/cards/{card_id}/download?format={format} — all 25 content formats map to optimal download formats (Markdown, JSON, CSV, HTML, native); 6 templates export as Markdown/JSON. Download buttons in card grid headers and Spotlight title bar. Clipboard Copy: copy any card as Markdown to the clipboard via the copy button (reuses the download endpoint with ?format=md); available in both card grid headers and Spotlight view. Spotlight navigation: keyboard shortcuts (ArrowLeft/Right to navigate cards, Escape to exit manual navigation and return to live/latest mode), spotlight-swap animations, template badge in title bar, minimal info bar mode, and mobile-responsive layout. DB Browser: sidebar tree + paginated table view for inspecting Synapse SQLite databases (/api/db/list, /api/db/{db}/{table} endpoints; task_board.db is excluded). Dashboard: responsive auto-fit grid layout. Accessibility: agent panel uses role=button, tabindex, aria-expanded, and focus-visible styling. Sidebar menu: Canvas, History, Dashboard, Agent Control, Workflow, Database, Harnesses (landing) / Skills (tree-table of discovered skills at #/harnesses/skills; two-level hierarchy: User Global (subdivided by agent harness: Claude Code .claude/skills/** vs shared .agents/skills/**) → Projects (per-directory, further split by agent bucket when applicable) → Synapse Central Store; columns NAME / DESCRIPTION / LOCATION; collapsible with incremental name filter) / MCP Servers (tree-table of configured MCP servers at #/harnesses/mcp; two-level hierarchy: User Global (subdivided per agent: Claude Code ~/.claude.json, Codex ~/.codex/config.toml TOML, Gemini ~/.gemini/settings.json, OpenCode ~/.config/opencode/opencode.json, Claude Desktop) → Projects (per .mcp.json; projects without one render as a dashed-folder "no .mcp.json" row so scanned-but-unconfigured is distinguished from not-seen); columns NAME / COMMAND / DETAILS where DETAILS shows transport type and env:KEY chips — env values are never sent to the browser), System. See Canvas Design, Admin Command Center
Smart Suggestanalyze_task MCP tool analyzes user prompts and returns a delegation_strategy (self, subagent, or spawn) along with rich context (diff_stats, file_conflicts, dependencies, parallelizable) and a recommended_worktree field (true when spawn strategy or high file conflicts detected). Accepts optional files and agent_type params. When collaboration would be beneficial, suggests team/task splits displayed as Plan Cards on Canvas. Trigger conditions (file count, multi-directory changes, missing tests, prompt complexity, keywords) are configurable via .synapse/suggest.yaml. See Smart Suggest Design (Japanese)
Proactive CollaborationAgents automatically evaluate collaboration opportunities before starting tasks. Built-in decision framework: do-it-yourself, delegate, ask-for-help, report-progress, share-knowledge. Cross-model spawning preference distributes token usage and avoids rate limits. Worker agents can also spawn/delegate (not just managers). Mandatory cleanup of spawned agents (synapse kill <name> -f)
Self-Learning PipelineObservation layer captures PTY and A2A signals into .synapse/observations.db. synapse learn analyzes repeated patterns and persists instincts (.synapse/instincts.db). synapse instinct lists/promotes learned instincts. synapse evolve clusters instincts into reusable skill candidates. Pipeline: Observation → Pattern Analyzer → Instinct → Evolve. Env: SYNAPSE_OBSERVATION_ENABLED (default true), SYNAPSE_OBSERVATION_DB_PATH, SYNAPSE_INSTINCT_DB_PATH
MCP Bootstrapsynapse mcp serve exposes bootstrap resources (instructions, settings, agent card) and tools (bootstrap_agent, list_agents, analyze_task, canvas_post) via the Model Context Protocol over stdio. Lets MCP-capable agents pull Synapse context with a minimal PTY startup bootstrap instead of the full initial instruction payload. canvas_post lets MCP clients publish Canvas cards without shell escaping. When a Synapse MCP server config entry is detected, Synapse sends a short MCP bootstrap message at startup and keeps approval prompts enabled unless the session is resumed; non-Synapse MCP entries do not trigger this path. Copilot MCP config: ~/.copilot/mcp-config.json. See MCP Bootstrap Design (Japanese)
Multi-Agent PatternsDeclarative coordination patterns that define how agents should behave rather than what to do (contrast with imperative Workflows). Five built-in pattern types: generator-verifier (generate + verify against criteria), orchestrator-subagent (decompose and delegate), agent-teams (parallel workers on a task queue), message-bus (pub/sub event-driven coordination), shared-state (agents collaborate via shared wiki). CLI: synapse multiagent init/list/show/run/status/stop (alias synapse map). Pattern configs stored in .synapse/patterns/ (project) or ~/.synapse/patterns/ (user). Canvas integration: Pattern tab with list/detail views at /api/multiagent endpoints. --dry-run to preview, --async for background execution

Prerequisites

  • OS: macOS / Linux (Windows via WSL2 recommended)
  • Python: 3.10+
  • CLI Tools: Pre-install and configure the agents you want to use:

- Claude Code - Codex CLI - Gemini CLI - OpenCode - GitHub Copilot CLI


Installation

1. Install Synapse A2A

<details> <summary><b>macOS / Linux / WSL2 (recommended)</b></summary>

bash
# pipx (recommended)
pipx install synapse-a2a

# Or run directly with uvx (no install)
uvx synapse-a2a claude

</details>

<details> <summary><b>Windows</b></summary>

WSL2 is strongly recommended. Synapse A2A uses pty.spawn() which requires a Unix-like terminal.

bash
# Inside WSL2 — same as Linux
pipx install synapse-a2a

# Scoop (experimental, WSL2 still required for pty)
scoop bucket add synapse-a2a https://github.com/s-hiraoku/scoop-synapse-a2a
scoop install synapse-a2a

</details>

<details> <summary><b>Developer (from source)</b></summary>

bash
# Install with uv
uv sync

# Or pip (editable)
pip install -e .

</details>

With gRPC support:

bash
pip install "synapse-a2a[grpc]"

2. Install Skills (Recommended)

Installing skills is strongly recommended to get the most out of Synapse A2A.

Skills help Claude automatically understand Synapse A2A features: @agent messaging, File Safety, and more.

bash
# Requires GitHub CLI 2.90.0+
# https://github.blog/changelog/2026-04-16-manage-agent-skills-with-github-cli/
gh skill install s-hiraoku/synapse-a2a synapse-a2a
gh skill install s-hiraoku/synapse-a2a synapse-manager
# Pin a release: gh skill install s-hiraoku/synapse-a2a synapse-a2a --pin v0.26.4
# Target a specific agent runtime: ... --agent claude-code

See Skills for details and `docs/skills-management.md` for the full migration matrix. The legacy npx skills add ... / skills.sh path still works but is no longer the recommended way to install — use gh skill install for version pinning and provenance tracking.

3. Start Agents

bash
# Terminal 1: Claude
synapse claude

# Terminal 2: Codex
synapse codex

# Terminal 3: Gemini
synapse gemini

# Terminal 4: OpenCode
synapse opencode

# Terminal 5: GitHub Copilot CLI
synapse copilot

Note: If terminal scrollback display is garbled, try:

```bash

uv run synapse gemini

# or

uv run python -m synapse.cli gemini

```

Ports are auto-assigned:

AgentPort Range
Claude8100-8109
Gemini8110-8119
Codex8120-8129
OpenCode8130-8139
Copilot8140-8149

4. Inter-Agent Communication

Use synapse send to send messages between agents. The --from flag is optional -- Synapse auto-detects the sender from SYNAPSE_AGENT_ID (set at startup):

bash
synapse send codex "Please review this design"
synapse send gemini "Suggest API improvements"

For multiple instances of the same type, use type-port format:

bash
synapse send codex-8120 "Handle this task"
synapse send codex-8121 "Handle that task"

5. HTTP API

bash
# Send message
curl -X POST http://localhost:8100/tasks/send \
  -H "Content-Type: application/json" \
  -d '{"message": {"role": "user", "parts": [{"type": "text", "text": "Hello!"}]}}'

# Emergency stop (Priority 5)
curl -X POST "http://localhost:8100/tasks/send-priority?priority=5" \
  -H "Content-Type: application/json" \
  -d '{"message": {"role": "user", "parts": [{"type": "text", "text": "Stop!"}]}}'

Use Cases

1. Instant Specification Lookup (Simple)

While coding with Claude, quickly query Gemini (better at web search) for the latest library specs or error info without context switching.

bash
# In Claude's terminal:
synapse send gemini "Summarize the new f-string features in Python 3.12"

2. Cross-Review Designs (Intermediate)

Get feedback on your design from agents with different perspectives.

bash
# After Claude drafts a design:
synapse send gemini "Critically review this design from scalability and maintainability perspectives"

3. TDD Pair Programming (Intermediate)

Separate "test writer" and "implementer" for robust code.

bash
# Terminal 1 (Codex):
Create unit tests for auth.py - normal case and token expiration case.

# Terminal 2 (Claude):
synapse send codex-8120 "Implement auth.py to pass the tests you created"

4. Security Audit (Specialized)

Have an agent with a security expert role audit your code before committing.

bash
# Give Gemini a role:
You are a security engineer. Review only for vulnerabilities (SQLi, XSS, etc.)

# After writing code:
synapse send gemini "Audit the current changes (git diff)"

5. Auto-Fix from Error Logs (Advanced)

Pass error logs to an agent for automatic fix suggestions.

bash
# Tests failed...
pytest > error.log

# Ask agent to fix
synapse send claude "Read error.log and fix the issue in synapse/server.py"

6. Language/Framework Migration (Advanced)

Distribute large refactoring work across agents.

bash
# Terminal 1 (Claude):
Read legacy_api.js and create TypeScript type definitions

# Terminal 2 (Codex):
synapse send claude "Use the type definitions you created to rewrite legacy_api.js to src/new_api.ts"

7. Proactive Collaboration with Cross-Model Spawning (Advanced)

Agents proactively assess when to delegate, spawn helpers, or share knowledge. The collaboration framework encourages cross-model spawning to distribute token usage across providers and avoid rate limits.

bash
# Manager spawns a different model type for a subtask (cross-model preference)
synapse spawn gemini --worktree --name Tester --role "test writer"

# Spawn on a specific branch (--branch auto-enables --worktree)
synapse spawn codex --branch renovate/major-eslint-monorepo --name Fixer --role "dependency updater"

# Spawn + send task in one step (polls for READY then auto-sends)
synapse spawn gemini --worktree --name Tester --role "test writer" \
  --task "Write integration tests for auth module" --notify

# Or delegate manually after spawn (prefer --notify over --wait)
synapse send Tester "Write integration tests for auth module" --notify

# Share discoveries via LLM Wiki for all agents to use
synapse wiki ingest docs/auth-pattern.md --scope project

# Merge worktree branch without stopping the agent (integrate intermediate results)
synapse merge Tester

# MANDATORY: Always clean up agents you spawn (worktree branches auto-merge back)
synapse kill Tester -f
# Skip auto-merge if you want to review the branch first
synapse kill Tester -f --no-merge

Key principles:

  • Cross-model preference: Spawn different model types (Claude, Gemini, Codex) to leverage diverse strengths and distribute rate limit pressure
  • Worker autonomy: Any agent can spawn helpers and delegate, not just managers
  • Check before spawning: Run synapse list first to reuse existing READY agents before spawning new ones
  • Mandatory cleanup: Always synapse kill <name> -f agents you spawned after their work completes. Worktree branches are auto-merged; use --no-merge to skip
  • Feature usage: Actively use LLM Wiki, file safety, worktree, broadcast, and history

8. Cross-Worktree Knowledge Transfer (Advanced)

Share skills, config, or investigation results with agents running in different worktrees. Synapse automatically detects worktree relationships (parent, child, and sibling worktrees of the same repo), so --force is not needed for related worktree agents. Use --message-file for messages containing backticks or code blocks to avoid shell expansion issues.

bash
# Spawn a worker in its own worktree
synapse spawn codex --worktree feature-api --name Cody --role "API implementation"

# Spawn on a non-main base branch (--branch auto-enables --worktree)
synapse spawn codex --worktree feature-api --branch develop --name Cody --role "API implementation"

# Write instructions to a file (avoids shell expansion of backticks)
cat > /tmp/instructions.md << 'EOF'
## /release skill usage
Run `/release patch` to bump the patch version.
EOF

# Send across worktree boundaries (no --force needed for related worktrees)
synapse send Cody --message-file /tmp/instructions.md --silent

Alternatives: --attach sends files without needing --message-file. synapse memory save is directory-agnostic and works across all agents.

Comparison with SSH Remote

OperationSSHSynapse
Manual CLI operation
Programmatic task submission△ requires expect etc.◎ HTTP API
Multiple simultaneous clients△ multiple sessions◎ single endpoint
Real-time progress notifications◎ SSE/Webhook
Automatic inter-agent coordination◎ synapse send

Note: SSH is often sufficient for individual CLI use. Synapse shines when you need automation, coordination, and multi-agent collaboration.


Skills

Installing skills is strongly recommended when using Synapse A2A with Claude Code.

Why Install Skills?

With skills installed, Claude automatically understands and executes:

  • synapse send: Inter-agent communication via synapse send codex "Fix this" (sender auto-detected)
  • Priority control: Message sending with Priority 1-5 (5 = emergency stop)
  • File Safety: Prevent multi-agent conflicts with file locking and change tracking
  • History management: Search, export, and statistics for task history

Installation

Install via the GitHub CLI (requires `gh` 2.90.0+):

bash
# Install core skills from this repository
gh skill install s-hiraoku/synapse-a2a synapse-a2a
gh skill install s-hiraoku/synapse-a2a synapse-manager

# Pin to a release tag so updates are explicit
gh skill install s-hiraoku/synapse-a2a synapse-a2a --pin v0.26.4

# Install for a specific agent runtime
gh skill install s-hiraoku/synapse-a2a synapse-a2a --agent claude-code
gh skill install s-hiraoku/synapse-a2a synapse-a2a --agent copilot

# Preview a skill before installing
gh skill preview s-hiraoku/synapse-a2a synapse-a2a

# Check for upstream changes on installed skills
gh skill update

Each installed skill's SKILL.md frontmatter records the source repository, ref, and tree SHA, so gh skill update can detect drift and --pin gives you a deterministic version.

Legacy pathnpx skills add s-hiraoku/synapse-a2a (skills.sh) still works for older gh installs, but gh skill is the recommended tool going forward. See `docs/skills-management.md` for the migration matrix.

Included Skills

SkillDescription
synapse-a2aComprehensive guide for inter-agent communication: synapse send, priority, A2A protocol, history, File Safety, settings
synapse-managerMulti-agent management workflow: task delegation, progress monitoring, quality verification with regression testing, feedback delivery, cross-review orchestration, worker agent guide, and mandatory cleanup enforcement
check-ciCheck CI status, merge conflict state, and CodeRabbit review status for the current PR (/check-ci, /check-ci --fix)
fix-ciAuto-diagnose and fix CI failures: lint, format, type-check, test errors
fix-conflictAuto-resolve merge conflicts: fetch base, test merge, analyze both sides, resolve, verify, push
fix-reviewAuto-fix CodeRabbit review comments: classify by severity (Bug/Style/Suggestion), apply fixes, verify, push
dev-issue/dev-issue <number> — Bootstrap issue implementation in one step: fetch the issue, generate a task brief, create a feature branch, and spawn a Codex agent on it

Core Skills: Essential skills like synapse-a2a are automatically deployed to agent directories on startup (best-effort) to ensure basic quality even if skill sets are skipped.

Skill Management

Synapse includes a built-in skill manager with a central store (~/.synapse/skills/) for organizing and deploying skills across agents.

ScopeLocationDescription
Synapse~/.synapse/skills/Central store (deploy to agents from here)
User~/.claude/skills/, ~/.agents/skills/, etc.User-wide skills
Project./.claude/skills/, ./.agents/skills/, etc.Project-local skills
Plugin./plugins/*/skills/Read-only plugin skills
bash
# Interactive TUI
synapse skills

# List and browse
synapse skills list                          # All scopes
synapse skills list --scope synapse          # Central store only
synapse skills show <name>                   # Skill details

# Manage
synapse skills delete <name> [--force]
synapse skills move <name> --to <scope>

# Central store operations
synapse skills import <name>                 # Import from agent dirs to ~/.synapse/skills/
synapse skills deploy <name> --agent claude,codex --scope user
synapse skills add <repo>                    # Install from repo (legacy wrapper; prefer `gh skill install`)
synapse skills create [name]                 # Create a skill template
synapse skills create [name] --launch-agent  # Spawn an agent to finish it with anthropic-skill-creator

# Skill sets (named groups)
synapse skills set list
synapse skills set show <name>
synapse skills apply <target> <set_name>     # Apply skill set to running agent
synapse skills apply <target> <set_name> --dry-run  # Preview changes without applying

Synapse ships with 6 built-in skill sets (defined in .synapse/skill_sets.json):

Skill SetDescriptionSkills
architectSystem architecture and design — design docs, API contracts, code reviewsynapse-a2a, system-design, api-design, code-review, project-docs
developerImplementation and quality — test-first development, refactoring, code simplificationsynapse-a2a, test-first, refactoring, code-simplifier, agent-memory
reviewerCode review and security — structured reviews, security audits, code simplificationsynapse-a2a, code-review, security-audit, code-simplifier
frontendFrontend development — React/Next.js performance, component composition, design systems, accessibilitysynapse-a2a, react-performance, frontend-design, react-composition, web-accessibility
managerMulti-agent management — task delegation, progress monitoring, quality verification, cross-review orchestration, re-instructionsynapse-a2a, synapse-manager, task-planner, agent-memory, code-review, synapse-reinst
documentationDocumentation expert — audit, restructure, synchronize, and maintain project documentationsynapse-a2a, project-docs, api-design, agent-memory

Directory Structure

text
plugins/
└── synapse-a2a/
    ├── .claude-plugin/plugin.json
    ├── .codex-plugin/plugin.json
    ├── README.md
    └── skills/
        ├── synapse-a2a/
        │   ├── SKILL.md
        │   └── references/          # api, collaboration, commands, examples, features, file-safety, messaging, spawning
        └── synapse-manager/
            ├── SKILL.md
            ├── references/          # auto-approve-flags, commands-quick-ref, features-table, worker-guide
            └── scripts/             # wait_ready.sh, check_team_status.sh, regression_triage.sh

See plugins/synapse-a2a/README.md for details.

Codex can discover the repo-local plugin through .agents/plugins/marketplace.json. Gemini can use the expanded skills in the .agents/skills/ directory.


Documentation


Architecture

A2A Server/Client Structure

In Synapse, each agent operates as an A2A server. There's no central server; it's a P2P architecture.

code
┌─────────────────────────────────────┐    ┌─────────────────────────────────────┐
│  synapse claude (port 8100)         │    │  synapse codex (port 8120)          │
│  ┌───────────────────────────────┐  │    │  ┌───────────────────────────────┐  │
│  │  FastAPI Server (A2A Server)  │  │    │  │  FastAPI Server (A2A Server)  │  │
│  │  /.well-known/agent.json      │  │    │  │  /.well-known/agent.json      │  │
│  │  /tasks/send                  │◄─┼────┼──│  A2AClient                    │  │
│  │  /tasks/{id}                  │  │    │  └───────────────────────────────┘  │
│  └───────────────────────────────┘  │    │  ┌───────────────────────────────┐  │
│  ┌───────────────────────────────┐  │    │  │  PTY + Codex CLI              │  │
│  │  PTY + Claude CLI             │  │    │  └───────────────────────────────┘  │
│  └───────────────────────────────┘  │    └─────────────────────────────────────┘
└─────────────────────────────────────┘

Each agent is:

  • A2A Server: Accepts requests from other agents
  • A2A Client: Sends requests to other agents

Key Components

ComponentFileRole
FastAPI Serversynapse/server.pyProvides A2A endpoints
A2A Routersynapse/a2a_compat.pyA2A protocol endpoints and PTY bridging
A2A Modelssynapse/a2a_models.pyPydantic data models for A2A messages and tasks
TaskStoresynapse/task_store.pyIn-memory task persistence and status tracking
A2A Clientsynapse/a2a_client.pyCommunication with other agents
TerminalControllersynapse/controller.pyPTY management, READY/PROCESSING detection
Shellsynapse/shell.pyInteractive shell with @Agent pattern routing
AgentRegistrysynapse/registry.pyAgent registration and lookup
Worktreesynapse/worktree.pySynapse-native git worktree isolation for all agents
FileSafetysynapse/file_safety.pyMulti-agent file locking and change tracking
SkillManagersynapse/skills.pySkill discovery, deploy, import, skill sets
Commandssynapse/commands/CLI command handlers (extracted from cli.py)
SkillManagerCmdsynapse/commands/skill_manager.pySkill management TUI and CLI
AgentProfileStoresynapse/agent_profiles.pySaved agent definitions (reusable templates for spawn)
WorkflowRunDBsynapse/workflow_db.pySQLite persistence for workflow execution history
WorkflowRunnersynapse/workflow_runner.pyStep-by-step workflow executor
Observationsynapse/observation.pyPTY/A2A signal capture for self-learning pipeline
PatternAnalyzersynapse/pattern_analyzer.pyObservation pattern analysis
Instinctsynapse/instinct.pyLearned instinct persistence
Transportsynapse/transport.pyTransport abstraction layer
Canvassynapse/canvas/Shared visual output surface (server, protocol, store, export, routes)
Patternssynapse/patterns/Multi-agent coordination patterns (base, store, runner)
MultiagentCmdsynapse/commands/multiagent.pyCLI handlers for synapse multiagent / synapse map
MCP Serversynapse/mcp/MCP bootstrap resource server (instructions, settings, agent card)

Responsibility Boundaries

Synapse keeps the runtime split into four dependency layers. Lower layers do not import higher layers.

mermaid
flowchart TB
    Core["Core: A2A protocol, task lifecycle, status"]
    Adapters["Adapters: claude/codex/gemini profiles and HTTP wrappers"]
    Runtime["Runtime: CLI, PTY controller, registry, worktrees"]
    Extensions["Extensions: Canvas, skills, hooks, workflows, self-learning"]

    Extensions --> Runtime
    Runtime --> Adapters
    Adapters --> Core

The practical rule is: protocol/task code stays in a2a_*, task_store.py, status.py, and transport.py; provider-specific behavior lives in profile/adaptor modules; PTY and process orchestration stay in runtime modules; optional capabilities build on top through synapse/commands/, synapse/canvas/, workflow, hooks, and skills.

Startup Sequence

mermaid
sequenceDiagram
    participant Synapse as Synapse Server
    participant Registry as AgentRegistry
    participant PTY as TerminalController
    participant CLI as CLI Agent

    Synapse->>Registry: 1. Register agent (agent_id, pid, port)
    Synapse->>PTY: 2. Start PTY
    PTY->>CLI: 3. Start CLI agent
    Synapse->>PTY: 4. Send minimal bootstrap message (sender: synapse-system)
    PTY->>CLI: 5. AI retrieves system context via Agent Card (x-synapse-context)

Communication Flow

mermaid
sequenceDiagram
    participant User
    participant Claude as Claude (8100)
    participant Client as A2AClient
    participant Codex as Codex (8120)

    User->>Claude: @codex Review this design
    Claude->>Client: send_to_local()
    Client->>Codex: POST /tasks/send-priority
    Codex->>Codex: Create Task → Write to PTY
    Codex-->>Client: {"task": {"id": "...", "status": "working"}}
    Client-->>Claude: [→ codex] Send complete

CLI Commands

Basic Operations

bash
# Start agent (foreground)
synapse claude
synapse codex
synapse gemini
synapse opencode
synapse copilot

# Start with custom name and role
synapse claude --name my-claude --role "code reviewer"

# Start with saved agent definition (--agent / -A)
synapse claude --agent calm-lead
synapse claude -A Claud                           # Short flag, lookup by display name

# Skip interactive name/role setup
synapse claude --no-setup

# Specify port
synapse claude --port 8105

# Pass arguments to CLI tool
synapse claude -- --resume

Agent Naming

Assign custom names and roles to agents for easier identification and management:

bash
# Interactive setup (default when starting agent)
synapse claude
# → Prompts for name and role

# Skip interactive setup
synapse claude --no-setup

# Set name and role via CLI options
synapse claude --name my-claude --role "code reviewer"

# Load role from file (@prefix reads file content)
synapse claude --name reviewer --role "@./roles/reviewer.md"

# Use saved agent definition (--agent / -A)
synapse claude --agent calm-lead
synapse claude -A Claud                           # Short flag

# After agent is running, change name/role
synapse rename synapse-claude-8100 --name my-claude --role "test writer"
synapse rename my-claude --role "documentation"  # Change role only
synapse rename my-claude --clear                 # Clear name and role

Once named, use the custom name for all operations:

bash
synapse send my-claude "Review this code"
synapse jump my-claude
synapse kill my-claude

Name vs ID:

  • Display/Prompts: Shows name if set, otherwise ID (e.g., Kill my-claude (PID: 1234)?)
  • Internal processing: Always uses Runtime ID (synapse-claude-8100)
  • Target resolution: Name has highest priority when matching targets

Save Prompt on Exit

When an interactive agent session exits, Synapse can prompt to save the current agent definition for reuse:

text
Save this agent definition for reuse? [y/N]:
  • Triggered only for interactive synapse <profile> sessions with a configured name.
  • Not shown in --headless mode or non-TTY environments.
  • Not shown for synapse stop ... or synapse kill ... (those commands only stop running processes).
  • Default scope is project, but switches to user when the session is running inside a worktree (issue #410). The prompt makes this explicit (default: user - project scope in a worktree is deleted on cleanup). When a worktree is cleaned up, any *.agent files saved under <worktree>/.synapse/agents/ are also copied back to the main repo's .synapse/agents/ as a safety net (main repo files win on collision).
  • Disable with SYNAPSE_AGENT_SAVE_PROMPT_ENABLED=false.

Command List

CommandDescription
synapse <profile>Start in foreground
synapse start <profile>Start in background
`synapse stop <profile\id>`Stop agent (can specify ID)
synapse kill <target>Graceful shutdown (sends shutdown request, then SIGTERM after 30s). Auto-merges worktree branch
synapse kill <target> -fForce kill (immediate SIGKILL). Auto-merges worktree branch
synapse kill <target> --no-mergeKill without auto-merging worktree branch
synapse cleanupKill orphan agents (children whose spawned_by parent crashed/cleared). --dry-run to preview, -f to skip prompt, optional positional agent id to target one. Set SYNAPSE_ORPHAN_IDLE_TIMEOUT=<sec> to opt into opportunistic cleanup of long-READY orphans on synapse list
synapse merge <agent>Merge worktree branch without killing the agent. --all for all agents, --dry-run to preview
synapse jump <target>Jump to agent's terminal
synapse send-keys <target> [data]Write raw input bytes into a running agent's PTY. Escape hatch for unsticking agents blocked on a TUI dialog (codex edit-confirmation, model picker, rate-limit dialog) without synapse jump. --enter appends \r, --no-escape disables unicode_escape decoding, --json emits the raw HTTP response. CLI wrapper for POST /pty/write (require_auth-gated, same trust model as /tasks/{id}/cancel / /permission/approve). #695, Refs #694
synapse rename <target>Assign name/role to agent
synapse set-summary <target> [text]Set persistent agent summary (120 chars). --auto generates from git context, --clear removes
synapse --versionShow version
synapse listList running agents (Rich TUI in alternate screen with auto-refresh, ↑↓/1-9 selection, Enter/j terminal jump, and k kill confirmation)
synapse list --plainForce one-shot plain-text output without entering the TUI
synapse list --jsonOutput agent list as JSON array (for AI/programmatic consumption)
synapse status <target>Show detailed agent status (info, current task, history, file locks). Supports --json
synapse logs <profile>Show logs
synapse send <target> <message>Send message
synapse interrupt <target> <message>Soft interrupt (shorthand for send -p 4 --silent). Supports --force to bypass working_dir check
`synapse reply [<message> \--fail <reason>]`Reply to the last received A2A message (use --fail for failure)
synapse trace <task_id>Show task history + file-safety cross-reference
synapse instructions showShow instruction content
synapse instructions filesList instruction files
synapse instructions sendResend initial instructions
synapse history listShow task history
synapse history show <task_id>Show task details
synapse history searchKeyword search
synapse history cleanupDelete old data
synapse history statsShow statistics
synapse history exportExport to JSON/CSV
synapse file-safety statusShow file safety statistics
synapse file-safety locksList active locks
synapse file-safety lockLock a file
synapse file-safety unlockRelease lock
synapse file-safety historyFile change history
synapse file-safety recentRecent changes
synapse file-safety recordManually record change
synapse file-safety cleanupDelete old data
synapse file-safety debugShow debug info
synapse waiting-debug collectAppend /debug/waiting snapshots from every running agent to ~/.synapse/waiting_debug.jsonl (Phase 1.5 collection pipeline). --out <path> overrides the destination, --agent <id> filters to one agent, --include-empty records empty attempts, --timeout <seconds> sets the per-agent HTTP timeout (default 5.0, v0.28.2). See `docs/phase15-collection.md`
synapse waiting-debug reportSummarise a waiting_debug.jsonl file: per-profile / pattern_source / path_used counts, confidence distribution, idle_gate_drops, renderer_unavailable_agents. Accepts --since <iso>, --agent <id>, --json, --out <path> (write JSON to file; stdout stays empty, safe for cron)
synapse watchdog checkOne-shot stuck-agent detection across all live agents (Stage 1 MVP, #646). Prints a table with ID / STATUS / UPTIME / SAME_STATUS_FOR / LAST_OUTBOUND / ALARM. Heuristics: RATE_LIMITED > 30m, SENDING_REPLY > 60s, codex CLI rate-limit dialog visible while WAITING (alarm rate_limit_dialog, #691), codex CLI edit-confirmation dialog visible while WAITING (alarm edit_confirmation_dialog, #707), PROCESSING > 30m with no outbound A2A in the last 10m, and "spawn never ready" (registered > 60s ago, < 5m, status != READY). --alarm-only filters to alarm rows; --json emits an array of reports for programmatic consumers. Stage 2-4 (background daemon, push notifications, multi-watchdog locking, automatic recovery) are future work
synapse skillsSkill Manager (interactive TUI)
synapse skills listList discovered skills
synapse skills show <name>Show skill details
synapse skills delete <name>Delete a skill
synapse skills move <name>Move skill to another scope
synapse skills deploy <name>Deploy skill from central store to agent dirs
synapse skills import <name>Import skill to central store (~/.synapse/skills/)
synapse skills add <repo>Install skill from repository (legacy wrapper; prefer gh skill install <repo> <skill>)
synapse skills create [name]Create new skill template. Add `--launch-agent [--agent claudecodexgemini] to deploy anthropic-skill-creator` and spawn an agent with the right starter task
synapse skills set listList skill sets
synapse skills set show <name>Show skill set details
synapse skills apply <target> <set_name>Apply skill set to running agent (--dry-run to preview)
synapse configSettings management (interactive TUI)
synapse config showShow current settings
synapse doctorRun health checks; also detects orphan port listeners in the managed range and stale UDS sockets
synapse doctor --cleanTerminate orphan listeners and remove stale sockets (prompts per orphan; -y to skip prompts)
synapse doctor --strictExit 1 when orphan listeners or stale sockets are present (for CI / scripts)
synapse worktree pruneRemove orphan worktrees whose directories no longer exist but whose git refs remain
synapse approve <task_id>Approve a plan
synapse reject <task_id>Reject a plan with reason
synapse team startLaunch agents (1st=handoff, rest=new panes). Defaults to --worktree isolation; opt out with --no-worktree. --all-new for all new panes
`synapse spawn <profile\saved-agent>`Spawn a single agent in a new terminal pane. Auto-tiles panes when 2+ agents are spawned. Accepts saved agent IDs/names. --worktree / -w for Synapse-native worktree isolation (all agents). --branch / -b auto-enables --worktree and sets the base branch (default: origin/main). --no-worktree to opt out. --task "msg" / --task-file path to auto-send a task after READY. Recommended: --task-file <path> --task-timeout 600 --notify
synapse merge <agent>Merge a worktree agent's branch into the current branch. --all to merge all worktree agents. --dry-run to preview. --resolve-with <agent> to delegate conflict resolution (Phase 2)
synapse agents listList saved agent definitions
synapse agents show <id_or_name>Show details for a saved agent
synapse agents add <id>Add or update a saved agent definition (requires --name, --profile)
synapse agents set <profile>Set .synapse/agents.json defaults for synapse <profile> startup
synapse agents unset <profile>Remove an agents.json profile default
synapse agents rolesList Markdown role templates from .synapse/roles and ~/.synapse/roles
synapse agents delete <id_or_name>Delete a saved agent by ID or name
synapse session save <name>Save running agents as a named session snapshot (captures session_id for resume)
synapse session listList saved sessions
synapse session show <name>Show session details (includes session_id per agent)
synapse session publish <name>Publish a saved session JSON to SYNAPSE_SHARED_SESSION_DIR for team handoff
synapse session import <name>Import a shared session JSON into the local project/user session store
synapse session restore <name>Restore a saved session (spawns agents). Use --resume to resume each agent's CLI conversation
synapse session delete <name>Delete a saved session
synapse workflow create <name>Create a workflow template YAML
synapse workflow listList saved workflows
synapse workflow show <name>Show workflow details
synapse workflow run <name>Execute workflow steps sequentially (--dry-run to preview, --async for background execution returning a run_id)
synapse workflow status <run_id>Show workflow run status
synapse workflow syncRe-generate skills from all workflow YAMLs (removes orphans)
synapse workflow delete <name>Delete a saved workflow
synapse mcp serveStart MCP bootstrap server over stdio (options auto-resolved from $SYNAPSE_AGENT_ID). Exposes bootstrap_agent, list_agents, analyze_task, and canvas_post tools
synapse canvas serveStart Canvas server (auto-opens browser, port 3000). --no-open to suppress browser open
synapse canvas statusShow Canvas server status (version, PID, asset hash match, STALE warning)
synapse canvas stopStop Canvas server (health-check with identity + process verification, SIGKILL escalation, PID fallback). --port/-p to specify port
synapse canvas restartRestart Canvas server on the same port (stop + serve). --no-open to skip browser open. Use this to pick up updated HTML/JS assets that are cached at startup
synapse canvas mermaid <body>Post Mermaid diagram card
synapse canvas markdown <body>Post Markdown card
synapse canvas table <json>Post table card
synapse canvas chart <json>Post Chart.js card
synapse canvas code <body>Post syntax-highlighted code card
synapse canvas html <body>Post raw HTML card (sandboxed iframe with theme sync, auto-resize, and full document normalization)
synapse canvas diff <body>Post side-by-side diff card
synapse canvas image <url>Post image card
synapse canvas briefing <json>Post briefing template card (structured report with sections). Supports --file
synapse canvas plan <json>Post Plan Card template (Mermaid DAG + step list with status tracking). Supports --file. See Smart Suggest Design
synapse canvas post-raw <json>Post raw Canvas Message Protocol JSON (supports all templates, typed bodies, and block-level metadata such as x_title / x_filename)
synapse canvas post progress <json>Post progress bar card ({current, total, label, steps, status})
synapse canvas post terminal <string>Post terminal output card (supports ANSI escape codes)
synapse canvas post dependency-graph <json>Post dependency graph card ({nodes, edges}, rendered via Mermaid)
synapse canvas post cost <json>Post token/cost aggregation table ({agents, total_cost, currency})
synapse canvas link <url>Post link preview card (OGP-enriched embed with title, description, image)
synapse canvas listList cards (--mine, --search, --type)
synapse canvas delete <card_id>Delete a card
synapse canvas clearClear all cards (--agent to filter)
synapse learnAnalyze observations and persist learned instincts
synapse instinctList learned instincts (filters: --scope, --domain, --min-confidence)
synapse instinct promote <id>Promote a project-scoped instinct to global scope
synapse evolveDiscover skill candidates from learned instincts (--generate to write skill files)
synapse multiagent init <type>Create a new multi-agent pattern template YAML. Types: generator-verifier, orchestrator-subagent, agent-teams, message-bus, shared-state. --name, --user for user scope, --force to overwrite
synapse multiagent listList saved multi-agent patterns (--user / --project to filter scope)
synapse multiagent show <name>Show pattern YAML details
synapse multiagent run <name> <task>Execute a saved pattern (--dry-run to preview, --async for background)
synapse multiagent status <run_id>Show status of a pattern run
synapse multiagent stop <run_id>Stop a running pattern execution
synapse mapAlias for synapse multiagent

Resume Mode

When resuming an existing session, use these flags to skip initial instruction sending (A2A protocol explanation), keeping your context clean:

bash
# Resume Claude Code session
synapse claude -- --resume

# Resume Gemini with history
synapse gemini -- --resume=5

# Codex uses 'resume' as a subcommand (not --resume flag)
synapse codex -- resume --last

Default flags (customizable in settings.json):

  • Claude: --resume, --continue, -r, -c
  • Gemini: --resume, -r
  • Codex: resume
  • OpenCode: --continue, -c
  • Copilot: --continue, --resume

Instruction Management

Manually resend initial instructions when they weren't sent (e.g., after --resume mode):

bash
# Show instruction content
synapse instructions show claude

# List instruction files
synapse instructions files claude

# Send initial instructions to running agent
synapse instructions send claude

# Preview before sending
synapse instructions send claude --preview

# Send to specific Runtime ID
synapse instructions send synapse-claude-8100

Useful when:

  • You need A2A protocol info after starting with --resume
  • Agent lost/forgot instructions and needs recovery
  • Debugging instruction content

External Agent Management

bash
# Register external agent
synapse external add http://other-agent:9000 --alias other

# List
synapse external list

# Send message
synapse external send other "Process this task"

Task History Management

Search, browse, and analyze past agent execution results.

Note: History is enabled by default since v0.3.13. To disable:

bash
# Disable via environment variable
export SYNAPSE_HISTORY_ENABLED=false
synapse claude
bash
# Show latest 50 entries
synapse history list

# Filter by agent
synapse history list --agent claude

# Custom limit
synapse history list --limit 100

# Show task details
synapse history show task-id-uuid

Search input/output fields by keyword:

bash
# Single keyword
synapse history search "Python"

# Multiple keywords (OR logic)
synapse history search "Python" "Docker"

# AND logic (all keywords must match)
synapse history search "Python" "function" --logic AND

# With agent filter
synapse history search "Python" --agent claude

# Limit results
synapse history search "error" --limit 20
bash
# Overall stats (total, success rate, per-agent breakdown)
synapse history stats

# Specific agent stats
synapse history stats --agent claude

When token usage data is available (collected via synapse/token_parser.py), synapse history stats displays a TOKEN USAGE section with aggregated input/output tokens and estimated cost per agent.

bash
# JSON export (stdout)
synapse history export --format json

# CSV export
synapse history export --format csv

# Save to file
synapse history export --format json --output history.json
synapse history export --format csv --agent claude > claude_history.csv
bash
# Delete data older than 30 days
synapse history cleanup --days 30

# Keep database under 100MB
synapse history cleanup --max-size 100

# Force (no confirmation)
synapse history cleanup --days 30 --force

# Dry run
synapse history cleanup --days 30 --dry-run

Storage:

  • SQLite database: ~/.synapse/history/history.db (user-global)
  • Stored: task ID, agent name, input, output, status, metadata
  • Auto-indexed: agent_name, timestamp, task_id

Settings:

  • Enabled by default (v0.3.13+)
  • Disable: SYNAPSE_HISTORY_ENABLED=false

synapse send Command (Recommended)

Use synapse send for inter-agent communication. Works in sandboxed environments.

bash
synapse send <target> "<message>" [--from <sender>] [--priority <1-5>] [--wait | --notify | --silent]

Target Formats:

FormatExampleDescription
Custom namemy-claudeHighest priority, match name in registry
Full Runtime IDsynapse-claude-8100Match exact Runtime ID
Type-portclaude-8100Match type and port shorthand
Agent typeclaudeOnly works when single instance of type exists

When multiple agents of the same type are running, type-only (e.g., claude) will error. Use claude-8100 or synapse-claude-8100.

Options:

OptionShortDescription
--from-fSender Runtime ID (optional; auto-detected from SYNAPSE_AGENT_ID)
--priority-pPriority 1-4: normal, 5: emergency stop (sends SIGINT)
--message-file-FRead message from a file (- for stdin). Skips shell-expansion warnings for backticks/code blocks
--task-file-TRead message from a task file (- for stdin). Equivalent to --message-file; use when the content is a task specification (Markdown, etc.)
--stdin-Read message from stdin
--wait-Synchronous blocking - wait for receiver to reply with synapse reply
--notify-Async notification - get notified when task completes (default)
--silent-Fire and forget - no reply or notification needed
--force-Bypass working directory mismatch check (only needed for truly different projects; worktree agents of the same repo are auto-detected)

Message sources: Exactly one of positional message, --message-file, --task-file, or --stdin must be supplied. File/stdin inputs bypass the shell, so messages containing backticks, code fences, or long Markdown no longer trigger false shell-expansion warnings.

--wait and --notify spawn a sender-side task that produces structured A2A reply artifacts derived from the PTY output delta captured since task start. Synapse uses this delta, not the raw terminal tail, to reduce status-line noise in replies. TUI response cleaning (clean_copilot_response()) now runs for all agents, stripping Ink TUI artifacts (spinners, box-drawing borders, status bar, input echo) before finalization. In server mode, startup/runtime logs stay off stderr so they do not leak into the agent TUI. Quota-exhaustion output such as 402 You have no quota is classified as a failed task instead of a normal reply.

PROCESSING wait: When the target agent is in PROCESSING state, synapse send automatically waits up to 30 seconds for the agent to become idle before delivering the message. This prevents message loss when an agent is busy. The wait is skipped for --force, priority 5 (emergency), and --silent sends.

READY delay ([#467](https://github.com/s-hiraoku/synapse-a2a/issues/467) / [#642](https://github.com/s-hiraoku/synapse-a2a/pull/642)): When the target agent is in READY state, synapse send pauses for a short window (default 2 seconds, override with SYNAPSE_SEND_READY_DELAY in seconds) before injecting the message. This avoids overwriting input the user is in the middle of typing into the target agent's prompt. If the agent flips to PROCESSING during the window, the send fires immediately so it does not stall behind a freshly-started task. The delay is skipped for --force, priority 5, and --silent sends, mirroring the PROCESSING wait.

Choosing response mode:

Message TypeFlagExample
Question--wait"What is the status?"
Request for analysis--wait"Please review this code"
Task with result expected--notify"Run tests and report the results"
Delegated task (fire-and-forget)--silent"Fix this bug and commit"
Notification--silent"FYI: Build completed"

Default is --notify (async notification on completion).

Working directory check: synapse send verifies that the sender's current working directory matches the target agent's working_dir. Worktree relationships are automatically detected — parent repo, child worktree, and sibling worktrees of the same repo are all allowed without --force. For truly different projects, a warning is shown with available agents in the current directory (or a synapse spawn suggestion) and the command exits with code 1. Use --force to bypass this check.

Examples:

bash
# Task with result expected (async notification - default)
synapse send gemini "Analyze this and report findings" --notify

# Task with immediate response (blocking)
synapse send gemini "What is the best approach?" --wait

# Delegated task, fire-and-forget
synapse send codex "Fix this bug and commit" --silent

# Send message (single instance; --from auto-detected)
synapse send claude "Hello" --priority 1

# Long message support (automatic temp-file fallback)
synapse send claude --message-file /path/to/message.txt --silent
synapse send claude --task-file /path/to/tasks/auth.md --notify   # alias for --message-file (task-specification intent)
synapse send claude -T /path/to/tasks/auth.md --notify            # -T short form
echo "very long content..." | synapse send claude --stdin --silent

# File attachments
synapse send claude "Review this" --attach src/main.py --wait

# Send to specific instance (multiple of same type)
synapse send claude-8100 "Hello"

# Emergency stop
synapse send claude "Stop!" --priority 5

# Bypass working directory mismatch check (only needed for different projects)
synapse send claude "Review this" --force

# Explicit --from (only needed in sandboxed environments like Codex)
synapse send claude "Hello" --from $SYNAPSE_AGENT_ID

Default behavior: With a2a.flow=auto (default), synapse send uses --notify mode — the command returns immediately and you receive a PTY notification when the receiver completes. Use --wait for synchronous blocking, or --silent for fire-and-forget (no completion notification).

Sender auto-detection: --from is optional. Synapse auto-detects the sender using SYNAPSE_AGENT_ID (set at startup), then falls back to PID matching (process ancestry). Use explicit --from only in sandboxed environments (like Codex) where env vars may not propagate. If the sender cannot be identified, Synapse prints Warning: Could not identify sender agent. Set SYNAPSE_AGENT_ID or use --from. and the outbound message has an empty sender field — set SYNAPSE_AGENT_ID or pass --from to fix it.

Troubleshooting delivery failures: If synapse send prints Error sending message: local send failed, re-run with SYNAPSE_LOG_LEVEL=DEBUG to see UDS/TCP failure details, HTTP status codes, and endpoint information. Common causes include an HTTP 409 Agent busy (working task) when the target is mid-task (use synapse status <target> to check, or -p 5 to interrupt), or the target agent being unreachable on its local socket.

synapse reply Command

Reply to the last received message:

bash
synapse reply "<message>"
synapse reply --message-file /tmp/reply.md          # Read reply from file ('-' for stdin)
echo "long reply..." | synapse reply --stdin        # Read reply from stdin
synapse reply --fail "reason for failure"           # Send a failed reply

The --from flag is only needed in sandboxed environments (like Codex). Without --from, Synapse auto-detects the sender. Use --fail to indicate the task could not be completed; this sends a failed status with an error instead of a normal text reply.

Use synapse reply only for a Synapse-tracked incoming message, such as one marked [REPLY EXPECTED] or created by synapse send --wait. For user-pasted A2A text, Synapse has no reply target; use synapse send to continue the conversation instead.

Long replies / shell-expandable content: --message-file (-F) and --stdin mirror the same flags on synapse send, letting you supply replies that contain backticks, code fences, or other content that would otherwise be expanded or warned about by the shell. Other synapse send flags (--priority, --wait / --notify / --silent, --attach) are intentionally not mirrored — replies always use priority 3 in silent response mode.

Low-Level A2A Tool

For advanced operations:

bash
# List agents
python -m synapse.tools.a2a list

# Send message
python -m synapse.tools.a2a send --target claude --priority 1 "Hello"

# Reply to last received message (uses reply tracking)
python -m synapse.tools.a2a reply "Here is my response"

API Endpoints

A2A Compliant

EndpointMethodDescription
/.well-known/agent.jsonGETAgent Card
/tasks/sendPOSTSend message
/tasks/send-priorityPOSTSend with priority
/tasks/createPOSTCreate task (no PTY send, for --wait)
/tasks/{id}GETGet task status
/tasksGETList tasks
/tasks/{id}/cancelPOSTCancel task
/statusGETREADY/PROCESSING status

Readiness Gate: /tasks/send and /tasks/send-priority return HTTP 503 (with Retry-After: 5) until the agent finishes initialization (identity instruction sending). Priority 5 (emergency interrupt) and reply messages bypass this gate. See CLAUDE.md for details.

Agent Teams

EndpointMethodDescription
/tasks/{id}/approvePOSTApprove a plan
/tasks/{id}/rejectPOSTReject a plan with reason
/team/startPOSTStart multiple agents in terminal panes (A2A-initiated)
/spawnPOSTSpawn a single agent in a new terminal pane (A2A-initiated)

Synapse Extensions

EndpointMethodDescription
/reply-stack/getGETGet sender info without removing (for peek before send)
/reply-stack/popGETPop sender info from reply map (for synapse reply)
/tasks/{id}/subscribeGETSubscribe to task updates via SSE

Webhooks

EndpointMethodDescription
/webhooksPOSTRegister a webhook for task notifications
/webhooksGETList registered webhooks
/webhooksDELETEUnregister a webhook
/webhooks/deliveriesGETRecent webhook delivery attempts

External Agents

EndpointMethodDescription
/external/discoverPOSTRegister external agent
/external/agentsGETList
/external/agents/{alias}DELETERemove
/external/agents/{alias}/sendPOSTSend

Task Structure

In the A2A protocol, all communication is managed as Tasks.

Task Lifecycle

mermaid
stateDiagram-v2
    [*] --> submitted: POST /tasks/send
    submitted --> working: Processing starts
    working --> completed: Success
    working --> failed: Error
    working --> input_required: Waiting for input
    input_required --> working: Input received
    completed --> [*]
    failed --> [*]

Task Object

json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "context_id": "conversation-123",
  "status": "working",
  "message": {
    "role": "user",
    "parts": [{ "type": "text", "text": "Review this design" }]
  },
  "artifacts": [],
  "metadata": {
    "sender": {
      "sender_id": "synapse-claude-8100",
      "sender_type": "claude",
      "sender_endpoint": "http://localhost:8100"
    }
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:05Z"
}

Field Descriptions

FieldTypeDescription
idstringUnique task identifier (UUID)
context_idstring?Conversation context ID (for multi-turn)
statusstringsubmitted / working / completed / failed / input_required
messageMessageSent message
artifactsArtifact[]Task output artifacts
metadataobjectSender info (metadata.sender)
created_atstringCreation timestamp (ISO 8601)
updated_atstringUpdate timestamp (ISO 8601)

Message Structure

json
{
  "role": "user",
  "parts": [
    { "type": "text", "text": "Message content" },
    {
      "type": "file",
      "file": {
        "name": "doc.pdf",
        "mimeType": "application/pdf",
        "bytes": "..."
      }
    }
  ]
}
Part TypeDescription
textText message
fileFile attachment
dataStructured data

Sender Identification

The sender of A2A messages can be identified via metadata.sender.

PTY Output Format

Messages are sent to the agent's PTY with a prefix that includes optional sender identification and reply expectations:

code
A2A: [From: NAME (SENDER_ID)] [REPLY EXPECTED] <message content>
  • From: Identifies the sender's display name and unique Runtime ID.
  • REPLY EXPECTED: Indicates that the sender is waiting for a response (blocking).

If sender information is not available, it falls back to:

  • A2A: [From: SENDER_ID] <message content>
  • A2A: <message content> (backward compatible format)

Reply Handling

Synapse automatically manages reply routing. Agents simply use synapse reply:

bash
synapse reply "Here is my response"

The framework internally tracks sender information and routes replies automatically.

Task API Verification (Development)

bash
curl -s http://localhost:8120/tasks/<id> | jq '.metadata.sender'

Response:

json
{
  "sender_id": "synapse-claude-8100",
  "sender_type": "claude",
  "sender_endpoint": "http://localhost:8100"
}

How It Works

  1. On send: Reference Registry, identify own agent_id via PID matching (process ancestry)
  2. On Task creation: Attach sender info to metadata.sender
  3. On receive: Check via PTY prefix or Task API

Priority Levels

PriorityBehaviorUse Case
1-4Normal stdin writeRegular messages
5SIGINT then writeEmergency stop
bash
# Emergency stop
synapse send claude "Stop!" --priority 5

Agent Card

Each agent publishes an Agent Card at /.well-known/agent.json.

bash
curl http://localhost:8100/.well-known/agent.json
json
{
  "name": "Synapse Claude",
  "description": "PTY-wrapped claude CLI agent with A2A communication",
  "url": "http://localhost:8100",
  "capabilities": {
    "streaming": false,
    "pushNotifications": false,
    "multiTurn": true
  },
  "skills": [
    {
      "id": "chat",
      "name": "Chat",
      "description": "Send messages to the CLI agent"
    },
    {
      "id": "interrupt",
      "name": "Interrupt",
      "description": "Interrupt current processing"
    }
  ],
  "extensions": {
    "synapse": {
      "agent_id": "synapse-claude-8100",
      "pty_wrapped": true,
      "priority_interrupt": true,
      "at_agent_syntax": true,
      "summary": "Working on auth refactor"
    },
    "x-synapse-context": {
      "identity": "synapse-claude-8100",
      "routing_rules": {
        "self_patterns": ["@synapse-claude-8100", "@claude"],
        "forward_command": "synapse send <agent_id> \"<message>\" --from <your_agent_id>"
      },
      "available_agents": [
        { "id": "synapse-gemini-8110", "type": "gemini", "endpoint": "http://localhost:8110", "status": "READY" }
      ]
    }
  }
}

Context Injection (x-synapse-context)

To keep the PTY clean, Synapse uses the x-synapse-context extension to pass system context to agents. The PTY receives a minimal bootstrap message:

code
[SYNAPSE A2A] Your ID: synapse-claude-8100
Retrieve your system context:
curl -s http://localhost:8100/.well-known/agent.json | python3 -c "import sys,json; d=json.load(sys.stdin); print(json.dumps(d.get('extensions', {}).get('x-synapse-context', {}), indent=2))"

AI agents execute this command to discover themselves and their peers.

Design Philosophy

Agent Card is a "business card" containing only external-facing information:

  • capabilities, skills, endpoint, etc.
  • Synapse Extension (`x-synapse-context`): Includes system context (ID, routing rules, other agents) and bootstrap instructions, keeping the PTY clean.
  • Internal instructions are not included in the standard A2A fields (sent via x-synapse-context or initial Task).

Registry and Port Management

Registry Files

code
~/.a2a/registry/
├── synapse-claude-8100.json
├── synapse-claude-8101.json
└── synapse-gemini-8110.json

~/.a2a/reply/
└── synapse-claude-8100.reply.json   # Reply target persistence (auto-cleaned)

Auto Cleanup

Stale entries are automatically removed during:

  • synapse list execution
  • Message sending (when target is dead)

Port Ranges

python
PORT_RANGES = {
    "claude": (8100, 8109),
    "gemini": (8110, 8119),
    "codex": (8120, 8129),
    "opencode": (8130, 8139),
    "copilot": (8140, 8149),
    "dummy": (8190, 8199),
}

Typical Memory Usage (Resident Agents)

On macOS, idle resident agents are lightweight. As of January 25, 2026, RSS is around ~12 MB per agent process in a typical development setup.

Actual usage varies by profile, plugins, history settings, and workload. Note that ps reports RSS in KB (so ~12 MB corresponds to ~12,000 KB). To measure on your machine:

bash
ps -o pid,comm,rss,vsz,etime,command -A | rg "synapse"

If you don't have ripgrep:

bash
ps -o pid,comm,rss,vsz,etime,command -A | grep "synapse"

File Safety

Prevents conflicts when multiple agents edit the same files simultaneously.

mermaid
sequenceDiagram
    participant Claude
    participant FS as File Safety
    participant Gemini

    Claude->>FS: acquire_lock("auth.py")
    FS-->>Claude: ACQUIRED

    Gemini->>FS: validate_write("auth.py")
    FS-->>Gemini: DENIED (locked by claude)

    Claude->>FS: release_lock("auth.py")
    Gemini->>FS: acquire_lock("auth.py")
    FS-->>Gemini: ACQUIRED

Features

FeatureDescription
File LockingExclusive control prevents simultaneous editing
Change TrackingRecords who changed what and when
Context InjectionProvides recent change history on read
Pre-write ValidationChecks lock status before writing
List IntegrationActive locks visible in synapse list EDITING_FILE column

Enable

bash
# Enable via environment variable
export SYNAPSE_FILE_SAFETY_ENABLED=true
synapse claude

Basic Commands

bash
# Show statistics
synapse file-safety status

# List active locks
synapse file-safety locks

# Acquire lock
synapse file-safety lock /path/to/file.py claude --intent "Refactoring"

# Wait for lock to be released
synapse file-safety lock /path/to/file.py claude --wait --wait-timeout 60 --wait-interval 2

# Release lock
synapse file-safety unlock /path/to/file.py claude

# File change history
synapse file-safety history /path/to/file.py

# Recent changes
synapse file-safety recent

# Delete old data
synapse file-safety cleanup --days 30

Python API

python
from synapse.file_safety import FileSafetyManager, ChangeType, LockStatus

manager = FileSafetyManager.from_env()

# Acquire lock
result = manager.acquire_lock("/path/to/file.py", "claude", intent="Refactoring")
if result["status"] == LockStatus.ACQUIRED:
    # Edit file...

    # Record change
    manager.record_modification(
        file_path="/path/to/file.py",
        agent_name="claude",
        task_id="task-123",
        change_type=ChangeType.MODIFY,
        intent="Fix authentication bug"
    )

    # Release lock
    manager.release_lock("/path/to/file.py", "claude")

# Pre-write validation
validation = manager.validate_write("/path/to/file.py", "gemini")
if not validation["allowed"]:
    print(f"Write blocked: {validation['reason']}")

Storage: Default is .synapse/file_safety.db (SQLite, relative to working directory). Change via SYNAPSE_FILE_SAFETY_DB_PATH (e.g., ~/.synapse/file_safety.db for global).

See docs/file-safety.md for details.


Agent Monitor

Real-time monitoring of agent status with terminal jump capability.

Rich TUI Mode

bash
# Start Rich TUI in the alternate screen with auto-refresh (default)
synapse list

# JSON output for AI/programmatic consumption
synapse list --json

The display automatically updates when agent status changes (via file watcher) with a 10-second fallback polling interval.

JSON Output

synapse list --json outputs a JSON array of agent objects for AI and scripting use. Each object includes: agent_id, agent_type, name, role, skill_set, port, status, pid, working_dir, endpoint, transport, current_task_preview, task_received_at, uptime_seconds, input_required_tasks, summary, is_orphan, spawned_by, and optionally editing_file. The six canonical fields agent_id, status, current_task_preview, task_received_at, uptime_seconds, and input_required_tasks are produced by a shared view helper so synapse status <target> --json exposes them with identical shape and semantics (#708). The status field is the machine-readable enum value (the [ORPHAN] annotation that decorates the human synapse list table is stripped from JSON; use is_orphan instead).

If automation is attached to a TTY, use synapse list --json, synapse list --plain, or set SYNAPSE_NONINTERACTIVE=1. Bare synapse list is intended for human-operated interactive terminals.

For Copilot specifically, bracketed paste is enabled because Copilot CLI 1.0.12+ enables bracketed paste mode (ESC[?2004h). Synapse wraps input in paste markers so Ink routes it through usePaste as a single atomic event, which also eliminates the need for slash-command escaping. Input is delivered through an inject pipe mechanism that merges keyboard input and programmatic writes into the PTY's _copy loop, solving the issue where direct writes from other threads were lost. An input_ready_pattern () detects when the TUI is ready before sending instructions. Long messages use a single-line file reference format. Bounded submit confirmation verifies that Copilot cleared the prompt after submission. Copilot CLI also enables Kitty Keyboard Protocol (KKP) on startup, which re-encodes Enter from \r to CSI 13 u, causing injected \r submits to be silently ignored. Synapse detects KKP activation in PTY output and immediately pops the mode, and also proactively disables KKP before the first submit as a safety net.

Display Columns

ColumnDescription
IDRuntime ID (e.g., synapse-claude-8100)
NAMECustom name (if assigned)
TYPEAgent type (claude, gemini, codex, etc.)
ROLEAgent role description (if assigned)
STATUSCurrent status (READY, WAITING, WAITING_FOR_INPUT, PROCESSING, SENDING_REPLY, RATE_LIMITED, DONE)
CURRENTCurrent task preview with elapsed time (e.g., "Review code (2m 15s)")
TRANSPORTCommunication transport indicator
WORKING_DIRCurrent working directory
SKILL_SETApplied skill set name (if any)
SUMMARYPersistent agent summary (opt-in, not in default columns)
EDITING_FILEFile being edited (File Safety enabled only)

Customize columns in settings.json:

json
{
  "list": {
    "columns": ["ID", "NAME", "STATUS", "CURRENT", "TRANSPORT", "WORKING_DIR"]
  }
}

Status States

StatusColorMeaning
READYGreenAgent is idle, waiting for input
WAITINGCyanAgent is showing a permission prompt (selection UI / Y-N)
WAITING_FOR_INPUTOrangeAgent has an A2A task in input_required for a non-permission response (#538 / #640)
PROCESSINGYellowAgent is actively working
SENDING_REPLYCyanAgent is posting an outbound A2A send/reply request. This transient state restores the previous status when the POST finishes and does not overwrite terminal states such as DONE, SHUTTING_DOWN, or RATE_LIMITED
RATE_LIMITEDBold MagentaLLM provider rate limit hit; surfaced when the error_detector returns the RATE_LIMITED error code. Overrides PROCESSING / READY / WAITING_FOR_INPUT until the agent recovers (#561 / #648)
DONEBlueTask completed (auto-transitions to READY after 10s)

The registry status is reconciled against task_store on every controller transition: WAITING (permission) wins over WAITING_FOR_INPUT, and a fully terminal task_store demotes a stale PROCESSING / WAITING_FOR_INPUT back to READY (#569).

Stuck-Agent Watchdog

synapse watchdog check is a one-shot, read-only command that scans every live agent in the registry and surfaces stuck-state suspicions in a table (Stage 1 MVP, #646). It complements the status colours above: where synapse list shows the current state, the watchdog flags states that have lasted longer than expected.

bash
synapse watchdog check               # table output
synapse watchdog check --alarm-only  # only rows that tripped a heuristic
synapse watchdog check --json        # JSON array for programmatic consumers

Heuristics (priority order):

  1. RATE_LIMITED for more than 30 minutes
  2. SENDING_REPLY for more than 60 seconds
  3. WAITING with the codex CLI rate-limit reminder dialog visible in the PTY tail (alarm: rate_limit_dialog, #691 / #692)
  4. WAITING with the codex CLI edit-confirmation dialog ("Would you like to make the following edits?") visible in the PTY tail (alarm: edit_confirmation_dialog, #707)
  5. PROCESSING for more than 30 minutes with no outbound A2A send/reply in the last 10 minutes
  6. Spawn never ready: registered more than 60s ago (and within 5 minutes), status still not READY

Use synapse send-keys <target> '\x1b' to ESC out of the rate-limit dialog, or synapse send-keys <target> 'y' --enter to approve the edit-confirmation dialog without synapse jump.

Each row reports ID, STATUS, UPTIME, SAME_STATUS_FOR, LAST_OUTBOUND, and ALARM. The same_status_seconds field is computed from last_status_change_at, which is written only on real registry status transitions; legacy registry entries that pre-date the field skip duration-based heuristics gracefully. Stage 2-4 (background daemon, A2A push notifications, multi-watchdog locking, synapse list --watch integration, automatic recovery) are future work.

Interactive Controls

KeyAction
1-9Select agent row (direct)
↑/↓Navigate agent rows
Enter or jJump to selected agent's terminal
KKill selected agent (with confirmation)
/Filter by TYPE, NAME, or WORKING_DIR
ESCClear filter/selection
qQuit

Supported Terminals: iTerm2, Terminal.app, Ghostty, VS Code, tmux, Zellij

WAITING Detection

WAITING detection is enabled in all five profiles (claude, codex, gemini, opencode, copilot). The #140 false positive issue was resolved by matching only against fresh PTY output (new_data) and adding auto-expiry (waiting_expiry, default 10s) with buffer tail re-check. As of #572, the waiting_detection regex is evaluated against a pyte-backed virtual terminal (synapse/pty_renderer.py) that replays cursor-motion CSI sequences in place, so TUI-based agents (ratatui, Ink, Bubble Tea) that overwrite the same cells are matched against the text a human actually sees rather than an ANSI-stripped byte stream. Alt-screen buffer (\x1b[?1049h/l) enter/leave is tracked, and a new GET /debug/pty endpoint on each per-agent A2A server returns the rendered screen as JSON ({display, cursor, alt_screen, columns, rows}) for debugging regex matches.

WAITING observability (Phase 1 + 1.5, v0.28.1): each per-agent A2A server also exposes GET /debug/waiting, a ring buffer of recent detection attempts with path_used, pattern_source, confidence, idle_gate_passed, renderer_on, and raw/rendered snippets. synapse status <agent> --debug-waiting pretty-prints that buffer plus aggregates, synapse list / synapse status surface (renderer: off) and renderer_available when the pyte renderer failed to initialise, and synapse waiting-debug collect / report provide a cross-agent JSONL collection pipeline for Phase 2 analysis (see `docs/phase15-collection.md`). Detection logic itself is intentionally unchanged in this layer.

Detects agents waiting for user input (selection UI, Y/n prompts) using agent-specific regex patterns:

  • Claude: ❯ Option cursor, ☐/☑ checkboxes, [Y/n] prompts
  • Gemini: ● 1. Option selection UI, Action Required header, Allow once/for this session/for this file, No, suggest changes, Apply this change, Do you want to proceed
  • Codex: selector with numbered items, Yes, proceed, Yes, and don't ask again, No, and tell Codex, Press enter to confirm, Press [Ee]nter to confirm, Would you like to
  • OpenCode: Permission Required header, horizontal button bar (Allow (a), Allow for session (s), Deny (d))
  • Copilot: Numbered choices, selection indicators, [y/N] or (y/n) prompts, approve ... for the rest of the running session, No, and tell Copilot. A repeated WAITING state only confirms after the prompt text clears.

Compound Signal Status Detection

The PROCESSING to READY transition uses compound signals to prevent premature detection during A2A task processing:

  • `task_active` flag: Suppresses READY when an A2A task is being processed (timeout: task_protection_timeout, default 30s)
  • File locks: Suppresses READY when the agent holds file locks via FileSafetyManager

Use synapse status <agent> to inspect the detailed state of a specific agent, including current task elapsed time and file locks. Its Recent Messages section shows messages where the selected agent was involved as sender or receiver, rather than unrelated global history. Since 0.31.0, parent-side synapse send observations are included in recent messages (#659 / #662), timestamps use millisecond precision so rapid writes within the same second can still be ordered (#661 / #666), and output_text is no longer overwritten with a parent-side placeholder (#660 / #663).


CI Automation (Claude Code)

Synapse A2A includes hooks and skills for automated CI monitoring and repair when used with Claude Code.

How It Works

  1. PostToolUse hook (check-ci-trigger.sh) detects git push or gh pr create commands
  2. Two background monitors launch automatically:

- `poll-ci.sh` — polls GitHub Actions workflow status - `poll-pr-status.sh` — polls merge conflict state and CodeRabbit review comments

  1. When issues are detected, the agent receives a systemMessage notification suggesting the appropriate fix skill

Available Skills

SkillDescription
/check-ciManually check CI status, merge conflict state, and CodeRabbit review status. Use --fix to get suggested repair commands
/fix-ciAuto-diagnose and fix CI failures (lint, format, type-check, test)
/fix-conflictAuto-resolve merge conflicts by fetching the base branch, performing a test merge, analyzing both sides of each conflict, resolving, verifying locally, and pushing
/fix-reviewAuto-fix CodeRabbit review comments — classifies comments as Bug/Security (auto-fix), Style (auto-fix), or Suggestion (report only). Use --all to also fix suggestions
/dev-issue <number>Bootstrap issue implementation in one step — fetches the issue from GitHub, generates a task brief, creates a feature branch (feat/<slug>-<number>), and spawns a Codex agent on it

Conflict Detection Flow

code
git push / gh pr create
  └─→ check-ci-trigger.sh (PostToolUse hook)
        ├─→ poll-ci.sh (background) → monitors GitHub Actions
        └─→ poll-pr-status.sh (background)
              ├─→ checks mergeable state → if CONFLICTING → notifies agent → /fix-conflict
              └─→ checks CodeRabbit reviews → if comments found → classifies → notifies agent → /fix-review

Setup

These hooks and skills are pre-configured in .claude/settings.json. The following permissions are required:

  • Skill(check-ci), Skill(fix-ci), Skill(fix-conflict), Skill(fix-review)
  • Bash(gh api:*), Bash(gh repo view:*), Bash(gh pr checks:*)

Testing

Comprehensive test suite verifies A2A protocol compliance:

bash
# All tests
pytest

# Specific category
pytest tests/test_a2a_compat.py -v
pytest tests/test_sender_identification.py -v

# Opt-in live E2E against real agent CLIs
SYNAPSE_LIVE_E2E=1 pytest tests/test_live_e2e_agents.py -q

# Limit live E2E to specific agents
SYNAPSE_LIVE_E2E=1 SYNAPSE_LIVE_E2E_PROFILES=copilot,codex \
  pytest tests/test_live_e2e_agents.py -q

Live E2E tests are skipped by default. They launch the real claude, codex, gemini, opencode, and copilot CLIs in headless Synapse sessions and verify that a message sent through /tasks/send completes and returns the requested token. Use them for local validation or a dedicated CI job with authenticated agent CLIs.


Configuration (.synapse)

Customize environment variables and initial instructions via .synapse/settings.json.

Scopes

ScopePathPriority
User~/.synapse/settings.jsonLow
Project./.synapse/settings.jsonMedium
Local./.synapse/settings.local.jsonHigh (gitignore recommended)

Higher priority settings override lower ones.

Setup

bash
# Create .synapse/ directory (copies all template files)
synapse init

# ? Where do you want to create .synapse/?
#   ❯ User scope (~/.synapse/)
#     Project scope (./.synapse/)
#
# ✔ Created ~/.synapse

# Reset to defaults
synapse reset

# Edit settings interactively (TUI)
synapse config

# Show current settings (read-only)
synapse config show
synapse config show --scope user

synapse init copies these files to .synapse/:

FileDescription
settings.jsonEnvironment variables and initial instruction settings
default.mdInitial instructions common to all agents
gemini.mdGemini-specific initial instructions
file-safety.mdFile Safety instructions
learning.mdLearning Mode instructions (structured prompt improvement and learning feedback)
proactive.mdProactive Mode instructions (task-size x feature matrix with per-feature skip conditions)

settings.json Structure

json
{
  "env": {
    "SYNAPSE_HISTORY_ENABLED": "true",
    "SYNAPSE_FILE_SAFETY_ENABLED": "true",
    "SYNAPSE_FILE_SAFETY_DB_PATH": ".synapse/file_safety.db"
  },
  "instructions": {
    "default": "[SYNAPSE INSTRUCTIONS...]\n...",
    "claude": "",
    "gemini": "",
    "codex": ""
  },
  "approvalMode": "required",
  "a2a": {
    "flow": "auto"
  }
}

Environment Variables (env)

VariableDescriptionDefault
SYNAPSE_HISTORY_ENABLEDEnable task historytrue
SYNAPSE_FILE_SAFETY_ENABLEDEnable file safetytrue
SYNAPSE_FILE_SAFETY_DB_PATHFile safety DB path.synapse/file_safety.db
SYNAPSE_FILE_SAFETY_RETENTION_DAYSLock history retention days30
SYNAPSE_AUTH_ENABLEDEnable API authenticationfalse
SYNAPSE_API_KEYSAPI keys (comma-separated)-
SYNAPSE_ADMIN_KEYAdmin key-
SYNAPSE_ALLOW_LOCALHOSTSkip auth for localhosttrue
SYNAPSE_USE_HTTPSUse HTTPSfalse
SYNAPSE_WEBHOOK_SECRETWebhook secret-
SYNAPSE_WEBHOOK_TIMEOUTWebhook timeout (sec)10
SYNAPSE_WEBHOOK_MAX_RETRIESWebhook retry count3
SYNAPSE_SKILLS_DIRCentral skill store directory~/.synapse/skills
SYNAPSE_REPLY_TARGET_DIRReply target persistence directory~/.a2a/reply
SYNAPSE_LONG_MESSAGE_THRESHOLDCharacter threshold for file storage200
SYNAPSE_LONG_MESSAGE_TTLTTL for message files (seconds)3600
SYNAPSE_LONG_MESSAGE_DIRDirectory for message filesSystem temp
SYNAPSE_SEND_MESSAGE_THRESHOLDThreshold for auto temp-file fallback (bytes)102400
SYNAPSE_LEARNING_MODE_ENABLEDEnable Prompt Improvement section (Goal/Problem/Fix, recommended rewrite, detail-level options). Independent of TRANSLATION flag. Either flag enables learning.md injection and Tipsfalse
SYNAPSE_LEARNING_MODE_TRANSLATIONEnable JP-to-EN Learning section (reusable English patterns with slot mapping). Independent of LEARNING_MODE_ENABLED flag. Either flag enables learning.md injection and Tipsfalse
SYNAPSE_PROACTIVE_MODE_ENABLEDEnable Proactive Mode: guides agents to use Synapse features (shared memory, canvas, file safety, delegation, broadcast) based on task-size x feature matrix with per-feature skip conditions. Appends .synapse/proactive.md instructions at startup. Off by defaultfalse
SYNAPSE_OBSERVATION_ENABLEDEnable PTY/A2A observation capture for the self-learning pipelinetrue
SYNAPSE_OBSERVATION_DB_PATHPath to observations SQLite database.synapse/observations.db
SYNAPSE_INSTINCT_DB_PATHPath to instincts SQLite database.synapse/instincts.db

A2A Communication Settings (a2a)

SettingValueDescription
flowroundtripAlways wait for result
flowonewayAlways forward only (don't wait)
flowautoFlag-controlled; if omitted, waits by default

Approval Mode (approvalMode)

Controls whether to show a confirmation prompt before sending initial instructions.

SettingDescription
requiredShow approval prompt at startup (default)
autoSend instructions automatically without prompting

When set to required, you'll see a prompt like:

code
[Synapse] Agent: synapse-claude-8100 | Port: 8100
[Synapse] Initial instructions will be sent to configure A2A communication.

Proceed? [Y/n/s(skip)]:

Options:

  • Y (or Enter): Send initial instructions and start agent
  • n: Abort startup
  • s: Start agent without sending initial instructions

Initial Instructions (instructions)

Customize instructions sent at agent startup:

json
{
  "instructions": {
    "default": "Common instructions for all agents",
    "claude": "Claude-specific instructions (takes priority over default)",
    "gemini": "Gemini-specific instructions",
    "codex": "Codex-specific instructions"
  }
}

Priority:

  1. Agent-specific setting (claude, gemini, codex, opencode, copilot) if present
  2. Otherwise use default
  3. If both empty, no initial instructions sent

Placeholders:

  • {{agent_id}} - Runtime ID (e.g., synapse-claude-8100)
  • {{port}} - Port number (e.g., 8100)

See guides/settings.md for details.


Development & Release

Publishing to PyPI

Merging a pyproject.toml version change to main automatically creates a git tag, GitHub Release, and publishes to PyPI.

bash
# 1. Generate changelog with git-cliff
python scripts/generate_changelog.py

# 2. Update version in pyproject.toml and review CHANGELOG.md
# 3. Create PR and merge to main
# 4. Automation handles: tag → GitHub Release → PyPI → Homebrew/Scoop PR

Manual Publishing (Fallback)

bash
# Build and publish with uv
uv build
uv publish

User Installation

macOS / Linux / WSL2 (recommended):

bash
pipx install synapse-a2a

# Upgrade
pipx upgrade synapse-a2a

# Uninstall
pipx uninstall synapse-a2a

Windows (Scoop, experimental — WSL2 required for pty):

bash
scoop bucket add synapse-a2a https://github.com/s-hiraoku/scoop-synapse-a2a
scoop install synapse-a2a

# Upgrade
scoop update synapse-a2a

Known Limitations

  • TUI Rendering: Display may be garbled with Ink-based CLIs (response artifacts from Bubble Tea and Ink TUIs are automatically stripped)
  • PTY Limitations: Some special input sequences not supported
  • Ghostty Focus: Ghostty uses AppleScript to target the currently focused window or tab. If you switch tabs while a spawn or team start command is executing, the agent may be spawned in the unintended tab. Please wait for the command to complete before interacting with the terminal.
  • Codex Sandbox: Codex CLI's sandbox blocks network access, requiring configuration for inter-agent communication (see below)

Inter-Agent Communication in Codex CLI

Codex CLI runs in a sandbox by default with restricted network access. To use @agent pattern for inter-agent communication, allow network access in ~/.codex/config.toml.

Global Setting (applies to all projects):

toml
# ~/.codex/config.toml

sandbox_mode = "workspace-write"

[sandbox_workspace_write]
network_access = true

Per-Project Setting:

toml
# ~/.codex/config.toml

[projects."/path/to/your/project"]
sandbox_mode = "workspace-write"

[projects."/path/to/your/project".sandbox_workspace_write]
network_access = true

See guides/troubleshooting.md for details.


Enterprise Features

Security, notification, and high-performance communication features for production environments.

API Key Authentication

bash
# Start with authentication enabled
export SYNAPSE_AUTH_ENABLED=true
export SYNAPSE_API_KEYS=<YOUR_API_KEY>
synapse claude

# Request with API Key
curl -H "X-API-Key: <YOUR_API_KEY>" http://localhost:8100/tasks

Webhook Notifications

Send notifications to external URLs when tasks complete.

bash
# Register webhook
curl -X POST http://localhost:8100/webhooks \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-server.com/hook", "events": ["task.completed"]}'
EventDescription
task.completedTask completed successfully
task.failedTask failed
task.canceledTask canceled

SSE Streaming

Receive task output in real-time.

bash
curl -N http://localhost:8100/tasks/{task_id}/subscribe

Event types:

EventDescription
outputNew CLI output
statusStatus change
doneTask complete (includes Artifact)

Output Parsing

Automatically parse CLI output for error detection, status updates, and Artifact generation.

FeatureDescription
Error DetectionDetects command not found, permission denied, etc.
input_requiredDetects question/confirmation prompts
TUI Artifact RemovalStrips Ink/Bubble Tea artifacts (spinners, box-drawing, block elements, frame content, Gemini input prompts) from all agent responses
Output ParserStructures code/files/errors

gRPC Support

Use gRPC for high-performance communication.

bash
# Install gRPC dependencies
pip install synapse-a2a[grpc]

# gRPC runs on REST port + 1
# REST: 8100 → gRPC: 8101

See guides/enterprise.md for details.


Documentation

PathContent
guides/usage.mdDetailed usage
guides/architecture.mdArchitecture details
guides/enterprise.mdEnterprise features
guides/troubleshooting.mdTroubleshooting
docs/file-safety.mdFile conflict prevention
docs/project-philosophy.mdDesign philosophy

License

MIT License


Related Links

Install & Usage

1
Create the skills directory
mkdir -p .claude/skills
2
Download the skill file
mkdir -p .claude/skills && curl -o .claude/skills/synapse-a2a.md https://raw.githubusercontent.com/s-hiraoku/synapse-a2a/main/SKILL.md
3
Invoke in Claude Code
/synapse-a2a
View source on GitHub
agentplugin

Frequently Asked Questions

What is synapse-a2a?

Complete plugin for Synapse A2A multi-agent framework including inter-agent communication, task delegation, file safety, and history management

How to install synapse-a2a?

To install synapse-a2a, create the .claude/skills directory in your project, then run the curl command to download the skill file. Once installed, invoke it in Claude Code with /synapse-a2a.

What is synapse-a2a best for?

synapse-a2a is a community categorized under General. It is designed for: agent, plugin. Created by s-hiraoku.