optio-chat 0.1.0__py3-none-any.whl

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.
optio_chat/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """optio-chat: agent chat for optio (hub, client library, CLI, Claude Code plugin)."""
2
+
3
+ from optio_chat.api import ChatConnectionAPI, Connector
4
+ from optio_chat.client import mqtt_connector
5
+ from optio_chat.models import (
6
+ ERR_AVATAR_INVALID,
7
+ ERR_CHANNEL_INVALID,
8
+ ERR_FILE_NOT_FOUND,
9
+ ERR_HUB_UNREACHABLE,
10
+ ERR_NAME_INVALID,
11
+ ERR_NAME_LOST,
12
+ ERR_NAME_TAKEN,
13
+ ERR_NO_NAME,
14
+ ERR_NOT_MEMBER,
15
+ ERR_NOT_SOLE_MEMBER,
16
+ ERR_OTHER_NAME,
17
+ ERR_REFUSED,
18
+ ERR_TOO_LARGE,
19
+ ERR_WRONG_KEY,
20
+ ERR_WRONG_PASSWORD,
21
+ ChatError,
22
+ ChatMessage,
23
+ ChatState,
24
+ HubAddress,
25
+ JoinResult,
26
+ SendResult,
27
+ )
28
+
29
+ __all__ = [
30
+ "ChatConnectionAPI", "Connector", "mqtt_connector",
31
+ "ChatError", "ChatMessage", "ChatState", "HubAddress", "JoinResult", "SendResult",
32
+ "ERR_AVATAR_INVALID", "ERR_CHANNEL_INVALID", "ERR_FILE_NOT_FOUND", "ERR_HUB_UNREACHABLE",
33
+ "ERR_NAME_INVALID", "ERR_NAME_LOST", "ERR_NAME_TAKEN", "ERR_NO_NAME", "ERR_NOT_MEMBER",
34
+ "ERR_NOT_SOLE_MEMBER", "ERR_OTHER_NAME", "ERR_REFUSED", "ERR_TOO_LARGE", "ERR_WRONG_KEY",
35
+ "ERR_WRONG_PASSWORD",
36
+ ]
optio_chat/api.py ADDED
@@ -0,0 +1,95 @@
1
+ """The client-side interface: what a connection to the hub can do, and how one is made.
2
+
3
+ Contract module (Phase 0 of the agent chat plan). Implemented by ``optio_chat.client`` (paho-mqtt,
4
+ the real thing) and ``optio_chat.testing.FakeHub`` (in memory, for tests). Used by the engine chat
5
+ service (optio-core), the CLI and the Claude Code plugin.
6
+
7
+ One connection = one MQTT session = one name. All methods raise ``ChatError``:
8
+ ERR_HUB_UNREACHABLE while disconnected or when a request gets no answer within
9
+ ``wire.REQUEST_TIMEOUT_S``; the hub's refusals map through ``wire.error_for``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import AsyncIterator, Awaitable, Callable, Protocol, runtime_checkable
15
+
16
+ from optio_chat.models import ChatMessage, JoinResult, SendResult
17
+
18
+
19
+ @runtime_checkable
20
+ class ChatConnectionAPI(Protocol):
21
+ name: str
22
+ # Called once when a reconnect is refused because the hub no longer accepts this name's key
23
+ # (the name expired, or the hub's database was reset, or someone else holds it now). After
24
+ # that the connection stays down; every call raises ERR_NAME_LOST.
25
+ on_name_lost: Callable[[], Awaitable[None]] | None
26
+
27
+ @property
28
+ def connected(self) -> bool: ...
29
+
30
+ async def join(self, channel: str) -> JoinResult:
31
+ """Subscribe to the channel (no-local). Joining a channel already joined is a success."""
32
+
33
+ async def send(self, channel: str, text: str) -> SendResult:
34
+ """Publish to the channel under this name. Not being a member is allowed."""
35
+
36
+ async def describe(self, channel: str, description: str) -> None:
37
+ """Set (or, with "", clear) the channel's description. Only a sole member may."""
38
+
39
+ async def set_avatar(self, image: bytes) -> str:
40
+ """Upload an avatar; it becomes this name's current avatar. Returns its id (the
41
+ uploaded image's, ``wire.avatar_id_of``)."""
42
+
43
+ async def fetch_avatar(self, avatar_id: str, *, full: bool = False) -> bytes:
44
+ """Any avatar the hub stores: its small version (``wire.AVATAR_SMALL_SIDE`` px on its
45
+ longer side, what normal display uses), or with ``full`` the original as uploaded. An
46
+ avatar that is its own small version (or was stored before the hub kept originals)
47
+ gives the same image for both."""
48
+
49
+ def incoming(self) -> AsyncIterator[ChatMessage]:
50
+ """Messages for this name, in hub order, starting with the ones waiting at the hub.
51
+
52
+ A message stays unacknowledged until ``ack``; after a reconnect the hub delivers it again,
53
+ but this iterator never yields the same id twice while it is unacknowledged on this
54
+ connection. One iterator per connection.
55
+ """
56
+
57
+ async def ack(self, message: ChatMessage) -> None:
58
+ """Acknowledge a delivered message: the hub drops it from this name's queue."""
59
+
60
+ async def release(self) -> None:
61
+ """End the name now (MQTT disconnect with session expiry 0): its memberships and waiting
62
+ messages go with it. The connection is closed afterwards."""
63
+
64
+ async def close(self) -> None:
65
+ """Disconnect but keep the name, its memberships and its waiting messages at the hub."""
66
+
67
+
68
+ class Connector(Protocol):
69
+ """Makes connections. ``expiry`` is the name's session expiry in seconds (how long the hub
70
+ keeps it after the last disconnect). ``receive_maximum`` is MQTT 5's Receive Maximum: the hub
71
+ sends the connection at most that many unacknowledged messages, the rest wait at the hub and
72
+ come as earlier ones are acknowledged. None (the default): the CONNECT carries none, and the
73
+ hub allows MQTT's 65535; else an int in 1-65535 (``wire.check_receive_maximum``; ValueError
74
+ otherwise, before anything is sent). It holds for every reconnect of the connection. Engines
75
+ pass ``wire.ENGINE_RECEIVE_MAXIMUM`` for their names.
76
+
77
+ ``server`` is the optio server the connection comes from (``wire.server_id``:
78
+ ``<database>/<prefix>``), sent in every CONNECT of the connection, reconnects included, as
79
+ the user property ``wire.PROP_SERVER``; the hub logs once that the server connected (see the
80
+ hub's ``on_server_connected``) and nothing else changes. None (the default): none is sent.
81
+ A value ``wire.server_id_ok`` refuses raises ValueError before anything is sent
82
+ (``wire.check_server``). Engines pass theirs on every connection; the CLI and the plugin
83
+ pass none."""
84
+
85
+ async def claim(self, name: str, *, expiry: int, receive_maximum: int | None = None,
86
+ server: str | None = None) -> tuple[ChatConnectionAPI, str]:
87
+ """Claim a free name. Returns the connection and the name's key (keep it to resume).
88
+ Raises ERR_NAME_TAKEN, ERR_NAME_INVALID, ERR_WRONG_PASSWORD, ERR_HUB_UNREACHABLE."""
89
+
90
+ async def resume(self, name: str, key: str, *, expiry: int, clean: bool = False,
91
+ receive_maximum: int | None = None,
92
+ server: str | None = None) -> ChatConnectionAPI:
93
+ """Reconnect to a name this caller holds. ``clean=True`` keeps the name but drops its
94
+ memberships and waiting messages. Raises ERR_WRONG_KEY, ERR_WRONG_PASSWORD,
95
+ ERR_HUB_UNREACHABLE."""
optio_chat/cli.py ADDED
@@ -0,0 +1,140 @@
1
+ """The ``optio-chat`` command line: argument parsing and dispatch only.
2
+
3
+ Phase 0 (complete). The commands live in ``optio_chat.cli_commands`` (Part 4: name, join, send,
4
+ describe, avatar, read, listen) and ``optio_chat.plugin.commands`` (Part 6: mcp, monitor,
5
+ plugin-dir). Every command function is ``async def cmd_<name>(args: argparse.Namespace) -> int``
6
+ and returns the exit code: 0 success, 2 a chat error (its ``texts.error_text`` printed to stderr),
7
+ 1 anything else. The commands that claim or resume a name (and ``mcp``) take
8
+ ``--expiry-hours``; ``session_expiry(args)`` is the expiry they use (the option, else
9
+ ``OPTIO_CHAT_EXPIRY_HOURS``, else 24 hours).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import asyncio
16
+ import math
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import Mapping
21
+
22
+ from optio_chat import wire
23
+
24
+ DEFAULT_KEYS_DIR = Path.home() / ".config" / "optio-chat" / "keys"
25
+
26
+ # How long the hub keeps a name after its last disconnect: `--expiry-hours` on the commands that
27
+ # claim or resume (and `mcp`), else this variable (the plugin's MCP server has no command line the
28
+ # user edits), else wire.OUTSIDE_SESSION_EXPIRY (24 h).
29
+ EXPIRY_ENV = "OPTIO_CHAT_EXPIRY_HOURS"
30
+ # MQTT's Session Expiry Interval is a 32-bit count of seconds whose largest value means "never".
31
+ MAX_EXPIRY_HOURS = (wire.SESSION_EXPIRY_NEVER - 1) // 3600
32
+
33
+
34
+ def expiry_seconds(hours: str) -> int:
35
+ """``hours`` (a positive number, e.g. ``24`` or ``0.5``) as a session expiry in seconds,
36
+ rounded up. ValueError saying what is wrong otherwise (0 is refused: the hub would end the
37
+ name at every disconnect)."""
38
+ try:
39
+ value = float(hours)
40
+ except ValueError:
41
+ value = math.nan
42
+ if not 0 < value <= MAX_EXPIRY_HOURS: # NaN fails it too
43
+ raise ValueError(f"must be a positive number of hours (at most {MAX_EXPIRY_HOURS}), "
44
+ f"e.g. 24 or 0.5; got {hours!r}")
45
+ return math.ceil(value * 3600)
46
+
47
+
48
+ def session_expiry(args: argparse.Namespace, environ: Mapping[str, str] | None = None) -> int:
49
+ """The session expiry, in seconds, a command claims or resumes its name with:
50
+ ``--expiry-hours``, else ``OPTIO_CHAT_EXPIRY_HOURS`` (empty counts as unset), else 24 hours.
51
+ ValueError naming the variable for an unusable value of it."""
52
+ given = getattr(args, "expiry", None)
53
+ if given is not None:
54
+ return given
55
+ text = (os.environ if environ is None else environ).get(EXPIRY_ENV, "").strip()
56
+ if not text:
57
+ return wire.OUTSIDE_SESSION_EXPIRY
58
+ try:
59
+ return expiry_seconds(text)
60
+ except ValueError as exc:
61
+ raise ValueError(f"{EXPIRY_ENV} {exc}") from None
62
+
63
+
64
+ def _expiry_argument(text: str) -> int:
65
+ try:
66
+ return expiry_seconds(text)
67
+ except ValueError as exc:
68
+ raise argparse.ArgumentTypeError(str(exc)) from None
69
+
70
+
71
+ def _expiry_option() -> argparse.ArgumentParser:
72
+ """``--expiry-hours``, shared by the commands that claim or resume a name."""
73
+ parent = argparse.ArgumentParser(add_help=False)
74
+ parent.add_argument(
75
+ "--expiry-hours", dest="expiry", type=_expiry_argument, default=None, metavar="HOURS",
76
+ help=f"how long the hub keeps your name, its channels and the messages waiting for it "
77
+ f"after you disconnect (env {EXPIRY_ENV}; default 24)",
78
+ )
79
+ return parent
80
+
81
+
82
+ def build_parser() -> argparse.ArgumentParser:
83
+ parser = argparse.ArgumentParser(prog="optio-chat", description="Chat with optio agents.")
84
+ parser.add_argument("--hub", default=os.environ.get("OPTIO_CHAT_HUB"),
85
+ help="the hub's URL (env OPTIO_CHAT_HUB)")
86
+ parser.add_argument("--password", default=os.environ.get("OPTIO_CHAT_SHARED_PASSWORD"),
87
+ help="the hub's password (env OPTIO_CHAT_SHARED_PASSWORD)")
88
+ parser.add_argument("--name", default=os.environ.get("OPTIO_CHAT_NAME"),
89
+ help="which of your names to act as (env OPTIO_CHAT_NAME)")
90
+ parser.add_argument("--keys-dir", type=Path, default=DEFAULT_KEYS_DIR,
91
+ help=f"where name keys are kept (default {DEFAULT_KEYS_DIR})")
92
+ sub = parser.add_subparsers(dest="command", required=True)
93
+ expiry = [_expiry_option()]
94
+
95
+ p = sub.add_parser("name", parents=expiry,
96
+ help="claim a name (its key is saved for later commands)")
97
+ p.add_argument("new_name")
98
+ p = sub.add_parser("join", parents=expiry, help="join a channel")
99
+ p.add_argument("channel")
100
+ p = sub.add_parser("send", parents=expiry, help="send a message to a channel")
101
+ p.add_argument("channel")
102
+ p.add_argument("text")
103
+ p = sub.add_parser("describe", parents=expiry,
104
+ help="set a channel's description (sole member only)")
105
+ p.add_argument("channel")
106
+ p.add_argument("text")
107
+ p = sub.add_parser("avatar", parents=expiry, help="set your avatar from an image file")
108
+ p.add_argument("path", type=Path)
109
+ sub.add_parser("read", parents=expiry, help="print the messages waiting for you, then exit")
110
+ sub.add_parser("listen", parents=expiry,
111
+ help="stay connected and print messages as they arrive")
112
+ sub.add_parser("mcp", parents=expiry,
113
+ help="run the MCP server of the Claude Code plugin (stdio)")
114
+ sub.add_parser("monitor", help="run the plugin monitor (prints pushed messages)")
115
+ sub.add_parser("plugin-dir", help="print the Claude Code plugin's directory")
116
+ return parser
117
+
118
+
119
+ _PLUGIN_COMMANDS = {"mcp", "monitor", "plugin-dir"}
120
+
121
+
122
+ def _command(name: str):
123
+ attr = "cmd_" + name.replace("-", "_")
124
+ if name in _PLUGIN_COMMANDS:
125
+ from optio_chat.plugin import commands as module
126
+ else:
127
+ from optio_chat import cli_commands as module
128
+ return getattr(module, attr)
129
+
130
+
131
+ def main(argv: list[str] | None = None) -> int:
132
+ args = build_parser().parse_args(argv)
133
+ try:
134
+ return asyncio.run(_command(args.command)(args))
135
+ except KeyboardInterrupt:
136
+ return 130
137
+
138
+
139
+ if __name__ == "__main__": # pragma: no cover
140
+ sys.exit(main())
@@ -0,0 +1,293 @@
1
+ """The CLI's chat commands: ``optio-chat name | join | send | describe | avatar | read | listen``.
2
+
3
+ Each ``cmd_*`` takes the parsed ``argparse.Namespace`` (see ``optio_chat.cli.build_parser``) and
4
+ returns the exit code: 0 success, 2 a chat error (its ``texts.error_text`` on stderr), 1 anything
5
+ else (missing settings, an unusable hub URL, an unknown or ambiguous name). Connections come from
6
+ ``connector_for(args)`` so tests can substitute ``FakeHub.connector()``.
7
+
8
+ ``name`` claims a name and keeps its key (``optio_chat.keys``); every other command resumes the
9
+ name from ``--name`` (or the only name kept for that hub), acts, and disconnects: the session
10
+ stays at the hub for the session expiry (``optio_chat.cli.session_expiry``: ``--expiry-hours``,
11
+ else ``OPTIO_CHAT_EXPIRY_HOURS``, else 24 hours), so messages wait between commands. Output texts
12
+ are the agents' (``optio_chat.texts``), with verbs rendered as CLI subcommands. What other agents
13
+ wrote (messages, channel descriptions) is printed as the plugin shows it (``wire.peer_line``: no
14
+ control characters, one line). A claimed name whose key cannot be saved is given up again (exit
15
+ 1, ``texts.key_not_saved``).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import asyncio
22
+ import contextlib
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import AsyncIterator, Awaitable, Callable
26
+
27
+ from optio_chat import texts, wire
28
+ from optio_chat.api import ChatConnectionAPI, Connector
29
+ from optio_chat.cli import session_expiry
30
+ from optio_chat.client import mqtt_connector
31
+ from optio_chat.keys import KeyStore
32
+ from optio_chat.plugin.bridge import monitor_line, shown_join
33
+ from optio_chat.models import (
34
+ ERR_FILE_NOT_FOUND,
35
+ ERR_HUB_UNREACHABLE,
36
+ ERR_NAME_LOST,
37
+ ERR_NO_NAME,
38
+ ERR_WRONG_KEY,
39
+ ChatError,
40
+ ChatMessage,
41
+ HubAddress,
42
+ )
43
+
44
+ READ_QUIET_S = 1.0 # `read` exits once nothing new arrived for this long (tests shorten it)
45
+
46
+
47
+ class CommandError(Exception):
48
+ """A problem outside the chat itself (settings, names kept here): exit code 1."""
49
+
50
+
51
+ class _Told(Exception):
52
+ """A problem outside the chat whose text is a ``texts`` one (printed as is, then the detail
53
+ as ``optio-chat: <detail>``): exit code 1."""
54
+
55
+ def __init__(self, text: str, detail: str) -> None:
56
+ super().__init__(text)
57
+ self.text = text
58
+ self.detail = detail
59
+
60
+
61
+ def cli_ref(key: str) -> str:
62
+ """A verb key ("name", "join", ...) as the subcommand that does it, for the texts."""
63
+ return f"`optio-chat {key}`"
64
+
65
+
66
+ def connector_for(args: argparse.Namespace) -> Connector:
67
+ """The Connector for ``args.hub`` / ``args.password`` (tests patch this)."""
68
+ if not args.hub:
69
+ raise CommandError("no hub given: use --hub or set OPTIO_CHAT_HUB")
70
+ if not args.password:
71
+ raise CommandError(
72
+ "no hub password given: use --password or set OPTIO_CHAT_SHARED_PASSWORD")
73
+ try:
74
+ return mqtt_connector(HubAddress(args.hub, args.password))
75
+ except ValueError as exc:
76
+ raise CommandError(str(exc)) from None
77
+
78
+
79
+ def _bare(channel: str) -> str:
80
+ """The channel argument without its '#' (the form ``texts.error_text`` wants)."""
81
+ return channel[1:] if channel.startswith("#") else channel
82
+
83
+
84
+ class _Run:
85
+ """One command: its key store, the name it acts as, its connection."""
86
+
87
+ def __init__(self, args: argparse.Namespace) -> None:
88
+ self.args = args
89
+ self.store = KeyStore(args.keys_dir)
90
+ self.name: str | None = None
91
+ self.conn: ChatConnectionAPI | None = None
92
+
93
+ def expiry(self) -> int:
94
+ """The session expiry to claim or resume with, in seconds."""
95
+ try:
96
+ return session_expiry(self.args)
97
+ except ValueError as exc:
98
+ raise CommandError(str(exc)) from None
99
+
100
+ def _pick_name(self) -> str:
101
+ if self.args.name:
102
+ return self.args.name
103
+ names = self.store.names(self.args.hub)
104
+ if not names:
105
+ raise ChatError(ERR_NO_NAME)
106
+ if len(names) > 1:
107
+ raise CommandError(f"you hold several names on this hub ({', '.join(names)}); "
108
+ "choose one with --name")
109
+ return names[0]
110
+
111
+ async def resume(self) -> ChatConnectionAPI:
112
+ connector = connector_for(self.args)
113
+ expiry = self.expiry()
114
+ name = self.name = self._pick_name()
115
+ key = self.store.load(self.args.hub, name)
116
+ if key is None:
117
+ raise CommandError(f"no key is kept for the name {name} on this hub; claim it with "
118
+ f"`optio-chat name {name}`")
119
+ self.conn = await connector.resume(name, key, expiry=expiry)
120
+ self.name = self.conn.name
121
+ return self.conn
122
+
123
+
124
+ async def _run(args: argparse.Namespace, body: Callable[[_Run], Awaitable[None]],
125
+ **context: str) -> int:
126
+ run = _Run(args)
127
+ try:
128
+ await body(run)
129
+ return 0
130
+ except CommandError as exc:
131
+ print(f"optio-chat: {exc}", file=sys.stderr)
132
+ return 1
133
+ except _Told as exc:
134
+ print(exc.text, file=sys.stderr)
135
+ print(f"optio-chat: {exc.detail}", file=sys.stderr)
136
+ return 1
137
+ except ChatError as err:
138
+ if err.code in (ERR_WRONG_KEY, ERR_NAME_LOST) and run.name and args.hub:
139
+ run.store.delete(args.hub, run.name) # the hub no longer knows this name
140
+ print(texts.error_text(err, cli_ref, name=run.name, **context), file=sys.stderr)
141
+ return 2
142
+ finally:
143
+ if run.conn is not None:
144
+ await run.conn.close()
145
+
146
+
147
+ async def cmd_name(args: argparse.Namespace) -> int:
148
+ async def body(run: _Run) -> None:
149
+ run.name = args.new_name
150
+ connector = connector_for(args)
151
+ expiry = run.expiry()
152
+ key = run.store.load(args.hub, args.new_name)
153
+ if key is not None: # held already: just check it
154
+ try:
155
+ run.conn = await connector.resume(args.new_name, key, expiry=expiry)
156
+ except ChatError as err:
157
+ if err.code != ERR_WRONG_KEY:
158
+ raise
159
+ run.store.delete(args.hub, args.new_name)
160
+ else:
161
+ print(texts.answer_named(run.conn.name))
162
+ return
163
+ run.conn, key = await connector.claim(args.new_name, expiry=expiry)
164
+ try:
165
+ run.store.save(args.hub, run.conn.name, key)
166
+ except OSError as exc:
167
+ # Nobody could ever resume the name: end it at once.
168
+ with contextlib.suppress(ChatError):
169
+ await run.conn.release()
170
+ raise _Told(texts.key_not_saved(run.conn.name, cli_ref), str(exc)) from None
171
+ print(texts.answer_named(run.conn.name))
172
+
173
+ return await _run(args, body)
174
+
175
+
176
+ async def cmd_join(args: argparse.Namespace) -> int:
177
+ async def body(run: _Run) -> None:
178
+ result = await (await run.resume()).join(args.channel)
179
+ print(texts.answer_joined(shown_join(result), cli_ref))
180
+
181
+ return await _run(args, body, channel=_bare(args.channel))
182
+
183
+
184
+ async def cmd_send(args: argparse.Namespace) -> int:
185
+ async def body(run: _Run) -> None:
186
+ result = await (await run.resume()).send(args.channel, args.text)
187
+ if not result.reached_others:
188
+ print(texts.warning_nobody(result.channel), file=sys.stderr)
189
+
190
+ return await _run(args, body, channel=_bare(args.channel), what="message")
191
+
192
+
193
+ async def cmd_describe(args: argparse.Namespace) -> int:
194
+ async def body(run: _Run) -> None:
195
+ await (await run.resume()).describe(args.channel, args.text)
196
+ print(texts.answer_described(wire.check_channel(args.channel), cleared=not args.text))
197
+
198
+ return await _run(args, body, channel=_bare(args.channel), what="description")
199
+
200
+
201
+ async def cmd_avatar(args: argparse.Namespace) -> int:
202
+ async def body(run: _Run) -> None:
203
+ try:
204
+ image = Path(args.path).read_bytes()
205
+ except OSError:
206
+ raise ChatError(ERR_FILE_NOT_FOUND, str(args.path)) from None
207
+ wire.check_avatar(image) # refuse before connecting
208
+ await (await run.resume()).set_avatar(image)
209
+ print(texts.answer_avatar_set())
210
+
211
+ return await _run(args, body, path=str(args.path), what="avatar")
212
+
213
+
214
+ def _line(message: ChatMessage) -> str:
215
+ """A message as ``read`` and ``listen`` print it: as the plugin monitor prints it
216
+ (``monitor_line``: control characters removed, line breaks escaped), so a message cannot pass
217
+ a line of its own text off as another message, nor act on the terminal."""
218
+ return monitor_line(message)
219
+
220
+
221
+ async def _next(messages: AsyncIterator[ChatMessage]) -> ChatMessage | None:
222
+ try:
223
+ return await anext(messages)
224
+ except StopAsyncIteration:
225
+ return None
226
+
227
+
228
+ async def _next_within(messages: AsyncIterator[ChatMessage], quiet: float) -> ChatMessage | None:
229
+ """The next message, or None when none came within ``quiet`` seconds (or the stream ended).
230
+ A message that is already there always wins over the timer: the step runs before the timer
231
+ can fire, and a finished step is used even when the timer fired too."""
232
+ step = asyncio.ensure_future(_next(messages))
233
+ try:
234
+ await asyncio.wait({step}, timeout=quiet)
235
+ finally:
236
+ if not step.done():
237
+ step.cancel()
238
+ with contextlib.suppress(asyncio.CancelledError):
239
+ await step
240
+ return None if step.cancelled() else step.result()
241
+
242
+
243
+ async def cmd_read(args: argparse.Namespace) -> int:
244
+ async def body(run: _Run) -> None:
245
+ conn = await run.resume()
246
+ messages = conn.incoming()
247
+ try:
248
+ while (message := await _next_within(messages, READ_QUIET_S)) is not None:
249
+ print(_line(message), flush=True)
250
+ await conn.ack(message)
251
+ finally:
252
+ await messages.aclose()
253
+
254
+ return await _run(args, body)
255
+
256
+
257
+ async def _ack_all(conn: ChatConnectionAPI, messages: list[ChatMessage]) -> list[ChatMessage]:
258
+ """Acknowledge what can be; return the ones to retry (the hub was unreachable)."""
259
+ retry = []
260
+ for message in messages:
261
+ try:
262
+ await conn.ack(message)
263
+ except ChatError as err:
264
+ if err.code != ERR_HUB_UNREACHABLE:
265
+ raise
266
+ retry.append(message)
267
+ return retry
268
+
269
+
270
+ async def cmd_listen(args: argparse.Namespace) -> int:
271
+ async def body(run: _Run) -> None:
272
+ conn = await run.resume()
273
+ lost = False
274
+
275
+ async def on_name_lost() -> None:
276
+ nonlocal lost
277
+ lost = True
278
+
279
+ conn.on_name_lost = on_name_lost
280
+ unacked: list[ChatMessage] = []
281
+ messages = conn.incoming()
282
+ try:
283
+ async for message in messages:
284
+ print(_line(message), flush=True)
285
+ unacked = await _ack_all(conn, [*unacked, message])
286
+ finally:
287
+ await messages.aclose()
288
+ if lost:
289
+ raise ChatError(ERR_NAME_LOST, run.name or "")
290
+ raise CommandError(f"the hub closed this connection; another client now uses the name "
291
+ f"{run.name}")
292
+
293
+ return await _run(args, body)