mirror of
https://github.com/block/buzz.git
synced 2026-11-27 03:31:50 +00:00
feat(keyless): route broker capabilities
Signed-off-by: Joel Robotham <jrobotham@squareup.com>
This commit is contained in:
@@ -12,14 +12,15 @@ The backend is selected by `--agent-mode` (env `BUZZ_AGENT_MODE`), default
|
||||
- `broker` — keyless; route every operation through a broker host.
|
||||
|
||||
Broker mode currently covers: `messages get` (with `--mentions-only`, the wake
|
||||
path), `messages send` / reply, `reactions add`, `users set-profile`, and
|
||||
`mem address <slug>` as an addressing-only bridge for encrypted memory. Every
|
||||
other command still needs the local backend.
|
||||
path), `messages send` / reply, `reactions add`, `users set-profile/set-presence`, and
|
||||
`mem address/get/set/hash`. The ACP runtime also routes core-memory reads,
|
||||
presence, typing, observer telemetry, and turn liveness through the broker.
|
||||
Commands without a matching broker capability still need the local backend.
|
||||
|
||||
The same provisioning variables now select the prototype keyless `buzz-acp`
|
||||
runtime. It derives its public identity through `storage.address`, polls
|
||||
configured channels through `channel.read`, and passes broker provisioning to
|
||||
the CLI used by the spawned agent. See
|
||||
configured channels through `channel.read`, uses broker-backed memory and live
|
||||
signals, and passes broker provisioning to the CLI used by the spawned agent. See
|
||||
[`../buzz-acp/README.md`](../buzz-acp/README.md#keyless-broker-mode-prototype)
|
||||
for the runtime command and its deliberate housekeeping limits.
|
||||
|
||||
@@ -57,7 +58,10 @@ buzz messages send --channel "$CH" --reply-to <event-id> --content "on it"
|
||||
buzz messages get --channel "$CH" --mentions-only --limit 10
|
||||
buzz reactions add --channel "$CH" --event <event-id> --emoji "👍"
|
||||
buzz users set-profile --name "Ada" --about "a keyless agent"
|
||||
buzz users set-presence online
|
||||
buzz mem address core
|
||||
buzz mem get core
|
||||
buzz mem set core "I am Ada."
|
||||
```
|
||||
|
||||
Terminal 1 logs each action, the bearer credential, and the args it received.
|
||||
@@ -85,17 +89,14 @@ is a minimal reference for the wire shape.
|
||||
- Broker HTTP actions have a 30-second end-to-end transport timeout. A runtime
|
||||
credential rejected as `unauthenticated` is terminal instead of being polled
|
||||
forever.
|
||||
- Runtime cursors and event deduplication are currently in memory only. The
|
||||
first cursorless read after restart follows the host's default-window
|
||||
semantics, which must be pinned at the real-host integration checkpoint to
|
||||
prevent missed or replayed mentions.
|
||||
- Runtime cursors and event deduplication are currently in memory only. Once a
|
||||
pagination chain ends, polling returns to the host's default window and
|
||||
bounded event-ID deduplication absorbs replayed messages.
|
||||
- This CLI slice exposes only the first `messages get --limit` window; broker
|
||||
cursor pagination and thread reads are not yet command-line options. The ACP
|
||||
runtime therefore prompts from the triggering event without relay-fetched
|
||||
thread history.
|
||||
- `buzz mem address <slug>` prints the broker's `{authorPubkey, kind, dTag}`
|
||||
outcome as JSON. This temporary bridge proves secret-dependent address
|
||||
derivation without giving the client a key or relay route. It does not yet
|
||||
make `mem get/set/patch/rm` keyless; fetching, decrypting, encrypting, and
|
||||
publishing memory records belong to the later end-to-end runtime storage
|
||||
work.
|
||||
- `buzz mem address <slug>` prints `{authorPubkey, kind, dTag}`. `mem get/set`
|
||||
use broker-side decryption/encryption and `mem hash` composes a read locally.
|
||||
Listing, patching, and deletion remain unavailable because listing and
|
||||
tombstone semantics are not represented by the current contract.
|
||||
|
||||
@@ -73,6 +73,42 @@ async fn action(headers: axum::http::HeaderMap, body: Bytes) -> Response {
|
||||
"dTag": FAKE_EVENT_ID,
|
||||
}),
|
||||
),
|
||||
"storage.get" => succeeded(
|
||||
request_id,
|
||||
action,
|
||||
serde_json::json!({ "value": "I am a keyless agent using broker-backed memory." }),
|
||||
),
|
||||
"storage.put" => succeeded(
|
||||
request_id,
|
||||
action,
|
||||
serde_json::json!({ "eventId": FAKE_EVENT_ID, "kind": 30174, "createdAt": 1_700_000_000u64 }),
|
||||
),
|
||||
"presence.set" => succeeded(
|
||||
request_id,
|
||||
action,
|
||||
serde_json::json!({ "eventId": FAKE_EVENT_ID, "kind": 20001, "createdAt": 1_700_000_000u64 }),
|
||||
),
|
||||
"typing.set" => succeeded(
|
||||
request_id,
|
||||
action,
|
||||
serde_json::json!({ "eventId": FAKE_EVENT_ID, "kind": 20002, "createdAt": 1_700_000_000u64 }),
|
||||
),
|
||||
"observer.emit" => succeeded(
|
||||
request_id,
|
||||
action,
|
||||
serde_json::json!({
|
||||
"accepted": request
|
||||
.get("args")
|
||||
.and_then(|args| args.get("frames"))
|
||||
.and_then(|frames| frames.as_array())
|
||||
.map_or(0, Vec::len),
|
||||
}),
|
||||
),
|
||||
"liveness.ping" => succeeded(
|
||||
request_id,
|
||||
action,
|
||||
serde_json::json!({ "eventId": FAKE_EVENT_ID, "kind": 24200, "createdAt": 1_700_000_000u64 }),
|
||||
),
|
||||
"channel.read" => succeeded(request_id, action, serde_json::json!({ "messages": [] })),
|
||||
other => serde_json::json!({
|
||||
"type": "broker_result",
|
||||
|
||||
@@ -14,7 +14,8 @@ use uuid::Uuid;
|
||||
use buzz_sdk::broker::{
|
||||
ActionArgs, ActionOutcome, BrokerClientExt, BrokerError, BrokerRequest, BrokerResult,
|
||||
ChannelReadArgs, EventPublished, MessagePage, MessagePostArgs, MessageReplyArgs,
|
||||
ProfileSetArgs, PubkeyHex, ReactionAddArgs, StorageAddress, StorageAddressArgs,
|
||||
PresenceSetArgs, ProfileSetArgs, PubkeyHex, ReactionAddArgs, StorageAddress,
|
||||
StorageAddressArgs, StorageGetArgs, StoragePutArgs, StorageRecord,
|
||||
};
|
||||
use buzz_sdk::ThreadRef;
|
||||
|
||||
@@ -34,7 +35,10 @@ pub trait AgentBackend {
|
||||
async fn message_reply(&self, args: MessageReplyArgs) -> Result<EventPublished, CliError>;
|
||||
async fn reaction_add(&self, args: ReactionAddArgs) -> Result<EventPublished, CliError>;
|
||||
async fn profile_set(&self, args: ProfileSetArgs) -> Result<EventPublished, CliError>;
|
||||
async fn presence_set(&self, args: PresenceSetArgs) -> Result<EventPublished, CliError>;
|
||||
async fn storage_address(&self, args: StorageAddressArgs) -> Result<StorageAddress, CliError>;
|
||||
async fn storage_get(&self, args: StorageGetArgs) -> Result<StorageRecord, CliError>;
|
||||
async fn storage_put(&self, args: StoragePutArgs) -> Result<EventPublished, CliError>;
|
||||
}
|
||||
|
||||
/// Keyless backend: no key, no relay route. Every operation is a broker request.
|
||||
@@ -102,12 +106,33 @@ impl AgentBackend for BrokerBackend {
|
||||
}
|
||||
}
|
||||
|
||||
async fn presence_set(&self, args: PresenceSetArgs) -> Result<EventPublished, CliError> {
|
||||
match self.run(ActionArgs::PresenceSet(args)).await? {
|
||||
ActionOutcome::PresenceSet(published) => Ok(published),
|
||||
_ => Err(unexpected_outcome("presence.set")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn storage_address(&self, args: StorageAddressArgs) -> Result<StorageAddress, CliError> {
|
||||
match self.run(ActionArgs::StorageAddress(args)).await? {
|
||||
ActionOutcome::StorageAddress(address) => Ok(address),
|
||||
_ => Err(unexpected_outcome("storage.address")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn storage_get(&self, args: StorageGetArgs) -> Result<StorageRecord, CliError> {
|
||||
match self.run(ActionArgs::StorageGet(args)).await? {
|
||||
ActionOutcome::StorageGet(record) => Ok(record),
|
||||
_ => Err(unexpected_outcome("storage.get")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn storage_put(&self, args: StoragePutArgs) -> Result<EventPublished, CliError> {
|
||||
match self.run(ActionArgs::StoragePut(args)).await? {
|
||||
ActionOutcome::StoragePut(published) => Ok(published),
|
||||
_ => Err(unexpected_outcome("storage.put")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Local backend: holds the key and talks to the relay directly. Preserves
|
||||
@@ -235,6 +260,12 @@ impl AgentBackend for LocalBackend {
|
||||
self.publish(event).await
|
||||
}
|
||||
|
||||
async fn presence_set(&self, _args: PresenceSetArgs) -> Result<EventPublished, CliError> {
|
||||
Err(CliError::Other(
|
||||
"local presence updates use the existing signed command path".into(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn storage_address(&self, args: StorageAddressArgs) -> Result<StorageAddress, CliError> {
|
||||
let owner = crate::commands::mem::resolve_owner(&self.client, None)?;
|
||||
let conversation_key =
|
||||
@@ -246,6 +277,18 @@ impl AgentBackend for LocalBackend {
|
||||
d_tag: buzz_core::engram::d_tag(&conversation_key, &args.slug),
|
||||
})
|
||||
}
|
||||
|
||||
async fn storage_get(&self, _args: StorageGetArgs) -> Result<StorageRecord, CliError> {
|
||||
Err(CliError::Other(
|
||||
"local storage reads use the existing encrypted-memory command path".into(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn storage_put(&self, _args: StoragePutArgs) -> Result<EventPublished, CliError> {
|
||||
Err(CliError::Other(
|
||||
"local storage writes use the existing encrypted-memory command path".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// A runtime-selected backend. Implements [`AgentBackend`] by dispatch, so
|
||||
@@ -257,11 +300,13 @@ pub enum Backend {
|
||||
|
||||
impl Backend {
|
||||
/// Keyless: talk to a broker `base_url` with `credential`.
|
||||
#[must_use]
|
||||
pub fn broker(base_url: impl Into<String>, credential: impl Into<String>) -> Self {
|
||||
Self::Broker(BrokerBackend::new(HttpBrokerClient::new(
|
||||
base_url, credential,
|
||||
)))
|
||||
pub fn broker(
|
||||
base_url: impl Into<String>,
|
||||
credential: impl Into<String>,
|
||||
) -> Result<Self, CliError> {
|
||||
let client = HttpBrokerClient::new(base_url, credential)
|
||||
.map_err(|error| CliError::Usage(format!("invalid broker configuration: {error}")))?;
|
||||
Ok(Self::Broker(BrokerBackend::new(client)))
|
||||
}
|
||||
|
||||
/// Local: hold the key and talk to the relay.
|
||||
@@ -307,12 +352,33 @@ impl AgentBackend for Backend {
|
||||
}
|
||||
}
|
||||
|
||||
async fn presence_set(&self, args: PresenceSetArgs) -> Result<EventPublished, CliError> {
|
||||
match self {
|
||||
Self::Local(b) => b.presence_set(args).await,
|
||||
Self::Broker(b) => b.presence_set(args).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn storage_address(&self, args: StorageAddressArgs) -> Result<StorageAddress, CliError> {
|
||||
match self {
|
||||
Self::Local(b) => b.storage_address(args).await,
|
||||
Self::Broker(b) => b.storage_address(args).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn storage_get(&self, args: StorageGetArgs) -> Result<StorageRecord, CliError> {
|
||||
match self {
|
||||
Self::Local(b) => b.storage_get(args).await,
|
||||
Self::Broker(b) => b.storage_get(args).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn storage_put(&self, args: StoragePutArgs) -> Result<EventPublished, CliError> {
|
||||
match self {
|
||||
Self::Local(b) => b.storage_put(args).await,
|
||||
Self::Broker(b) => b.storage_put(args).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn broker_verdict(status: &str, error: &BrokerError) -> CliError {
|
||||
@@ -377,7 +443,7 @@ mod tests {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr: SocketAddr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
BrokerBackend::new(HttpBrokerClient::new(format!("http://{addr}"), "cred"))
|
||||
BrokerBackend::new(HttpBrokerClient::new(format!("http://{addr}"), "cred").unwrap())
|
||||
}
|
||||
|
||||
fn succeeded(rid: &str, action: &str, outcome: serde_json::Value) -> (StatusCode, String) {
|
||||
@@ -515,6 +581,41 @@ mod tests {
|
||||
assert_eq!(address.d_tag, EVENT_ID);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn broker_storage_get_returns_plaintext_or_absence() {
|
||||
let backend = spawn_host(|rid, action| {
|
||||
succeeded(rid, action, serde_json::json!({ "value": "remember me" }))
|
||||
})
|
||||
.await;
|
||||
let record = backend
|
||||
.storage_get(StorageGetArgs {
|
||||
slug: "core".into(),
|
||||
})
|
||||
.await
|
||||
.expect("record");
|
||||
assert_eq!(record.value.as_deref(), Some("remember me"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn broker_storage_put_returns_the_published_event() {
|
||||
let backend = spawn_host(|rid, action| {
|
||||
succeeded(
|
||||
rid,
|
||||
action,
|
||||
serde_json::json!({ "eventId": EVENT_ID, "kind": 30174, "createdAt": 1_700_000_000u64 }),
|
||||
)
|
||||
})
|
||||
.await;
|
||||
let published = backend
|
||||
.storage_put(StoragePutArgs {
|
||||
slug: "core".into(),
|
||||
value: "remember me".into(),
|
||||
})
|
||||
.await
|
||||
.expect("published");
|
||||
assert_eq!(published.kind, 30174);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn broker_read_returns_a_page_of_signed_events() {
|
||||
// A real signed event, so the strict event reader accepts it.
|
||||
|
||||
@@ -24,7 +24,7 @@ use buzz_core::engram::{
|
||||
self, conversation_key, d_tag, normalize_slug, select_head, validate_and_decrypt, Body, Listing,
|
||||
};
|
||||
use buzz_core::kind::KIND_AGENT_ENGRAM;
|
||||
use buzz_sdk::broker::StorageAddressArgs;
|
||||
use buzz_sdk::broker::{StorageAddressArgs, StorageGetArgs, StoragePutArgs};
|
||||
use nostr::PublicKey;
|
||||
|
||||
use crate::backend::{AgentBackend, Backend};
|
||||
@@ -804,11 +804,16 @@ pub async fn dispatch(cmd: crate::MemCmd, client: &BuzzClient) -> Result<(), Cli
|
||||
}
|
||||
}
|
||||
|
||||
/// Keyless (broker) dispatch for encrypted-memory addressing only.
|
||||
///
|
||||
/// The returned coordinates are intentionally surfaced as-is. They identify
|
||||
/// the encrypted record but do not, by themselves, provide read, decrypt,
|
||||
/// encrypt, or publish semantics; those remain a later runtime slice.
|
||||
async fn broker_value(backend: &Backend, slug: String) -> Result<String, CliError> {
|
||||
backend
|
||||
.storage_get(StorageGetArgs { slug: slug.clone() })
|
||||
.await?
|
||||
.value
|
||||
.ok_or_else(|| CliError::NotFound(format!("not found: {slug}")))
|
||||
}
|
||||
|
||||
/// Keyless (broker) dispatch. The host owns encryption, signing, and relay
|
||||
/// publication; the CLI sees only slug-addressed plaintext records.
|
||||
pub async fn dispatch_broker(cmd: crate::MemCmd, backend: &Backend) -> Result<(), CliError> {
|
||||
use crate::MemCmd;
|
||||
match cmd {
|
||||
@@ -823,9 +828,82 @@ pub async fn dispatch_broker(cmd: crate::MemCmd, backend: &Backend) -> Result<()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(CliError::Usage(
|
||||
"keyless (broker) mode supports only 'mem address' in this group; encrypted-memory \
|
||||
reads and writes need the later runtime storage slice"
|
||||
MemCmd::Get { slug, owner, agent } => {
|
||||
if owner.is_some() || agent.is_some() {
|
||||
return Err(CliError::Usage(
|
||||
"--owner/--agent are unavailable in broker mode; identity is credential-bound"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let slug = normalize_slug(&slug)
|
||||
.map_err(|e| CliError::Usage(format!("invalid slug: {e}")))?;
|
||||
use std::io::Write;
|
||||
std::io::stdout()
|
||||
.write_all(broker_value(backend, slug).await?.as_bytes())
|
||||
.map_err(|e| CliError::Other(e.to_string()))
|
||||
}
|
||||
MemCmd::Hash { slug, owner, agent } => {
|
||||
if owner.is_some() || agent.is_some() {
|
||||
return Err(CliError::Usage(
|
||||
"--owner/--agent are unavailable in broker mode; identity is credential-bound"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let slug = normalize_slug(&slug)
|
||||
.map_err(|e| CliError::Usage(format!("invalid slug: {e}")))?;
|
||||
println!("{}", sha256_hex(&broker_value(backend, slug).await?));
|
||||
Ok(())
|
||||
}
|
||||
MemCmd::Set {
|
||||
slug,
|
||||
value,
|
||||
owner,
|
||||
allow_empty,
|
||||
} => {
|
||||
if owner.is_some() {
|
||||
return Err(CliError::Usage(
|
||||
"--owner is unavailable in broker mode; identity is credential-bound".into(),
|
||||
));
|
||||
}
|
||||
let slug = normalize_slug(&slug)
|
||||
.map_err(|e| CliError::Usage(format!("invalid slug: {e}")))?;
|
||||
let value = if value == "-" {
|
||||
let mut input = String::new();
|
||||
std::io::stdin()
|
||||
.take((engram::NIP44_PLAINTEXT_MAX + 1) as u64)
|
||||
.read_to_string(&mut input)
|
||||
.map_err(|e| CliError::Other(format!("stdin read failed: {e}")))?;
|
||||
input
|
||||
} else {
|
||||
value
|
||||
};
|
||||
if value.is_empty() {
|
||||
let detail = if allow_empty {
|
||||
"the broker storage contract does not support empty records"
|
||||
} else {
|
||||
"refusing to write an empty broker record"
|
||||
};
|
||||
return Err(CliError::Usage(detail.into()));
|
||||
}
|
||||
let published = backend
|
||||
.storage_put(StoragePutArgs { slug: slug.clone(), value })
|
||||
.await?;
|
||||
eprintln!(
|
||||
"wrote {slug} (event {}, created_at {})",
|
||||
published.event_id, published.created_at
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
MemCmd::Ls { .. } => Err(CliError::Usage(
|
||||
"'mem ls' is unavailable in broker mode because the contract has no storage listing action"
|
||||
.into(),
|
||||
)),
|
||||
MemCmd::Patch { .. } => Err(CliError::Usage(
|
||||
"'mem patch' is not yet wired to broker read-modify-write; use mem get/hash/set"
|
||||
.into(),
|
||||
)),
|
||||
MemCmd::Rm { .. } => Err(CliError::Usage(
|
||||
"'mem rm' is unavailable because the broker contract has no delete/tombstone action"
|
||||
.into(),
|
||||
)),
|
||||
}
|
||||
|
||||
@@ -424,7 +424,7 @@ pub async fn cmd_set_profile(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keyless (broker) dispatch for the users group: `set-profile` only.
|
||||
/// Keyless (broker) dispatch for profile and presence updates.
|
||||
pub async fn dispatch_broker(cmd: crate::UsersCmd, backend: &Backend) -> Result<(), CliError> {
|
||||
use crate::UsersCmd;
|
||||
match cmd {
|
||||
@@ -460,8 +460,25 @@ pub async fn dispatch_broker(cmd: crate::UsersCmd, backend: &Backend) -> Result<
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
UsersCmd::SetPresence { status } => {
|
||||
let status = match status {
|
||||
crate::PresenceStatus::Online => buzz_core::presence::PresenceStatus::Online,
|
||||
crate::PresenceStatus::Away => buzz_core::presence::PresenceStatus::Away,
|
||||
crate::PresenceStatus::Offline => buzz_core::presence::PresenceStatus::Offline,
|
||||
};
|
||||
let published = backend
|
||||
.presence_set(buzz_sdk::broker::PresenceSetArgs { status })
|
||||
.await?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&published)
|
||||
.map_err(|e| CliError::Other(format!("serialize outcome: {e}")))?
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(CliError::Usage(
|
||||
"keyless (broker) mode supports only 'users set-profile' in this group".into(),
|
||||
"keyless (broker) mode supports only 'users set-profile' and 'users set-presence' in this group"
|
||||
.into(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2171,7 +2171,7 @@ async fn run_broker(cli: Cli) -> Result<(), CliError> {
|
||||
.into(),
|
||||
)
|
||||
})?;
|
||||
let backend = backend::Backend::broker(base_url, credential);
|
||||
let backend = backend::Backend::broker(base_url, credential)?;
|
||||
|
||||
match cli.command {
|
||||
Cmd::Messages(sub) => commands::messages::dispatch_broker(sub, &backend).await,
|
||||
@@ -2179,9 +2179,8 @@ async fn run_broker(cli: Cli) -> Result<(), CliError> {
|
||||
Cmd::Users(sub) => commands::users::dispatch_broker(sub, &backend).await,
|
||||
Cmd::Mem(sub) => commands::mem::dispatch_broker(sub, &backend).await,
|
||||
_ => Err(CliError::Usage(
|
||||
"keyless (broker) mode currently supports the wake→reply slice plus reactions and \
|
||||
profile, plus encrypted-memory addressing: 'messages get/send', 'reactions add', \
|
||||
'users set-profile', and 'mem address'. Other commands need the local backend — \
|
||||
"keyless (broker) mode currently supports messages, reactions, profile/presence updates, and \
|
||||
broker-backed memory get/set/address/hash. Other commands need the local backend — \
|
||||
unset --agent-mode or set it to 'local'"
|
||||
.into(),
|
||||
)),
|
||||
|
||||
Reference in New Issue
Block a user