optio-chat 0.1.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.
- optio_chat-0.1.0/PKG-INFO +55 -0
- optio_chat-0.1.0/README.md +24 -0
- optio_chat-0.1.0/pyproject.toml +67 -0
- optio_chat-0.1.0/setup.cfg +4 -0
- optio_chat-0.1.0/src/optio_chat/__init__.py +36 -0
- optio_chat-0.1.0/src/optio_chat/api.py +95 -0
- optio_chat-0.1.0/src/optio_chat/cli.py +140 -0
- optio_chat-0.1.0/src/optio_chat/cli_commands.py +293 -0
- optio_chat-0.1.0/src/optio_chat/client.py +822 -0
- optio_chat-0.1.0/src/optio_chat/hub/__init__.py +93 -0
- optio_chat-0.1.0/src/optio_chat/hub/codec.py +645 -0
- optio_chat-0.1.0/src/optio_chat/hub/core.py +927 -0
- optio_chat-0.1.0/src/optio_chat/hub/images.py +84 -0
- optio_chat-0.1.0/src/optio_chat/hub/packets.py +202 -0
- optio_chat-0.1.0/src/optio_chat/hub/store.py +334 -0
- optio_chat-0.1.0/src/optio_chat/hub/transport.py +346 -0
- optio_chat-0.1.0/src/optio_chat/keys.py +90 -0
- optio_chat-0.1.0/src/optio_chat/models.py +90 -0
- optio_chat-0.1.0/src/optio_chat/plugin/__init__.py +2 -0
- optio_chat-0.1.0/src/optio_chat/plugin/bridge.py +248 -0
- optio_chat-0.1.0/src/optio_chat/plugin/claude_plugin/.claude-plugin/plugin.json +5 -0
- optio_chat-0.1.0/src/optio_chat/plugin/claude_plugin/.mcp.json +14 -0
- optio_chat-0.1.0/src/optio_chat/plugin/claude_plugin/README.md +91 -0
- optio_chat-0.1.0/src/optio_chat/plugin/claude_plugin/monitors/monitors.json +7 -0
- optio_chat-0.1.0/src/optio_chat/plugin/commands.py +76 -0
- optio_chat-0.1.0/src/optio_chat/plugin/mcp_stdio.py +537 -0
- optio_chat-0.1.0/src/optio_chat/plugin/monitor.py +85 -0
- optio_chat-0.1.0/src/optio_chat/testing.py +411 -0
- optio_chat-0.1.0/src/optio_chat/texts.py +466 -0
- optio_chat-0.1.0/src/optio_chat/wire.py +380 -0
- optio_chat-0.1.0/src/optio_chat.egg-info/PKG-INFO +55 -0
- optio_chat-0.1.0/src/optio_chat.egg-info/SOURCES.txt +48 -0
- optio_chat-0.1.0/src/optio_chat.egg-info/dependency_links.txt +1 -0
- optio_chat-0.1.0/src/optio_chat.egg-info/entry_points.txt +2 -0
- optio_chat-0.1.0/src/optio_chat.egg-info/requires.txt +12 -0
- optio_chat-0.1.0/src/optio_chat.egg-info/top_level.txt +1 -0
- optio_chat-0.1.0/tests/test_cli.py +413 -0
- optio_chat-0.1.0/tests/test_client.py +1142 -0
- optio_chat-0.1.0/tests/test_codec.py +686 -0
- optio_chat-0.1.0/tests/test_conformance_paho.py +922 -0
- optio_chat-0.1.0/tests/test_core.py +1593 -0
- optio_chat-0.1.0/tests/test_fake_hub.py +641 -0
- optio_chat-0.1.0/tests/test_integration_client_hub.py +250 -0
- optio_chat-0.1.0/tests/test_keys.py +112 -0
- optio_chat-0.1.0/tests/test_plugin_bridge.py +328 -0
- optio_chat-0.1.0/tests/test_plugin_mcp.py +498 -0
- optio_chat-0.1.0/tests/test_store.py +240 -0
- optio_chat-0.1.0/tests/test_texts.py +219 -0
- optio_chat-0.1.0/tests/test_transport.py +571 -0
- optio_chat-0.1.0/tests/test_wire.py +238 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: optio-chat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Agent chat for optio: an MQTT 5 hub, a client library, a CLI and a Claude Code plugin
|
|
5
|
+
Author-email: Kristof Csillag <kristof.csillag@deai-labs.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/deai-network/optio
|
|
8
|
+
Project-URL: Repository, https://github.com/deai-network/optio
|
|
9
|
+
Project-URL: Issues, https://github.com/deai-network/optio/issues
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Operating System :: MacOS
|
|
17
|
+
Classifier: Topic :: Communications :: Chat
|
|
18
|
+
Classifier: Framework :: AsyncIO
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: paho-mqtt<3,>=2.1
|
|
22
|
+
Provides-Extra: hub
|
|
23
|
+
Requires-Dist: motor>=3.3.0; extra == "hub"
|
|
24
|
+
Requires-Dist: aiohttp>=3.9; extra == "hub"
|
|
25
|
+
Requires-Dist: Pillow>=10; extra == "hub"
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: optio-chat[hub]; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
29
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-xdist>=3.6; extra == "dev"
|
|
31
|
+
|
|
32
|
+
# optio-chat
|
|
33
|
+
|
|
34
|
+
Agent chat for optio. Agents claim names, join channels and send messages to channels; every member
|
|
35
|
+
of a channel receives its messages, except the sender.
|
|
36
|
+
|
|
37
|
+
- **The hub** (`optio_chat.hub`, install `optio-chat[hub]`): an MQTT 5 broker that keeps names,
|
|
38
|
+
channels, memberships, undelivered messages and avatars in MongoDB, so a restart loses nothing.
|
|
39
|
+
Every optio engine runs one; an engine can share its hub with other servers.
|
|
40
|
+
- **The client library** (`optio_chat.client`): an asyncio client over paho-mqtt.
|
|
41
|
+
- **The CLI** (`optio-chat`): claim a name, join, send, read and listen from a shell.
|
|
42
|
+
- **The Claude Code plugin** (`optio-chat plugin-dir`): an MCP server with the chat tools and a
|
|
43
|
+
monitor that pushes incoming messages into an interactive Claude Code session.
|
|
44
|
+
|
|
45
|
+
Settings: `OPTIO_CHAT_HUB` (the hub's URL, e.g. `wss://app.example.com/api/chat/<db>/<prefix>`)
|
|
46
|
+
and `OPTIO_CHAT_SHARED_PASSWORD`.
|
|
47
|
+
|
|
48
|
+
A name you claim with the CLI or the plugin stays at the hub, with its channels and the messages
|
|
49
|
+
waiting for it, for 24 hours after you disconnect; then the hub releases it. To change that, give
|
|
50
|
+
the commands that claim or resume a name `--expiry-hours HOURS` (e.g.
|
|
51
|
+
`optio-chat send --expiry-hours 72 '#design' 'back on Monday'`), or set `OPTIO_CHAT_EXPIRY_HOURS`
|
|
52
|
+
(the plugin reads only the variable). It takes a positive number of hours; fractions such as
|
|
53
|
+
`0.5` work, `0` is refused.
|
|
54
|
+
|
|
55
|
+
Design: `docs/2026-11-24-agent-chat-design.md` in the optio repository.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# optio-chat
|
|
2
|
+
|
|
3
|
+
Agent chat for optio. Agents claim names, join channels and send messages to channels; every member
|
|
4
|
+
of a channel receives its messages, except the sender.
|
|
5
|
+
|
|
6
|
+
- **The hub** (`optio_chat.hub`, install `optio-chat[hub]`): an MQTT 5 broker that keeps names,
|
|
7
|
+
channels, memberships, undelivered messages and avatars in MongoDB, so a restart loses nothing.
|
|
8
|
+
Every optio engine runs one; an engine can share its hub with other servers.
|
|
9
|
+
- **The client library** (`optio_chat.client`): an asyncio client over paho-mqtt.
|
|
10
|
+
- **The CLI** (`optio-chat`): claim a name, join, send, read and listen from a shell.
|
|
11
|
+
- **The Claude Code plugin** (`optio-chat plugin-dir`): an MCP server with the chat tools and a
|
|
12
|
+
monitor that pushes incoming messages into an interactive Claude Code session.
|
|
13
|
+
|
|
14
|
+
Settings: `OPTIO_CHAT_HUB` (the hub's URL, e.g. `wss://app.example.com/api/chat/<db>/<prefix>`)
|
|
15
|
+
and `OPTIO_CHAT_SHARED_PASSWORD`.
|
|
16
|
+
|
|
17
|
+
A name you claim with the CLI or the plugin stays at the hub, with its channels and the messages
|
|
18
|
+
waiting for it, for 24 hours after you disconnect; then the hub releases it. To change that, give
|
|
19
|
+
the commands that claim or resume a name `--expiry-hours HOURS` (e.g.
|
|
20
|
+
`optio-chat send --expiry-hours 72 '#design' 'back on Monday'`), or set `OPTIO_CHAT_EXPIRY_HOURS`
|
|
21
|
+
(the plugin reads only the variable). It takes a positive number of hours; fractions such as
|
|
22
|
+
`0.5` work, `0` is refused.
|
|
23
|
+
|
|
24
|
+
Design: `docs/2026-11-24-agent-chat-design.md` in the optio repository.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "optio-chat"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Agent chat for optio: an MQTT 5 hub, a client library, a CLI and a Claude Code plugin"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Kristof Csillag", email = "kristof.csillag@deai-labs.com" },
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Operating System :: POSIX :: Linux",
|
|
22
|
+
"Operating System :: MacOS",
|
|
23
|
+
"Topic :: Communications :: Chat",
|
|
24
|
+
"Framework :: AsyncIO",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"paho-mqtt>=2.1,<3",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
hub = [
|
|
32
|
+
"motor>=3.3.0",
|
|
33
|
+
"aiohttp>=3.9",
|
|
34
|
+
"Pillow>=10",
|
|
35
|
+
]
|
|
36
|
+
dev = [
|
|
37
|
+
"optio-chat[hub]",
|
|
38
|
+
"pytest>=8.0",
|
|
39
|
+
"pytest-asyncio>=0.23",
|
|
40
|
+
"pytest-xdist>=3.6",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[project.urls]
|
|
44
|
+
Homepage = "https://github.com/deai-network/optio"
|
|
45
|
+
Repository = "https://github.com/deai-network/optio"
|
|
46
|
+
Issues = "https://github.com/deai-network/optio/issues"
|
|
47
|
+
|
|
48
|
+
[project.scripts]
|
|
49
|
+
optio-chat = "optio_chat.cli:main"
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.packages.find]
|
|
52
|
+
where = ["src"]
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.package-data]
|
|
55
|
+
optio_chat = [
|
|
56
|
+
"plugin/claude_plugin/**/*",
|
|
57
|
+
"plugin/claude_plugin/.claude-plugin/*",
|
|
58
|
+
"plugin/claude_plugin/.mcp.json",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
[tool.pytest.ini_options]
|
|
62
|
+
asyncio_mode = "auto"
|
|
63
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
64
|
+
testpaths = ["tests"]
|
|
65
|
+
markers = [
|
|
66
|
+
"serial: spawn-heavy or timing-fragile tests, run in the serial phase",
|
|
67
|
+
]
|
|
@@ -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
|
+
]
|
|
@@ -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."""
|
|
@@ -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())
|