# Synqed as a Universal Substrate

## Overview

Synqed is designed as a **universal substrate** for AI agent collaboration. This means:

- **ANY agent from ANY ecosystem can join a Synqed workspace**
- **Synqed doesn't wrap or adapt agents** - it provides the routing infrastructure
- **Agents just need to speak A2A protocol** - that's the universal interface

## The Key Insight

> **Synqed must define the interface that everything plugs into.**  
> **A2A is that protocol.**

When an agent says:
- "Here is my endpoint URL"
- "Here is my schema (A2A AgentCard)"
- "Here is my auth (optional)"
- "Here is how you call me"

Synqed can route messages to it. No wrapping. No adaptation. Pure routing.

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    Synqed Workspace                         │
│              (Universal Routing Substrate)                  │
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐    │
│  │ Local Agent  │  │ Remote Agent │  │ Remote Agent │    │
│  │ (Synqed)     │  │ (LangChain)  │  │ (CrewAI)     │    │
│  │              │  │              │  │              │    │
│  │ In-memory    │  │ HTTP/gRPC    │  │ HTTP/gRPC    │    │
│  │ routing      │  │ A2A protocol │  │ A2A protocol │    │
│  └──────────────┘  └──────────────┘  └──────────────┘    │
│                                                             │
│  All agents receive and send messages through Synqed       │
│  Synqed handles routing, workspaces, coordination          │
└─────────────────────────────────────────────────────────────┘
```

## What Makes This Universal?

### 1. **Protocol, Not Implementation**

Synqed doesn't care:
- What framework you used to build your agent
- What LLM your agent uses
- What language your agent is written in
- Where your agent is hosted

Synqed only cares:
- Does your agent implement A2A protocol?
- Can I send it messages via A2A endpoints?
- Does it return structured responses?

### 2. **No Wrappers, Just Routing**

**Wrong Approach (Wrapper Pattern):**
```python
# ❌ This is NOT what Synqed does
class LangChainAdapter:
    def __init__(self, langchain_agent):
        self.agent = langchain_agent  # Wrap it
    
    def translate_to_synqed_format(self, ...):
        # Try to adapt LangChain's model to Synqed's model
        pass
```

**Right Approach (Routing Pattern):**
```python
# ✅ This IS what Synqed does
AgentRuntimeRegistry.register_remote(
    role="ExternalAgent",
    url="https://agent.example.com",  # Just the URL!
    auth_token="optional-key"
)

# Synqed will route messages to this endpoint using A2A protocol
# No wrapping, no adaptation
```

### 3. **Mixed Agent Workspaces**

A single workspace can contain:
- **Local agents** (built with Synqed) - fast, in-memory routing
- **Remote A2A agents** (built with anything) - HTTP/gRPC routing

They all collaborate seamlessly because they all speak A2A.

## How to Use

### Register a Local Agent

```python
import synqed

# Define agent logic
async def my_agent_logic(context: synqed.AgentLogicContext) -> dict:
    latest = context.latest_message
    # Your logic here...
    return {"send_to": "OtherAgent", "content": "Response"}

# Create and register
agent = synqed.Agent(
    name="MyAgent",
    description="My local agent",
    logic=my_agent_logic
)

synqed.AgentRuntimeRegistry.register("MyAgent", agent)
```

### Register a Remote A2A Agent

```python
import synqed

# Register a remote agent from ANY ecosystem
synqed.AgentRuntimeRegistry.register_remote(
    role="ExternalCodeReviewer",
    url="https://code-review-agent.example.com",
    auth_token="secret-key"  # Optional
)

# That's it! Synqed will now route to this agent using A2A protocol
```

### Create a Workspace with Mixed Agents

```python
import synqed
from pathlib import Path

# Create workspace manager
workspace_manager = synqed.WorkspaceManager(
    workspaces_root=Path("/tmp/workspaces")
)

# Define what agents the workspace needs
class TaskNode:
    id = "collaboration-task"
    required_agents = [
        "MyAgent",              # Local agent
        "ExternalCodeReviewer"  # Remote A2A agent
    ]

# Create workspace
workspace = await workspace_manager.create_workspace(
    task_tree_node=TaskNode(),
    parent_workspace_id=None
)

# Workspace now contains both local and remote agents!
# Synqed handles routing to both seamlessly
```

## A2A Protocol Requirements

For an agent to participate in Synqed workspaces, it must implement:

### 1. **AgentCard Discovery**

Expose agent metadata at `/.well-known/agent-card.json`:

```json
{
  "protocol_version": "1.0",
  "name": "My Agent",
  "description": "What this agent does",
  "url": "https://my-agent.example.com",
  "preferred_transport": "JSONRPC",
  "skills": [
    {
      "id": "code-review",
      "name": "Code Review",
      "description": "Reviews code for quality"
    }
  ]
}
```

### 2. **Message Endpoint**

Implement `message/send` endpoint (JSON-RPC) or equivalent:

```
POST https://my-agent.example.com
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "method": "message/send",
  "params": {
    "message": {
      "message_id": "msg-123",
      "role": "ROLE_USER",
      "parts": [{"text": "Your task here"}]
    },
    "configuration": {
      "blocking": true
    }
  },
  "id": 1
}
```

### 3. **Structured Response**

Return a structured response:

```json
{
  "jsonrpc": "2.0",
  "result": {
    "task": {
      "id": "task-123",
      "status": {
        "state": "TASK_STATE_COMPLETED"
      },
      "artifacts": [
        {
          "artifact_id": "result-1",
          "parts": [
            {
              "text": "Agent's response here"
            }
          ]
        }
      ]
    }
  },
  "id": 1
}
```

## Benefits of Universal Substrate

### 1. **Ecosystem Agnostic**

Build agents with:
- **Synqed** - native, fast, in-memory
- **LangChain** - expose via A2A endpoint
- **CrewAI** - expose via A2A endpoint
- **AutoGPT** - expose via A2A endpoint
- **Custom framework** - just implement A2A

They all work together in Synqed workspaces.

### 2. **Best Tool for the Job**

- Use Synqed for fast, coordinated multi-agent workflows
- Use LangChain for agents that need complex tool chains
- Use CrewAI for role-based agent teams
- Mix and match as needed

### 3. **Gradual Migration**

Already have agents built with other frameworks?
- Keep using them!
- Just expose an A2A endpoint
- Plug them into Synqed workspaces

No rewrite needed.

### 4. **Future-Proof**

New agent framework comes out tomorrow?
- Does it support A2A? Great!
- Plug it into Synqed immediately
- No code changes needed

## Example Use Cases

### Enterprise Multi-Agent System

```
Synqed Workspace:
├── Coordinator (local, Synqed)
├── Data Analyst (remote, internal LangChain service)
├── Code Generator (remote, internal CrewAI service)
└── Security Auditor (remote, external vendor's A2A agent)
```

All agents collaborate on a complex task, each using their own
specialized framework and infrastructure.

### Agent Marketplace

```
Synqed Workspace:
├── Project Manager (your local agent)
├── Domain Expert A (purchased from Marketplace A)
├── Domain Expert B (purchased from Marketplace B)
└── Quality Assurance (purchased from Marketplace C)
```

Agents from different vendors, all working together through A2A.

### Hybrid Cloud Architecture

```
Synqed Workspace:
├── Orchestrator (local, on-premises)
├── Data Processor (remote, AWS Lambda A2A agent)
├── ML Model (remote, GCP Vertex AI A2A agent)
└── Validator (remote, Azure Function A2A agent)
```

Multi-cloud agent collaboration with no vendor lock-in.

## Implementation Status

✅ **Completed:**
- RemoteA2AAgent client for calling external A2A endpoints
- AgentRuntimeRegistry.register_remote() for registering remote agents
- MessageRouter routing to both local and remote agents
- WorkspaceExecutionEngine support for remote agents
- Example demonstrating mixed local/remote agents

🚧 **In Progress:**
- Full A2A AgentCard discovery and validation
- A2A server wrapper for exposing local agents as A2A endpoints
- gRPC transport support (currently JSON-RPC only)
- Authentication schemes (OAuth2, mTLS, etc.)

📋 **Planned:**
- Agent marketplace integration
- A2A extension support
- Enhanced streaming support for long-running tasks
- Monitoring and observability for remote agent calls

## Learn More

- **A2A Protocol:** https://a2a-protocol.org
- **A2A Specification:** https://github.com/a2aproject/A2A
- **Synqed Documentation:** [Link to docs]
- **Example:** `examples/intro/universal_substrate_demo.py`

## Contributing

Want to help make Synqed a better universal substrate?

- Add support for more A2A transports (gRPC, HTTP+JSON)
- Improve remote agent discovery and validation
- Build adapters to help existing agent frameworks expose A2A endpoints
- Create examples showing integration with popular frameworks

See `CONTRIBUTING.md` for details.

