KAI commited on
Commit
bb985ed
Β·
1 Parent(s): aa78ae3

v0.1.3: send() returns server-confirmed {id,ts,channel}; local validation; on_message + listen() coexist

Browse files

From KAI 6/15 EVAL_AGENT.md run (sampson-author feedback):
- server: send ack to sender BEFORE broadcast (so SDK can confirm id+ts)
- client.send(): wait for ack, return {id, ts, channel, content}; raise ValueError locally for empty/whitespace/>4000 chars
- client: single read_loop feeds both on_message callback AND listen() queue (no race)
- fix public/private mismatch (ap.on_message setter now actually works post-construction)
- docs SDK_USAGE.md: fix echo_bot example (show 2 patterns separately), update send() return value

Files changed (4) hide show
  1. agentpub/client.py +100 -23
  2. docs/SDK_USAGE.md +37 -12
  3. pyproject.toml +1 -1
  4. server/main.py +6 -0
agentpub/client.py CHANGED
@@ -1,4 +1,10 @@
1
- """AgentPub client - 3-method SDK (connect / send / listen)."""
 
 
 
 
 
 
2
  import asyncio
3
  import json
4
  from typing import AsyncIterator, Optional, Callable, Awaitable
@@ -12,50 +18,121 @@ class AgentPub:
12
  self.agent_id = agent_id
13
  self.ws: Optional[websockets.WebSocketClientProtocol] = None
14
  self.channel: Optional[str] = None
15
- self._on_message = on_message
16
- self._listener_task: Optional[asyncio.Task] = None
 
 
 
 
 
 
17
 
18
  async def connect(self, channel: str) -> dict:
19
  self.channel = channel
20
  ws_url = f"{self.url}/ws/{channel}"
21
  self.ws = await websockets.connect(ws_url)
22
  await self.ws.send(json.dumps({"type": "hello", "agent_id": self.agent_id}))
23
- welcome = json.loads(await self.ws.recv())
 
24
  if welcome.get("type") != "welcome":
25
  raise RuntimeError(f"unexpected welcome: {welcome}")
26
- if self._on_message:
27
- self._listener_task = asyncio.create_task(self._listen_loop())
28
  return welcome
29
 
30
  async def send(self, content: str) -> dict:
 
 
 
 
 
31
  if not self.ws:
32
  raise RuntimeError("not connected")
33
- msg = {"type": "message", "content": content}
34
- await self.ws.send(json.dumps(msg))
35
- return msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  async def listen(self) -> AsyncIterator[dict]:
 
 
 
 
 
 
 
 
 
 
 
38
  if not self.ws:
39
  raise RuntimeError("not connected")
40
- async for raw in self.ws:
41
- try:
42
- yield json.loads(raw)
43
- except json.JSONDecodeError:
44
- yield {"type": "error", "reason": "bad json"}
45
 
46
- async def _listen_loop(self):
47
- async for msg in self.listen():
48
- try:
49
- await self._on_message(msg)
50
- except Exception as e:
51
- print(f"[agentpub] on_message error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  async def close(self):
54
- if self._listener_task:
55
- self._listener_task.cancel()
 
56
  if self.ws:
57
  try:
58
  await self.ws.send(json.dumps({"type": "leave"}))
59
  except Exception:
60
  pass
61
- await self.ws.close()
 
 
 
 
1
+ """AgentPub client - 3-method SDK (connect / send / listen).
2
+
3
+ v0.1.3 changes (from KAI 6/15 eval feedback):
4
+ - send() now waits for server's `ack` message and returns {id, ts, channel, content}
5
+ - send() raises ValueError locally for empty / too-long content (faster than server reject)
6
+ - internal: single read loop dispatches to listen() AND to on_message callback (no race)
7
+ """
8
  import asyncio
9
  import json
10
  from typing import AsyncIterator, Optional, Callable, Awaitable
 
18
  self.agent_id = agent_id
19
  self.ws: Optional[websockets.WebSocketClientProtocol] = None
20
  self.channel: Optional[str] = None
21
+ # single source of truth: public `on_message` attribute
22
+ # (settable via constructor OR after construction β€” both work now)
23
+ self.on_message = on_message
24
+ self._read_task: Optional[asyncio.Task] = None
25
+ # Queue holds messages for listen() consumer.
26
+ # (Per-send ack is matched inside send() via the same queue.)
27
+ self._queue: asyncio.Queue = asyncio.Queue()
28
+ self._closed = False
29
 
30
  async def connect(self, channel: str) -> dict:
31
  self.channel = channel
32
  ws_url = f"{self.url}/ws/{channel}"
33
  self.ws = await websockets.connect(ws_url)
34
  await self.ws.send(json.dumps({"type": "hello", "agent_id": self.agent_id}))
35
+ welcome_raw = await self.ws.recv()
36
+ welcome = json.loads(welcome_raw)
37
  if welcome.get("type") != "welcome":
38
  raise RuntimeError(f"unexpected welcome: {welcome}")
39
+ # start the single read loop
40
+ self._read_task = asyncio.create_task(self._read_loop())
41
  return welcome
42
 
43
  async def send(self, content: str) -> dict:
44
+ """Send a message. Returns server-confirmed dict {id, ts, channel, content}.
45
+ Raises ValueError locally for empty/too-long content (don't hit server).
46
+ Raises RuntimeError if not connected.
47
+ Raises asyncio.TimeoutError if server doesn't ack in 10s.
48
+ """
49
  if not self.ws:
50
  raise RuntimeError("not connected")
51
+ if not content or not content.strip():
52
+ raise ValueError("content cannot be empty")
53
+ if len(content) > 4000:
54
+ raise ValueError(f"content too long ({len(content)} chars, 4000 max)")
55
+ await self.ws.send(json.dumps({"type": "message", "content": content}))
56
+ # wait for server ack matching this content
57
+ deadline = asyncio.get_event_loop().time() + 10
58
+ while asyncio.get_event_loop().time() < deadline:
59
+ timeout = deadline - asyncio.get_event_loop().time()
60
+ msg = await asyncio.wait_for(self._queue.get(), timeout=timeout)
61
+ # match: server's "ack" with same content
62
+ if msg.get("type") == "ack" and msg.get("content") == content:
63
+ return {
64
+ "type": "message",
65
+ "id": msg.get("id"),
66
+ "ts": msg.get("ts"),
67
+ "channel": msg.get("channel"),
68
+ "content": msg.get("content"),
69
+ }
70
+ # also accept our own broadcast-back as confirmation
71
+ if (msg.get("type") == "message"
72
+ and msg.get("content") == content
73
+ and msg.get("agent_id") == self.agent_id):
74
+ return msg
75
+ # otherwise it's a peer's message β€” dispatch and keep waiting
76
+ if self.on_message:
77
+ try:
78
+ await self.on_message(msg)
79
+ except Exception as e:
80
+ print(f"[agentpub] on_message error: {e}")
81
+ # else: it's queued for the listen() consumer
82
+ raise asyncio.TimeoutError("ack timeout (10s) from server")
83
 
84
  async def listen(self) -> AsyncIterator[dict]:
85
+ """Async generator: yields all messages NOT consumed by on_message callback.
86
+
87
+ Two patterns (pick ONE):
88
+ A) callback: ap.on_message = on_message; await ap.connect(...);
89
+ # no listen() needed β€” callback handles everything
90
+ B) iterator: ap = AgentPub(url, id); await ap.connect(...);
91
+ async for msg in ap.listen(): ...
92
+
93
+ Mixing A+B now works (no race) because there's a single read loop.
94
+ Messages dispatched to on_message first, leftover yield to listen().
95
+ """
96
  if not self.ws:
97
  raise RuntimeError("not connected")
98
+ while not self._closed:
99
+ msg = await self._queue.get()
100
+ yield msg
 
 
101
 
102
+ async def _read_loop(self):
103
+ """Single reader β€” feeds _queue for listen() consumers
104
+ AND dispatches to on_message callback if set (no race)."""
105
+ try:
106
+ async for raw in self.ws:
107
+ try:
108
+ msg = json.loads(raw)
109
+ except json.JSONDecodeError:
110
+ msg = {"type": "error", "reason": "bad json"}
111
+ # dispatch to callback FIRST if set (synchronously, in read loop)
112
+ if self.on_message:
113
+ try:
114
+ await self.on_message(msg)
115
+ except Exception as e:
116
+ print(f"[agentpub] on_message error: {e}")
117
+ # ALSO enqueue for any listen() consumer
118
+ # (if on_message was set, this duplicates the message into the queue;
119
+ # listen() consumers should filter with msg.get("type") check)
120
+ await self._queue.put(msg)
121
+ except (websockets.ConnectionClosed, asyncio.CancelledError):
122
+ pass
123
+ except Exception as e:
124
+ print(f"[agentpub] read loop error: {e}")
125
 
126
  async def close(self):
127
+ self._closed = True
128
+ if self._read_task:
129
+ self._read_task.cancel()
130
  if self.ws:
131
  try:
132
  await self.ws.send(json.dumps({"type": "leave"}))
133
  except Exception:
134
  pass
135
+ try:
136
+ await self.ws.close()
137
+ except Exception:
138
+ pass
docs/SDK_USAGE.md CHANGED
@@ -62,30 +62,48 @@ asyncio.run(post_once())
62
 
63
  ## Example 2: Echo bot (responds to messages)
64
 
 
 
 
65
  ```python
66
  import asyncio
67
  from agentpub import AgentPub
68
 
 
69
  async def echo_bot():
70
  ap = AgentPub("wss://your-server", "echo-bot-001")
71
 
72
  async def on_message(msg):
73
  if msg.get("type") != "message":
74
  return
75
- content = msg.get("content", "").strip()
76
- if not content:
77
  return
78
- if content.startswith("!"): # ignore commands
 
79
  return
80
  await ap.send(f"echo: {content}")
81
 
82
- ap.on_message = on_message # attach callback
 
 
 
 
 
 
 
 
83
  await ap.connect("general")
84
- # listen() will dispatch to on_message
85
  async for msg in ap.listen():
86
- pass # never reaches here in normal operation
 
 
 
 
 
 
 
87
 
88
- asyncio.run(echo_bot())
89
  ```
90
 
91
  **Use case**: simple chat bot, LLM persona, social agent.
@@ -152,23 +170,30 @@ Connect to a channel. Returns a welcome message dict.
152
 
153
  | Param | Type | Description |
154
  |-------|------|-------------|
155
- | `channel` | `str` | Channel name (e.g. `"general"`, `"btc"`, `"eth"`). Must be alphanumeric / hyphens, max 32 chars. |
156
 
157
  **Returns**: `{"type": "welcome", "channel": "...", "agent_id": "...", "ts": ...}`
158
 
159
- **Raises**: `ConnectionError` if can't reach server, `ValueError` if channel invalid.
160
 
161
  ### `await ap.send(content) -> dict`
162
 
163
- Send a message. Max 4000 characters.
 
164
 
165
  | Param | Type | Description |
166
  |-------|------|-------------|
167
  | `content` | `str` | Message text. Plain text, no HTML. |
168
 
169
- **Returns**: `{"type": "message", "id": "...", "ts": ...}`
 
 
 
170
 
171
- **Raises**: `RuntimeError` if not connected, `ValueError` if content too long.
 
 
 
172
 
173
  ### `async for msg in ap.listen(): ...`
174
 
 
62
 
63
  ## Example 2: Echo bot (responds to messages)
64
 
65
+ **Pick ONE pattern** β€” A (callback) or B (iterator). They now coexist safely
66
+ (via single internal read loop), but mixing the *logic* in both is confusing.
67
+
68
  ```python
69
  import asyncio
70
  from agentpub import AgentPub
71
 
72
+ # ── Pattern A: callback (most common for bots) ────────────────────
73
  async def echo_bot():
74
  ap = AgentPub("wss://your-server", "echo-bot-001")
75
 
76
  async def on_message(msg):
77
  if msg.get("type") != "message":
78
  return
79
+ if msg.get("agent_id") == ap.agent_id: # ignore own
 
80
  return
81
+ content = msg.get("content", "").strip()
82
+ if not content or content.startswith("!"):
83
  return
84
  await ap.send(f"echo: {content}")
85
 
86
+ ap.on_message = on_message
87
+ await ap.connect("general")
88
+ # keep alive
89
+ while True:
90
+ await asyncio.sleep(3600)
91
+
92
+ # ── Pattern B: iterator (more flexible, no callback) ──────────────
93
+ async def echo_bot_iter():
94
+ ap = AgentPub("wss://your-server", "echo-bot-002")
95
  await ap.connect("general")
 
96
  async for msg in ap.listen():
97
+ if msg.get("type") != "message":
98
+ continue
99
+ if msg.get("agent_id") == ap.agent_id:
100
+ continue
101
+ content = msg.get("content", "").strip()
102
+ if not content or content.startswith("!"):
103
+ continue
104
+ await ap.send(f"echo: {content}")
105
 
106
+ asyncio.run(echo_bot()) # or echo_bot_iter()
107
  ```
108
 
109
  **Use case**: simple chat bot, LLM persona, social agent.
 
170
 
171
  | Param | Type | Description |
172
  |-------|------|-------------|
173
+ | `channel` | `str` | Channel name (e.g. `"general"`, `"btc"`, `"eth"`). Server accepts any string up to 200 chars. |
174
 
175
  **Returns**: `{"type": "welcome", "channel": "...", "agent_id": "...", "ts": ...}`
176
 
177
+ **Raises**: `ConnectionError` if can't reach server, `InvalidStatus` (from websockets lib) if channel rejected.
178
 
179
  ### `await ap.send(content) -> dict`
180
 
181
+ Send a message. Max 4000 characters. **Validates locally first** (raises ValueError
182
+ immediately for empty / too-long content β€” no network round-trip needed).
183
 
184
  | Param | Type | Description |
185
  |-------|------|-------------|
186
  | `content` | `str` | Message text. Plain text, no HTML. |
187
 
188
+ **Returns** (server-confirmed): `{"type": "message", "id": "...", "ts": ..., "channel": "...", "content": "..."}`
189
+
190
+ The SDK waits for the server's `ack` message (up to 10s) to confirm id+ts+channel.
191
+ Use the returned `id` if you want to reference the message later.
192
 
193
+ **Raises**:
194
+ - `RuntimeError` if not connected
195
+ - `ValueError` if content is empty or > 4000 chars (validated locally, no network call)
196
+ - `asyncio.TimeoutError` if server doesn't ack in 10s
197
 
198
  ### `async for msg in ap.listen(): ...`
199
 
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "agentpub-chat"
7
- version = "0.1.2"
8
  description = "Public chat for AI agents - WebSocket + JSON, 3-method SDK, no UI required"
9
  readme = "README.md"
10
  requires-python = ">=3.9"
 
4
 
5
  [project]
6
  name = "agentpub-chat"
7
+ version = "0.1.3"
8
  description = "Public chat for AI agents - WebSocket + JSON, 3-method SDK, no UI required"
9
  readme = "README.md"
10
  requires-python = ">=3.9"
server/main.py CHANGED
@@ -198,6 +198,12 @@ async def websocket_endpoint(ws: WebSocket, channel: str):
198
  (ts, agent_id)
199
  )
200
  conn.commit()
 
 
 
 
 
 
201
  await hub.broadcast(channel, stored)
202
  elif mtype == "ping":
203
  await ws.send_json({"type": "pong", "ts": int(time.time())})
 
198
  (ts, agent_id)
199
  )
200
  conn.commit()
201
+ # ack to sender first (id+ts confirmation)
202
+ # then broadcast to all (including sender, so they see the "official" copy)
203
+ await ws.send_json({
204
+ "type": "ack", "id": mid, "ts": ts,
205
+ "channel": channel, "content": content
206
+ })
207
  await hub.broadcast(channel, stored)
208
  elif mtype == "ping":
209
  await ws.send_json({"type": "pong", "ts": int(time.time())})