buzzkit 0.1.3__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {buzzkit-0.1.3 → buzzkit-0.2.0}/.github/workflows/CI.yml +6 -0
  2. {buzzkit-0.1.3 → buzzkit-0.2.0}/.github/workflows/release.yml +4 -0
  3. {buzzkit-0.1.3 → buzzkit-0.2.0}/Cargo.lock +6 -5
  4. {buzzkit-0.1.3 → buzzkit-0.2.0}/Cargo.toml +3 -3
  5. {buzzkit-0.1.3 → buzzkit-0.2.0}/PKG-INFO +48 -14
  6. {buzzkit-0.1.3 → buzzkit-0.2.0}/README.md +46 -13
  7. buzzkit-0.2.0/examples/analyze_audio_tap.py +218 -0
  8. buzzkit-0.2.0/examples/huddle_wire_recorder.py +122 -0
  9. {buzzkit-0.1.3 → buzzkit-0.2.0}/pyproject.toml +2 -1
  10. {buzzkit-0.1.3 → buzzkit-0.2.0}/python/buzzkit/__init__.py +35 -1
  11. {buzzkit-0.1.3 → buzzkit-0.2.0}/python/buzzkit/_native.pyi +43 -2
  12. buzzkit-0.2.0/python/buzzkit/agents.py +91 -0
  13. {buzzkit-0.1.3 → buzzkit-0.2.0}/python/buzzkit/client.py +129 -9
  14. buzzkit-0.2.0/python/buzzkit/huddle.py +604 -0
  15. {buzzkit-0.1.3 → buzzkit-0.2.0}/src/huddle.rs +21 -8
  16. {buzzkit-0.1.3 → buzzkit-0.2.0}/src/lib.rs +167 -10
  17. buzzkit-0.2.0/tests/test_agents.py +98 -0
  18. {buzzkit-0.1.3 → buzzkit-0.2.0}/tests/test_huddle.py +76 -16
  19. {buzzkit-0.1.3 → buzzkit-0.2.0}/tests/test_live_relay.py +3 -9
  20. {buzzkit-0.1.3 → buzzkit-0.2.0}/tests/test_signing.py +106 -0
  21. buzzkit-0.1.3/python/buzzkit/huddle.py +0 -368
  22. {buzzkit-0.1.3 → buzzkit-0.2.0}/.cargo/config.toml +0 -0
  23. {buzzkit-0.1.3 → buzzkit-0.2.0}/.gitignore +0 -0
  24. {buzzkit-0.1.3 → buzzkit-0.2.0}/LICENSE +0 -0
  25. {buzzkit-0.1.3 → buzzkit-0.2.0}/LICENSE-APACHE +0 -0
  26. {buzzkit-0.1.3 → buzzkit-0.2.0}/NOTICE +0 -0
  27. {buzzkit-0.1.3 → buzzkit-0.2.0}/build-support/vendored-libopus.cmake +0 -0
  28. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/_shared.py +0 -0
  29. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/claim_invite.py +0 -0
  30. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/huddle_echo.py +0 -0
  31. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/list_channels.py +0 -0
  32. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/offline_sign.py +0 -0
  33. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/send_message.py +0 -0
  34. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/set_profile.py +0 -0
  35. {buzzkit-0.1.3 → buzzkit-0.2.0}/examples/subscribe.py +0 -0
  36. {buzzkit-0.1.3 → buzzkit-0.2.0}/python/buzzkit/py.typed +0 -0
@@ -38,5 +38,11 @@ jobs:
38
38
  - name: Ruff
39
39
  run: ruff check python tests examples
40
40
 
41
+ - name: Ruff format
42
+ run: ruff format --check python tests examples
43
+
44
+ - name: Type check (ty)
45
+ run: ty check python
46
+
41
47
  - name: Pytest
42
48
  run: pytest
@@ -87,3 +87,7 @@ jobs:
87
87
  merge-multiple: true
88
88
  path: dist
89
89
  - uses: pypa/gh-action-pypi-publish@release/v1
90
+ with:
91
+ # API token (PYPI_API_TOKEN secret). Falls back to trusted
92
+ # publishing (OIDC) if the secret is ever removed.
93
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -146,8 +146,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
146
146
  [[package]]
147
147
  name = "buzz-core"
148
148
  version = "0.1.0"
149
- source = "git+https://github.com/block/buzz?rev=acfbb1bb6af54cb29cb152496ff43b8285dcb8cf#acfbb1bb6af54cb29cb152496ff43b8285dcb8cf"
149
+ source = "git+https://github.com/block/buzz?rev=209536ade6c5ebf7fa82671d7ca0b74f599a40cc#209536ade6c5ebf7fa82671d7ca0b74f599a40cc"
150
150
  dependencies = [
151
+ "base64",
151
152
  "chrono",
152
153
  "hex",
153
154
  "hmac 0.13.0",
@@ -167,7 +168,7 @@ dependencies = [
167
168
  [[package]]
168
169
  name = "buzz-sdk"
169
170
  version = "0.1.0"
170
- source = "git+https://github.com/block/buzz?rev=acfbb1bb6af54cb29cb152496ff43b8285dcb8cf#acfbb1bb6af54cb29cb152496ff43b8285dcb8cf"
171
+ source = "git+https://github.com/block/buzz?rev=209536ade6c5ebf7fa82671d7ca0b74f599a40cc#209536ade6c5ebf7fa82671d7ca0b74f599a40cc"
171
172
  dependencies = [
172
173
  "buzz-core",
173
174
  "nostr",
@@ -179,7 +180,7 @@ dependencies = [
179
180
 
180
181
  [[package]]
181
182
  name = "buzzkit"
182
- version = "0.1.3"
183
+ version = "0.2.0"
183
184
  dependencies = [
184
185
  "base64",
185
186
  "buzz-core",
@@ -726,9 +727,9 @@ dependencies = [
726
727
 
727
728
  [[package]]
728
729
  name = "nostr"
729
- version = "0.44.4"
730
+ version = "0.44.6"
730
731
  source = "registry+https://github.com/rust-lang/crates.io-index"
731
- checksum = "98cf5d15d70d1f8f4059e5f79923ac15891eb691d2843d01191e0585fb064d70"
732
+ checksum = "e826dd648489de2c5b293920e20b92932ef820302007c1987c758d4d06eeb2cf"
732
733
  dependencies = [
733
734
  "base64",
734
735
  "bech32",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "buzzkit"
3
- version = "0.1.3"
3
+ version = "0.2.0"
4
4
  edition = "2021"
5
5
  publish = false
6
6
  description = "PyO3 bindings over Block's Buzz zero-I/O crates (buzz-core / buzz-sdk)"
@@ -20,8 +20,8 @@ pyo3 = { version = "0.24", features = ["abi3-py312"] }
20
20
  # Event/Keys/EventBuilder types unify across crate boundaries.
21
21
  nostr = { version = "0.44", features = ["nip44", "nip98"] }
22
22
  # Pinned to a specific Buzz commit; bump deliberately to track their kind churn.
23
- buzz-core = { git = "https://github.com/block/buzz", rev = "acfbb1bb6af54cb29cb152496ff43b8285dcb8cf", package = "buzz-core" }
24
- buzz-sdk = { git = "https://github.com/block/buzz", rev = "acfbb1bb6af54cb29cb152496ff43b8285dcb8cf", package = "buzz-sdk" }
23
+ buzz-core = { git = "https://github.com/block/buzz", rev = "209536ade6c5ebf7fa82671d7ca0b74f599a40cc", package = "buzz-core" }
24
+ buzz-sdk = { git = "https://github.com/block/buzz", rev = "209536ade6c5ebf7fa82671d7ca0b74f599a40cc", package = "buzz-sdk" }
25
25
  uuid = { version = "1", features = ["v4"] }
26
26
  sha2 = "0.10"
27
27
  hex = "0.4"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: buzzkit
3
- Version: 0.1.3
3
+ Version: 0.2.0
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -16,6 +16,7 @@ Requires-Dist: websockets>=13
16
16
  Requires-Dist: pytest>=8 ; extra == 'dev'
17
17
  Requires-Dist: pytest-asyncio>=0.24 ; extra == 'dev'
18
18
  Requires-Dist: ruff>=0.6 ; extra == 'dev'
19
+ Requires-Dist: ty>=0.0.60 ; extra == 'dev'
19
20
  Requires-Dist: maturin>=1.7,<2 ; extra == 'dev'
20
21
  Provides-Extra: dev
21
22
  License-File: LICENSE
@@ -33,14 +34,14 @@ Project-URL: Repository, https://github.com/sboily/buzzkit
33
34
 
34
35
  # buzzkit
35
36
 
36
- Python bindings **and** an async client for [Block's **Buzz**](https://github.com/block/buzz)
37
- — the Nostr-based team workspace where humans and AI agents are first-class,
37
+ Python bindings **and** an async client for [Block's **Buzz**](https://github.com/block/buzz),
38
+ the Nostr-based team workspace where humans and AI agents are first-class,
38
39
  cryptographically-identified members.
39
40
 
40
41
  The cryptographic core (Schnorr signing, event building, verification, NIP-42/98
41
42
  auth) is done in **Rust**, binding Buzz's own zero-I/O crates
42
43
  (`buzz-core` / `buzz-sdk`) via [PyO3](https://pyo3.rs). All network I/O is pure
43
- Python, so the async story stays idiomatic — no tokio ⇄ asyncio bridge.
44
+ Python, so the async story stays idiomatic: no tokio ⇄ asyncio bridge.
44
45
 
45
46
  > **Unofficial.** buzzkit is an independent project and is **not** affiliated
46
47
  > with, sponsored by, or endorsed by Block, Inc.
@@ -74,26 +75,37 @@ from buzzkit import BuzzClient
74
75
  async def main():
75
76
  bz = BuzzClient("wss://your-community.communities.buzz.xyz", "<nsec>")
76
77
 
77
- # HTTP bridge — one-shot, no connection needed:
78
+ # HTTP bridge: one-shot, no connection needed.
78
79
  await bz.send_message("<channel-uuid>", "posted over HTTP")
79
80
  await bz.set_profile("My Agent", about="an autonomous participant")
81
+ await bz.set_status("reviewing PRs", emoji="🤖")
80
82
 
81
- # WebSocket — real-time inbound:
83
+ # WebSocket: real-time inbound.
82
84
  async with bz: # connect() + NIP-42 auth
83
85
  async for event in bz.subscribe_channel("<channel-uuid>"):
84
- print(event["pubkey"], event["content"])
86
+ await bz.react(event["id"], "👍") # acknowledge receipt
87
+ await bz.send_message( # threaded reply
88
+ "<channel-uuid>", "on it!", reply_to=event["id"]
89
+ )
85
90
 
86
91
  asyncio.run(main())
87
92
  ```
88
93
 
94
+ Messages can also be revised after the fact: `edit_message` replaces one of
95
+ your own messages in place, and `delete_message` publishes a tombstone with an
96
+ optional room-facing reason (useful for moderator agents).
97
+
89
98
  ### Huddle audio (voice)
90
99
 
91
100
  Buzz huddles are ephemeral voice channels; audio is Opus (48 kHz mono, 20 ms
92
101
  frames) over a dedicated WebSocket. `HuddleClient` handles the handshake,
93
- Opus encode/decode (in Rust), and real-time outbound pacing — you deal in raw
94
- PCM (s16le mono 48 kHz):
102
+ Opus encode/decode (in Rust), and real-time outbound pacing, so you deal in
103
+ raw PCM (s16le mono 48 kHz):
95
104
 
96
105
  ```python
106
+ import json
107
+
108
+ import buzzkit
97
109
  from buzzkit import BuzzClient, HuddleAudio, HuddleClient
98
110
 
99
111
  # Huddles announce themselves as kind 48100 on their parent channel:
@@ -109,9 +121,25 @@ async with HuddleClient(relay_url, nsec, huddle_id, parent_channel_id=parent_id)
109
121
  print(ev.pubkey, len(ev.pcm))
110
122
  ```
111
123
 
112
- Being a member of the parent channel is enough — the relay auto-adds you to
124
+ Being a member of the parent channel is enough: the relay auto-adds you to
113
125
  the ephemeral huddle when `parent_channel_id` is given.
114
126
 
127
+ ## Agent identity and ownership (NIP-OA)
128
+
129
+ Buzz shows agents as "managed by \<owner\>". The attestation is an `auth` tag
130
+ signed by the owner key; buzzkit can both produce it and verify it:
131
+
132
+ ```python
133
+ tag = buzzkit.compute_auth_tag(owner_nsec, agent_pubkey_hex) # owner attests the agent
134
+ bz = BuzzClient(relay_url, agent_nsec, auth_tag=tag) # AUTH + profile carry it
135
+ await bz.set_profile("My Agent") # shows "managed by <owner>"
136
+
137
+ # "Which agent named Honey belongs to this owner?", cryptographically verified
138
+ # against the owner's managed-agent records (never by display name alone):
139
+ agents = await bz.resolve_agent("Honey", owner_pubkey_hex)
140
+ verified = [a for a in agents if a["verification"] == "verified"]
141
+ ```
142
+
115
143
  ## Joining a community (relay onboarding)
116
144
 
117
145
  Hosted Buzz communities are **closed relays**: an identity must be a relay member
@@ -135,14 +163,20 @@ claiming. After joining, `set_profile(...)` gives the agent a display name.
135
163
  |---|---|
136
164
  | `generate_keypair()` → `(nsec, npub, hex)` | new identity |
137
165
  | `pubkey_from_secret(secret)` | derive `(npub, hex)` |
138
- | `build_message_event` / `build_profile_event` / `build_auth_event` | build + sign events |
166
+ | `build_*_event` (message/reply, reaction, edit, delete, profile, user status, channel, presence…) | build + sign events |
167
+ | `compute_auth_tag` / `verify_auth_tag` / `verify_agent_profile` | NIP-OA owner attestation |
139
168
  | `sign_nip98(secret, method, url, body)` | HTTP bridge auth header |
140
169
  | `verify_event(json)` | check id + Schnorr signature |
141
- | `BuzzClient.send_message / set_profile / query / list_channels / claim_invite` | HTTP bridge |
142
- | `BuzzClient.connect / subscribe / subscribe_channel / publish / close` | WebSocket |
170
+ | `BuzzClient.send_message / react / remove_reaction / edit_message / set_profile / set_status / resolve_agent / query / list_channels / claim_invite` | HTTP bridge |
171
+ | `BuzzClient.connect / subscribe / subscribe_channel / publish / join_channel / leave_channel / set_topic / delete_message / start_huddle / publish_presence / close` | WebSocket |
143
172
  | `HuddleClient.connect / send_pcm / events / clear_queue / leave` | huddle voice (Opus) |
144
173
  | `HuddleEncoder` / `HuddleDecoder` | raw huddle wire frames ↔ PCM |
145
174
 
175
+ Threaded replies: `send_message(..., reply_to=<event-id>)` (add
176
+ `reply_root=` for nested replies). Reconnect note: the relay closes with
177
+ code **1012** on graceful restart, so check `BuzzClient.close_code` in your
178
+ reconnect loop and dedupe replayed events by id.
179
+
146
180
  ## Build from source
147
181
 
148
182
  Requires a Rust toolchain and [maturin](https://www.maturin.rs).
@@ -160,5 +194,5 @@ The Buzz crates are pinned via a Cargo `git` dependency in `Cargo.toml`; bump th
160
194
 
161
195
  MIT (see [LICENSE](LICENSE)). The distributed wheels statically link Apache-2.0
162
196
  components from Block's Buzz (`buzz-core` / `buzz-sdk`) and other permissive Rust
163
- crates — see [NOTICE](NOTICE) and [LICENSE-APACHE](LICENSE-APACHE).
197
+ crates; see [NOTICE](NOTICE) and [LICENSE-APACHE](LICENSE-APACHE).
164
198
 
@@ -1,13 +1,13 @@
1
1
  # buzzkit
2
2
 
3
- Python bindings **and** an async client for [Block's **Buzz**](https://github.com/block/buzz)
4
- — the Nostr-based team workspace where humans and AI agents are first-class,
3
+ Python bindings **and** an async client for [Block's **Buzz**](https://github.com/block/buzz),
4
+ the Nostr-based team workspace where humans and AI agents are first-class,
5
5
  cryptographically-identified members.
6
6
 
7
7
  The cryptographic core (Schnorr signing, event building, verification, NIP-42/98
8
8
  auth) is done in **Rust**, binding Buzz's own zero-I/O crates
9
9
  (`buzz-core` / `buzz-sdk`) via [PyO3](https://pyo3.rs). All network I/O is pure
10
- Python, so the async story stays idiomatic — no tokio ⇄ asyncio bridge.
10
+ Python, so the async story stays idiomatic: no tokio ⇄ asyncio bridge.
11
11
 
12
12
  > **Unofficial.** buzzkit is an independent project and is **not** affiliated
13
13
  > with, sponsored by, or endorsed by Block, Inc.
@@ -41,26 +41,37 @@ from buzzkit import BuzzClient
41
41
  async def main():
42
42
  bz = BuzzClient("wss://your-community.communities.buzz.xyz", "<nsec>")
43
43
 
44
- # HTTP bridge — one-shot, no connection needed:
44
+ # HTTP bridge: one-shot, no connection needed.
45
45
  await bz.send_message("<channel-uuid>", "posted over HTTP")
46
46
  await bz.set_profile("My Agent", about="an autonomous participant")
47
+ await bz.set_status("reviewing PRs", emoji="🤖")
47
48
 
48
- # WebSocket — real-time inbound:
49
+ # WebSocket: real-time inbound.
49
50
  async with bz: # connect() + NIP-42 auth
50
51
  async for event in bz.subscribe_channel("<channel-uuid>"):
51
- print(event["pubkey"], event["content"])
52
+ await bz.react(event["id"], "👍") # acknowledge receipt
53
+ await bz.send_message( # threaded reply
54
+ "<channel-uuid>", "on it!", reply_to=event["id"]
55
+ )
52
56
 
53
57
  asyncio.run(main())
54
58
  ```
55
59
 
60
+ Messages can also be revised after the fact: `edit_message` replaces one of
61
+ your own messages in place, and `delete_message` publishes a tombstone with an
62
+ optional room-facing reason (useful for moderator agents).
63
+
56
64
  ### Huddle audio (voice)
57
65
 
58
66
  Buzz huddles are ephemeral voice channels; audio is Opus (48 kHz mono, 20 ms
59
67
  frames) over a dedicated WebSocket. `HuddleClient` handles the handshake,
60
- Opus encode/decode (in Rust), and real-time outbound pacing — you deal in raw
61
- PCM (s16le mono 48 kHz):
68
+ Opus encode/decode (in Rust), and real-time outbound pacing, so you deal in
69
+ raw PCM (s16le mono 48 kHz):
62
70
 
63
71
  ```python
72
+ import json
73
+
74
+ import buzzkit
64
75
  from buzzkit import BuzzClient, HuddleAudio, HuddleClient
65
76
 
66
77
  # Huddles announce themselves as kind 48100 on their parent channel:
@@ -76,9 +87,25 @@ async with HuddleClient(relay_url, nsec, huddle_id, parent_channel_id=parent_id)
76
87
  print(ev.pubkey, len(ev.pcm))
77
88
  ```
78
89
 
79
- Being a member of the parent channel is enough — the relay auto-adds you to
90
+ Being a member of the parent channel is enough: the relay auto-adds you to
80
91
  the ephemeral huddle when `parent_channel_id` is given.
81
92
 
93
+ ## Agent identity and ownership (NIP-OA)
94
+
95
+ Buzz shows agents as "managed by \<owner\>". The attestation is an `auth` tag
96
+ signed by the owner key; buzzkit can both produce it and verify it:
97
+
98
+ ```python
99
+ tag = buzzkit.compute_auth_tag(owner_nsec, agent_pubkey_hex) # owner attests the agent
100
+ bz = BuzzClient(relay_url, agent_nsec, auth_tag=tag) # AUTH + profile carry it
101
+ await bz.set_profile("My Agent") # shows "managed by <owner>"
102
+
103
+ # "Which agent named Honey belongs to this owner?", cryptographically verified
104
+ # against the owner's managed-agent records (never by display name alone):
105
+ agents = await bz.resolve_agent("Honey", owner_pubkey_hex)
106
+ verified = [a for a in agents if a["verification"] == "verified"]
107
+ ```
108
+
82
109
  ## Joining a community (relay onboarding)
83
110
 
84
111
  Hosted Buzz communities are **closed relays**: an identity must be a relay member
@@ -102,14 +129,20 @@ claiming. After joining, `set_profile(...)` gives the agent a display name.
102
129
  |---|---|
103
130
  | `generate_keypair()` → `(nsec, npub, hex)` | new identity |
104
131
  | `pubkey_from_secret(secret)` | derive `(npub, hex)` |
105
- | `build_message_event` / `build_profile_event` / `build_auth_event` | build + sign events |
132
+ | `build_*_event` (message/reply, reaction, edit, delete, profile, user status, channel, presence…) | build + sign events |
133
+ | `compute_auth_tag` / `verify_auth_tag` / `verify_agent_profile` | NIP-OA owner attestation |
106
134
  | `sign_nip98(secret, method, url, body)` | HTTP bridge auth header |
107
135
  | `verify_event(json)` | check id + Schnorr signature |
108
- | `BuzzClient.send_message / set_profile / query / list_channels / claim_invite` | HTTP bridge |
109
- | `BuzzClient.connect / subscribe / subscribe_channel / publish / close` | WebSocket |
136
+ | `BuzzClient.send_message / react / remove_reaction / edit_message / set_profile / set_status / resolve_agent / query / list_channels / claim_invite` | HTTP bridge |
137
+ | `BuzzClient.connect / subscribe / subscribe_channel / publish / join_channel / leave_channel / set_topic / delete_message / start_huddle / publish_presence / close` | WebSocket |
110
138
  | `HuddleClient.connect / send_pcm / events / clear_queue / leave` | huddle voice (Opus) |
111
139
  | `HuddleEncoder` / `HuddleDecoder` | raw huddle wire frames ↔ PCM |
112
140
 
141
+ Threaded replies: `send_message(..., reply_to=<event-id>)` (add
142
+ `reply_root=` for nested replies). Reconnect note: the relay closes with
143
+ code **1012** on graceful restart, so check `BuzzClient.close_code` in your
144
+ reconnect loop and dedupe replayed events by id.
145
+
113
146
  ## Build from source
114
147
 
115
148
  Requires a Rust toolchain and [maturin](https://www.maturin.rs).
@@ -127,4 +160,4 @@ The Buzz crates are pinned via a Cargo `git` dependency in `Cargo.toml`; bump th
127
160
 
128
161
  MIT (see [LICENSE](LICENSE)). The distributed wheels statically link Apache-2.0
129
162
  components from Block's Buzz (`buzz-core` / `buzz-sdk`) and other permissive Rust
130
- crates — see [NOTICE](NOTICE) and [LICENSE-APACHE](LICENSE-APACHE).
163
+ crates; see [NOTICE](NOTICE) and [LICENSE-APACHE](LICENSE-APACHE).
@@ -0,0 +1,218 @@
1
+ """Analyze audio tap captures and point at the failing link.
2
+
3
+ Reads a capture directory produced by either (or both):
4
+ * roomkit's ``examples/buzz_voice_agent.py`` run with ``BUZZ_TAP_DIR=...``
5
+ (sender-side taps: provider_out_24k.raw, pacer_in_48k.raw,
6
+ wire_out_48k.raw, wire_send.csv, events.csv), or
7
+ * ``examples/huddle_wire_recorder.py`` (receiver-side: recv_frames.csv,
8
+ peer<N>_48k.raw).
9
+
10
+ and reports, per stage: send/arrival timing (stalls, bursts), silence frames
11
+ spliced into speech, wire sequence gaps, and audible holes inside the PCM.
12
+
13
+ python examples/analyze_audio_tap.py <capture_dir>
14
+
15
+ Reading the verdict:
16
+ * holes in wire_out_48k.raw but not in pacer_in_48k.raw
17
+ -> the pacer inserted silence / dropped audio (sender side).
18
+ * clean wire_out but recv_frames.csv shows seq gaps or heavy arrival jitter
19
+ -> frames lost or bunched between agent and relay fan-out.
20
+ * clean + smooth arrivals at the recorder, but the app still sounds choppy
21
+ -> receiver side (NetEq/playout in the desktop app).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import csv
27
+ import pathlib
28
+ import sys
29
+
30
+ FRAME_MS = 20.0
31
+ NS = 1_000_000 # ns per ms
32
+
33
+
34
+ def fmt_ts(ms: float) -> str:
35
+ return f"{int(ms // 60000):02d}:{ms % 60000 / 1000:06.3f}"
36
+
37
+
38
+ # ---------------------------------------------------------------- timing CSVs
39
+
40
+
41
+ def analyze_send_timing(rows: list[dict], t_key: str, label: str) -> None:
42
+ """Inter-send/arrival timing: stalls (>2x frame) and bursts (<2 ms)."""
43
+ times = [int(r[t_key]) for r in rows]
44
+ if len(times) < 2:
45
+ print(f" {label}: not enough rows")
46
+ return
47
+ deltas = [(b - a) / NS for a, b in zip(times, times[1:], strict=False)]
48
+ span_s = (times[-1] - times[0]) / NS / 1000
49
+ stalls = [(i, d) for i, d in enumerate(deltas) if d > 2 * FRAME_MS]
50
+ bursts = sum(1 for d in deltas if d < 2.0)
51
+ print(
52
+ f" {label}: {len(times)} frames over {span_s:.1f}s "
53
+ f"(mean {sum(deltas) / len(deltas):.1f} ms/frame, max gap {max(deltas):.0f} ms)"
54
+ )
55
+ print(f" gaps >{2 * FRAME_MS:.0f} ms: {len(stalls)} sends <2 ms apart (bursts): {bursts}")
56
+ t0 = times[0]
57
+ for i, d in stalls[:10]:
58
+ print(f" gap {d:6.0f} ms at t+{fmt_ts((times[i] - t0) / NS)}")
59
+ if len(stalls) > 10:
60
+ print(f" … and {len(stalls) - 10} more")
61
+
62
+
63
+ def analyze_wire_csv(path: pathlib.Path) -> None:
64
+ rows = list(csv.DictReader(path.open()))
65
+ if not rows:
66
+ print(" wire_send.csv: empty")
67
+ return
68
+ print("wire_send.csv — pacer output timing (what buzzkit is asked to send):")
69
+ analyze_send_timing(rows, "t_mono_ns", "pacer->send_pcm")
70
+
71
+ # Silence frames spliced into speech: an all-zero send whose neighbours
72
+ # within 300 ms on both sides contain non-zero audio.
73
+ times = [int(r["t_mono_ns"]) for r in rows]
74
+ zero = [r["all_zero"] == "1" for r in rows]
75
+ t0 = times[0]
76
+ nonzero_times = [t for t, z in zip(times, zero, strict=True) if not z]
77
+ spliced = []
78
+ for t, z in zip(times, zero, strict=True):
79
+ if not z or not nonzero_times:
80
+ continue
81
+ # nearest real-audio sends before/after this silence frame
82
+ before = any(0 < t - u <= 300 * NS for u in nonzero_times)
83
+ after = any(0 < u - t <= 300 * NS for u in nonzero_times)
84
+ if before and after:
85
+ spliced.append(t)
86
+ n_zero = sum(zero)
87
+ print(f" all-zero frames: {n_zero} total, {len(spliced)} spliced mid-speech")
88
+ for t in spliced[:10]:
89
+ print(f" silence splice at t+{fmt_ts((t - t0) / NS)}")
90
+ if len(spliced) > 10:
91
+ print(f" … and {len(spliced) - 10} more")
92
+
93
+
94
+ def analyze_recv_csv(path: pathlib.Path) -> None:
95
+ rows = list(csv.DictReader(path.open()))
96
+ if not rows:
97
+ print(" recv_frames.csv: empty")
98
+ return
99
+ print("recv_frames.csv — wire arrivals at the recorder (per peer):")
100
+ peers: dict[str, list[dict]] = {}
101
+ for r in rows:
102
+ peers.setdefault(r["peer_index"], []).append(r)
103
+ for peer, frames in sorted(peers.items()):
104
+ speech = [f for f in frames if f["is_dtx"] == "0"]
105
+ dtx = len(frames) - len(speech)
106
+ print(f" peer {peer}: {len(speech)} speech frames, {dtx} DTX")
107
+ if len(speech) < 2:
108
+ continue
109
+ analyze_send_timing(speech, "t_mono_ns", f"peer {peer} arrivals")
110
+ # Wire continuity over ALL frames (DTX included — every wire packet
111
+ # consumes one seq and 960 ts): dseq != 1 means frames were lost or
112
+ # reordered between the sender and us; dts != dseq*960 means the
113
+ # sender's own media timeline jumped (encoder restart / bug).
114
+ lost = jumps = 0
115
+ for a, b in zip(frames, frames[1:], strict=False):
116
+ dseq = (int(b["seq"]) - int(a["seq"])) % 65536
117
+ dts = (int(b["ts_48k"]) - int(a["ts_48k"])) % (1 << 32)
118
+ if dseq != 1:
119
+ lost += 1
120
+ if lost <= 10:
121
+ print(f" lost/reordered: seq {a['seq']}->{b['seq']} ({dseq - 1} missing)")
122
+ elif dts != 960:
123
+ jumps += 1
124
+ if jumps <= 10:
125
+ print(f" sender ts jump at seq {b['seq']}: +{dts} (expected +960)")
126
+ print(f" lost/reordered frames: {lost} sender ts jumps: {jumps}")
127
+
128
+
129
+ # ------------------------------------------------------------------ PCM scans
130
+
131
+
132
+ def analyze_raw(path: pathlib.Path, rate: int) -> None:
133
+ """Find near-silent runs >=15 ms that sit inside speech (audible holes)."""
134
+ data = path.read_bytes()
135
+ samples = memoryview(data).cast("h")
136
+ n = len(samples)
137
+ if n == 0:
138
+ print(f" {path.name}: empty")
139
+ return
140
+ ms = 1000.0 / rate
141
+ win = rate // 100 # 10 ms windows
142
+ # Classify 10 ms windows as silent/speech, then find silent runs
143
+ # bordered by speech within 200 ms on each side.
144
+ n_win = n // win
145
+ loud = []
146
+ for w in range(n_win):
147
+ seg = samples[w * win : (w + 1) * win]
148
+ peak = max(abs(min(seg)), abs(max(seg)))
149
+ loud.append(peak > 400)
150
+ holes: list[tuple[int, int]] = []
151
+ w = 0
152
+ while w < n_win:
153
+ if loud[w]:
154
+ w += 1
155
+ continue
156
+ start = w
157
+ while w < n_win and not loud[w]:
158
+ w += 1
159
+ run_ms = (w - start) * 10
160
+ ctx = 20 # 200 ms of context windows
161
+ speech_before = any(loud[max(0, start - ctx) : start])
162
+ speech_after = any(loud[w : w + ctx])
163
+ if run_ms >= 15 and run_ms <= 2000 and speech_before and speech_after:
164
+ holes.append((start, run_ms))
165
+ dur_s = n * ms / 1000
166
+ print(f" {path.name}: {dur_s:.1f}s of audio, {len(holes)} hole(s) inside speech")
167
+ for start, run_ms in holes[:15]:
168
+ print(f" {run_ms:4d} ms hole at {fmt_ts(start * 10.0)}")
169
+ if len(holes) > 15:
170
+ print(f" … and {len(holes) - 15} more")
171
+
172
+
173
+ RAW_RATES = {"24k": 24_000, "48k": 48_000, "16k": 16_000}
174
+
175
+
176
+ def main() -> None:
177
+ if len(sys.argv) != 2:
178
+ raise SystemExit("usage: analyze_audio_tap.py <capture_dir>")
179
+ cap = pathlib.Path(sys.argv[1])
180
+ if not cap.is_dir():
181
+ raise SystemExit(f"not a directory: {cap}")
182
+
183
+ found = False
184
+ wire_csv = cap / "wire_send.csv"
185
+ if wire_csv.exists():
186
+ found = True
187
+ analyze_wire_csv(wire_csv)
188
+ print()
189
+ recv_csv = cap / "recv_frames.csv"
190
+ if recv_csv.exists():
191
+ found = True
192
+ analyze_recv_csv(recv_csv)
193
+ print()
194
+ events_csv = cap / "events.csv"
195
+ if events_csv.exists():
196
+ rows = list(csv.DictReader(events_csv.open()))
197
+ interesting = [r for r in rows if r.get("event") not in (None, "")]
198
+ if interesting:
199
+ print(f"events.csv: {len(interesting)} event(s)")
200
+ for r in interesting[:20]:
201
+ print(f" {r}")
202
+ print()
203
+ raws = sorted(cap.glob("*.raw"))
204
+ if raws:
205
+ found = True
206
+ print("PCM hole scan (near-silence >=15 ms surrounded by speech):")
207
+ for raw in raws:
208
+ rate = next(
209
+ (hz for tag, hz in RAW_RATES.items() if tag in raw.name),
210
+ 48_000,
211
+ )
212
+ analyze_raw(raw, rate)
213
+ if not found:
214
+ raise SystemExit(f"no tap files found in {cap}")
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()
@@ -0,0 +1,122 @@
1
+ """Wire-side recorder for Buzz huddles — capture exactly what receivers get.
2
+
3
+ Joins a huddle as a silent peer (sends nothing) and records every inbound
4
+ audio frame with its arrival time and wire header. This is the ground truth
5
+ for "what does the desktop app's jitter buffer actually see": if the audio
6
+ is already choppy here, the sender (e.g. the roomkit agent) is at fault; if
7
+ it is clean here but choppy in the app, the receiver side is at fault.
8
+
9
+ Watch mode (recommended): give it only the parent channel — the one in your
10
+ BUZZ_CHANNEL_ID — and it records every huddle announced there (kind 48100),
11
+ one output directory per huddle:
12
+
13
+ BUZZ_RELAY_URL=wss://... python examples/huddle_wire_recorder.py \
14
+ <parent_channel_id>
15
+
16
+ Direct mode, when you already know the ephemeral huddle id (the agent logs
17
+ it as "Joined huddle <uuid>"):
18
+
19
+ python examples/huddle_wire_recorder.py <parent_channel_id> \
20
+ <huddle_channel_id> [out_dir]
21
+
22
+ Output (out_dir, default ./wire-tap-<huddle>):
23
+ recv_frames.csv one row per wire frame:
24
+ t_mono_ns,peer_index,seq,ts_48k,level_dbov,is_dtx,pcm_bytes
25
+ events.csv roster events: t_mono_ns,event,pubkey
26
+ peer<N>_48k.raw decoded s16le mono 48 kHz PCM per peer (non-DTX frames,
27
+ concatenated in arrival order — listen with:
28
+ ffplay -f s16le -ar 48000 -ch_layout mono peer<N>_48k.raw)
29
+
30
+ Analyze the capture with examples/analyze_audio_tap.py.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import asyncio
36
+ import contextlib
37
+ import json
38
+ import pathlib
39
+ import sys
40
+ import time
41
+
42
+ from _shared import agent_secret, relay_url
43
+ from buzzkit import KIND_HUDDLE_STARTED, BuzzClient, HuddleAudio, HuddleClient
44
+
45
+
46
+ async def record(
47
+ relay: str, secret: str, huddle_id: str, parent_id: str, out: pathlib.Path
48
+ ) -> None:
49
+ out.mkdir(parents=True, exist_ok=True)
50
+ frames_csv = (out / "recv_frames.csv").open("w")
51
+ frames_csv.write("t_mono_ns,peer_index,seq,ts_48k,level_dbov,is_dtx,pcm_bytes\n")
52
+ events_csv = (out / "events.csv").open("w")
53
+ events_csv.write("t_mono_ns,event,pubkey\n")
54
+ pcm_files: dict[int, object] = {}
55
+ n_frames = 0
56
+
57
+ # paced=False: the client never sends anything on its own (no silence
58
+ # stream), so this peer is acoustically invisible in the huddle.
59
+ client = HuddleClient(relay, secret, huddle_id, parent_channel_id=parent_id, paced=False)
60
+ async with client:
61
+ print(f"recording huddle {huddle_id} -> {out} (Ctrl+C to stop)")
62
+ try:
63
+ async for ev in client.events():
64
+ now = time.monotonic_ns()
65
+ if isinstance(ev, HuddleAudio):
66
+ frames_csv.write(
67
+ f"{now},{ev.peer_index},{ev.seq},{ev.ts_48k},"
68
+ f"{ev.level_dbov},{int(ev.is_dtx)},{len(ev.pcm)}\n"
69
+ )
70
+ if not ev.is_dtx:
71
+ f = pcm_files.get(ev.peer_index)
72
+ if f is None:
73
+ f = (out / f"peer{ev.peer_index}_48k.raw").open("wb")
74
+ pcm_files[ev.peer_index] = f
75
+ f.write(ev.pcm)
76
+ n_frames += 1
77
+ if n_frames % 500 == 0:
78
+ frames_csv.flush()
79
+ print(f" {n_frames} frames…")
80
+ else:
81
+ events_csv.write(f"{now},{type(ev).__name__},{ev.pubkey}\n")
82
+ events_csv.flush()
83
+ finally:
84
+ frames_csv.close()
85
+ events_csv.close()
86
+ for f in pcm_files.values():
87
+ f.close()
88
+ print(f"done: {n_frames} frames from {len(pcm_files)} speaking peer(s)")
89
+ print(f"analyze with: python examples/analyze_audio_tap.py {out}")
90
+
91
+
92
+ async def watch_and_record(relay: str, secret: str, parent_id: str) -> None:
93
+ """Record every huddle announced on the parent channel from now on."""
94
+ print(f"watching {parent_id} for huddles (kind {KIND_HUDDLE_STARTED})…")
95
+ async with BuzzClient(relay, secret) as bz:
96
+ live = {"kinds": [KIND_HUDDLE_STARTED], "#h": [parent_id], "since": int(time.time())}
97
+ async for event in bz.subscribe([live]):
98
+ huddle_id = json.loads(event["content"]).get("ephemeral_channel_id")
99
+ if not huddle_id:
100
+ continue
101
+ out = pathlib.Path(f"wire-tap-{huddle_id[:8]}")
102
+ await record(relay, secret, huddle_id, parent_id, out)
103
+ print(f"watching {parent_id} for the next huddle…")
104
+
105
+
106
+ async def main() -> None:
107
+ if len(sys.argv) < 2:
108
+ raise SystemExit(
109
+ "usage: huddle_wire_recorder.py <parent_channel_id> [huddle_channel_id] [out_dir]"
110
+ )
111
+ parent_id = sys.argv[1]
112
+ if len(sys.argv) < 3:
113
+ await watch_and_record(relay_url(), agent_secret(), parent_id)
114
+ return
115
+ huddle_id = sys.argv[2]
116
+ out = pathlib.Path(sys.argv[3] if len(sys.argv) > 3 else f"wire-tap-{huddle_id[:8]}")
117
+ await record(relay_url(), agent_secret(), huddle_id, parent_id, out)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ with contextlib.suppress(KeyboardInterrupt):
122
+ asyncio.run(main())