Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/cli-full-parity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@resciencelab/agent-world-network": minor
---

feat(cli): add join/leave/ping/send commands for full plugin parity

The standalone AWN CLI (`awn`) now exposes all capabilities available in the OpenClaw plugin:

- `awn join <world_id|slug|host:port>` — join a world by ID, slug, or direct address; resolves via Gateway and sends a signed `world.join` P2P message
- `awn leave <world_id>` — send `world.leave` and remove from joined list
- `awn joined` — list currently joined worlds
- `awn ping <agent_id>` — check reachability of a known agent
- `awn send <agent_id> <message>` — send a signed `chat` P2P message to an agent

Adds `sign_http_request()` and `build_signed_p2p_message()` helpers to `crypto.rs` (wire-compatible with the TypeScript plugin). The daemon gains a `joined_worlds` state map and five new IPC routes.
9 changes: 9 additions & 0 deletions .changeset/fix-gateway-peer-announce-compat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@resciencelab/agent-world-sdk": patch
---

fix(gateway): add /peer/announce backward-compat route and auto-redeploy on SDK version bump

- Add `POST /peer/announce` backward-compat route for SDK < 1.4 world containers (returns legacy `{peers:[]}` shape)
- Raise default `STALE_TTL_MS` from 90 s to 15 min to prevent old SDK worlds (10 min announce interval, no heartbeat) from being pruned between announces
- Add `packages/agent-world-sdk/package.json` to `deploy-gateway.yml` path triggers so any SDK minor version bump automatically redeploys the gateway (fixes 403 signature mismatch caused by `PROTOCOL_VERSION` changing without gateway redeploy)
1 change: 1 addition & 0 deletions .github/workflows/deploy-gateway.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ on:
paths:
- "gateway/**"
- "packages/agent-world-sdk/src/**"
- "packages/agent-world-sdk/package.json"
workflow_dispatch:

concurrency:
Expand Down
62 changes: 61 additions & 1 deletion gateway/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const DEFAULT_HTTP_PORT = parseInt(process.env.HTTP_PORT ?? "8100")
const DEFAULT_PUBLIC_ADDR = process.env.PUBLIC_ADDR ?? null
const DEFAULT_PUBLIC_URL = process.env.PUBLIC_URL ?? null
const DEFAULT_DATA_DIR = process.env.DATA_DIR ?? "/data"
const DEFAULT_STALE_TTL_MS = parseInt(process.env.STALE_TTL_MS ?? String(90 * 1000))
const DEFAULT_STALE_TTL_MS = parseInt(process.env.STALE_TTL_MS ?? String(15 * 60 * 1000))
const WEBHOOK_URL = process.env.WEBHOOK_URL ?? null
const MAX_AGENTS = 500
const REGISTRY_VERSION = 1
Expand Down Expand Up @@ -811,6 +811,66 @@ export async function createGatewayApp(opts = {}) {
return { ok: true, agents: getAgentsForExchange(20) };
});

// Backward-compat: SDK versions < 1.4 post to /peer/announce instead of /agents.
// Accepts the same body, registers the same way, but returns the old {peers:[]} shape.
peer.post("/peer/announce", {
schema: {
summary: "Legacy peer announce (SDK < 1.4, maps to POST /agents)",
operationId: "postPeerAnnounce",
tags: ["gateway"],
body: { $ref: "AnnounceRequest#" },
response: {
200: {
type: "object",
properties: { peers: { type: "array", items: { $ref: "AgentRecord#" } } },
},
400: { $ref: "Error#" },
403: { $ref: "Error#" },
},
},
}, async (req, reply) => {
const ann = req.body;
if (!ann?.publicKey || !ann?.from) return reply.code(400).send({ error: "Invalid announce" });

const awSig = req.headers["x-agentworld-signature"];
if (awSig) {
const authority = req.headers["host"] ?? "localhost";
const result = verifyHttpRequestHeaders(req.headers, req.method, req.url, authority, req.rawBody, ann.publicKey);
if (!result.ok) return reply.code(403).send({ error: result.error });
} else {
const { signature, ...signable } = ann;
const domainOk = verifyWithDomainSeparator(DOMAIN_SEPARATORS.ANNOUNCE, ann.publicKey, signable, signature);
if (!domainOk && !verifySignature(ann.publicKey, signable, signature)) {
return reply.code(403).send({ error: "Invalid signature" });
}
}

if (agentIdFromPublicKey(ann.publicKey) !== ann.from) {
return reply.code(400).send({ error: "agentId mismatch" });
}

const worldCap = Array.isArray(ann.capabilities)
? ann.capabilities.find((cap) => typeof cap === "string" && cap.startsWith("world:"))
: undefined;
if (worldCap) {
const protocolWorldId = agentIdFromPublicKey(ann.publicKey);
upsertWorld(protocolWorldId, ann.publicKey, {
slug: typeof ann.slug === "string" && ann.slug.length > 0
? ann.slug
: worldCap.slice("world:".length) || ann.alias || protocolWorldId,
endpoints: ann.endpoints,
lastSeen: ann.timestamp,
persist: true,
});
} else {
upsertAgent(ann.from, ann.publicKey, {
alias: ann.alias, endpoints: ann.endpoints, capabilities: ann.capabilities, persist: true,
});
}
// Return legacy shape: {peers:[...]} instead of {ok, agents:[...]}
return { peers: getAgentsForExchange(20) };
});

peer.post("/agents/:agentId/heartbeat", {
schema: {
summary: "Lightweight liveness heartbeat",
Expand Down
2 changes: 1 addition & 1 deletion packages/awn-cli/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 34 additions & 1 deletion packages/awn-cli/skills/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,21 @@ awn worlds # list available worlds from Gateway
awn world <world_id> # get detailed info about a specific world
```

### World membership

```
awn join <world_id|slug|host:port> # join a world
awn joined # list currently joined worlds
awn leave <world_id> # leave a world
```

### P2P communication

```
awn ping <agent_id> # check agent reachability and latency
awn send <agent_id> "message" # send a signed P2P message
```

### JSON output (for agents)

All commands support `--json` for structured, machine-readable output:
Expand All @@ -72,6 +87,8 @@ awn --json status
awn --json worlds
awn --json world <world_id>
awn --json agents --capability world:
awn --json joined
awn --json ping <agent_id>
```

## Command Groups
Expand All @@ -92,15 +109,31 @@ awn --json agents --capability world:
| `worlds` | List available worlds from Gateway + local cache |
| `world <world_id>` | Get detailed info about a specific world including manifest and available actions |

### world membership

| Command | Description |
|---------|-------------|
| `join <world_id\|slug\|host:port>` | Join a world; resolves via Gateway or connects directly |
| `joined` | List currently joined worlds |
| `leave <world_id>` | Send `world.leave` and remove world from joined list |

### messaging

| Command | Description |
|---------|-------------|
| `ping <agent_id>` | Check if an agent is reachable; reports latency |
| `send <agent_id> <message>` | Send a signed `chat` P2P message to an agent |

## For AI Agents

When using this CLI programmatically:

1. **Always use `--json` flag** for parseable output
2. **Start daemon first**: `awn daemon start`
3. **Workflow**: `awn worlds` → `awn world <id>` (view actions) → `awn join <id>` → `awn action <name>`
3. **Workflow**: `awn worlds` → `awn world <id>` (view manifest/actions) → `awn join <id>` → `awn agents` → `awn send <agent_id> "msg"`
4. **Check return codes** — 0 for success, non-zero for errors
5. **Parse stderr** for error messages on failure
6. **Join before messaging** — agent endpoints are only discovered on world join

### Discovering world capabilities

Expand Down
156 changes: 156 additions & 0 deletions packages/awn-cli/src/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;

use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
use serde_json::Value;
use sha2::{Digest, Sha256};
Expand Down Expand Up @@ -144,6 +145,161 @@ pub fn compute_content_digest(body: &str) -> String {
format!("sha-256=:{}:", B64.encode(hash))
}

/// The six AgentWorld HTTP request headers returned by `sign_http_request`.
pub struct HttpRequestHeaders {
pub version: String,
pub from_agent: String,
pub key_id: String,
pub timestamp: String,
pub content_digest: String,
pub signature: String,
}

/// Build and sign the AgentWorld request headers for an outbound HTTP call.
/// Wire-compatible with the TS `signHttpRequest()`.
pub fn sign_http_request(
identity: &crate::identity::Identity,
method: &str,
authority: &str,
path: &str,
body: &str,
) -> HttpRequestHeaders {
let ts = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, false);
let kid = "#identity";
let content_digest = compute_content_digest(body);
let signing_input = serde_json::json!({
"v": PROTOCOL_VERSION,
"from": identity.agent_id,
"kid": kid,
"ts": ts,
"method": method.to_uppercase(),
"authority": authority,
"path": path,
"contentDigest": content_digest,
});
let signature =
sign_with_domain_separator(SEPARATOR_HTTP_REQUEST, &signing_input, &identity.signing_key);
HttpRequestHeaders {
version: PROTOCOL_VERSION.to_string(),
from_agent: identity.agent_id.clone(),
key_id: kid.to_string(),
timestamp: ts,
content_digest,
signature,
}
}

/// Build a signed P2P message payload ready for POST to `/peer/message`.
pub fn build_signed_p2p_message(
identity: &crate::identity::Identity,
event: &str,
content: &str,
) -> serde_json::Value {
let timestamp = now_ms_unix();
let payload_without_sig = serde_json::json!({
"from": identity.agent_id,
"publicKey": identity.pub_b64,
"event": event,
"content": content,
"timestamp": timestamp,
});
let signature = sign_with_domain_separator(
SEPARATOR_MESSAGE,
&payload_without_sig,
&identity.signing_key,
);
let mut msg = payload_without_sig;
msg["signature"] = serde_json::Value::String(signature);
msg
}

fn now_ms_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as u64
}

const MAX_CLOCK_SKEW_MS: u64 = 5 * 60 * 1000;

/// The AgentWorld HTTP response headers produced by `sign_http_response`.
pub struct HttpResponseHeaders {
pub version: String,
pub from_agent: String,
pub key_id: String,
pub timestamp: String,
pub content_digest: String,
pub signature: String,
}

/// Sign an outbound HTTP response. Wire-compatible with TS `signHttpResponse()`.
pub fn sign_http_response(
identity: &crate::identity::Identity,
status: u16,
body: &str,
) -> HttpResponseHeaders {
let ts = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, false);
let kid = "#identity";
let content_digest = compute_content_digest(body);
let signing_input = serde_json::json!({
"v": PROTOCOL_VERSION,
"from": identity.agent_id,
"kid": kid,
"ts": ts,
"status": status,
"contentDigest": content_digest,
});
let signature = sign_with_domain_separator(
SEPARATOR_HTTP_RESPONSE,
&signing_input,
&identity.signing_key,
);
HttpResponseHeaders {
version: PROTOCOL_VERSION.to_string(),
from_agent: identity.agent_id.clone(),
key_id: kid.to_string(),
timestamp: ts,
content_digest,
signature,
}
}

/// Verify an inbound signed HTTP response. Returns false on any failure.
/// Wire-compatible with TS `verifyHttpResponseHeaders()`.
pub fn verify_http_response(
version: &str,
from: &str,
key_id: &str,
timestamp: &str,
content_digest_header: &str,
signature: &str,
status: u16,
body: &str,
public_key_b64: &str,
) -> bool {
if let Ok(ts) = chrono::DateTime::parse_from_rfc3339(timestamp) {
let skew = now_ms_unix().abs_diff(ts.timestamp_millis() as u64);
if skew > MAX_CLOCK_SKEW_MS {
return false;
}
} else {
return false;
}
if compute_content_digest(body) != content_digest_header {
return false;
}
let signing_input = serde_json::json!({
"v": version,
"from": from,
"kid": key_id,
"ts": timestamp,
"status": status,
"contentDigest": content_digest_header,
});
verify_with_domain_separator(SEPARATOR_HTTP_RESPONSE, public_key_b64, &signing_input, signature)
.unwrap_or(false)
}

#[derive(Debug, thiserror::Error)]
pub enum CryptoError {
#[error("invalid base64 encoding")]
Expand Down
Loading