jchat 0.2.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.
- jchat/__init__.py +66 -0
- jchat/beat.py +104 -0
- jchat/cli.py +449 -0
- jchat/client.py +218 -0
- jchat/hooks.py +220 -0
- jchat/mcp.py +404 -0
- jchat/net.py +438 -0
- jchat/node.py +1029 -0
- jchat/schema.py +157 -0
- jchat-0.2.0.dist-info/METADATA +102 -0
- jchat-0.2.0.dist-info/RECORD +15 -0
- jchat-0.2.0.dist-info/WHEEL +5 -0
- jchat-0.2.0.dist-info/entry_points.txt +2 -0
- jchat-0.2.0.dist-info/licenses/LICENSE +21 -0
- jchat-0.2.0.dist-info/top_level.txt +1 -0
jchat/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""jchat v0.2: decentralized signal & notification bus for coordinating AI agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .schema import (
|
|
6
|
+
AuthError,
|
|
7
|
+
DEFAULT_LEASE_S,
|
|
8
|
+
DEFAULT_PORT,
|
|
9
|
+
DEFAULT_TTL_S,
|
|
10
|
+
DeliveryError,
|
|
11
|
+
Envelope,
|
|
12
|
+
JChatError,
|
|
13
|
+
KINDS,
|
|
14
|
+
MAX_BODY,
|
|
15
|
+
NETMODES,
|
|
16
|
+
PRIORITIES,
|
|
17
|
+
REF_PREFIXES,
|
|
18
|
+
STATES,
|
|
19
|
+
VERSION,
|
|
20
|
+
ValidationError,
|
|
21
|
+
validate_envelope,
|
|
22
|
+
validate_name,
|
|
23
|
+
validate_ref,
|
|
24
|
+
wrap_untrusted,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__version__ = VERSION
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"AuthError",
|
|
31
|
+
"Client",
|
|
32
|
+
"DEFAULT_LEASE_S",
|
|
33
|
+
"DEFAULT_PORT",
|
|
34
|
+
"DEFAULT_TTL_S",
|
|
35
|
+
"DeliveryError",
|
|
36
|
+
"Envelope",
|
|
37
|
+
"JChatError",
|
|
38
|
+
"KINDS",
|
|
39
|
+
"MAX_BODY",
|
|
40
|
+
"NETMODES",
|
|
41
|
+
"NetPolicy",
|
|
42
|
+
"Node",
|
|
43
|
+
"PRIORITIES",
|
|
44
|
+
"REF_PREFIXES",
|
|
45
|
+
"STATES",
|
|
46
|
+
"VERSION",
|
|
47
|
+
"ValidationError",
|
|
48
|
+
"__version__",
|
|
49
|
+
"validate_envelope",
|
|
50
|
+
"validate_name",
|
|
51
|
+
"validate_ref",
|
|
52
|
+
"wrap_untrusted",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def __getattr__(name: str):
|
|
57
|
+
if name == "Node":
|
|
58
|
+
from .node import Node
|
|
59
|
+
return Node
|
|
60
|
+
if name == "Client":
|
|
61
|
+
from .client import Client
|
|
62
|
+
return Client
|
|
63
|
+
if name == "NetPolicy":
|
|
64
|
+
from .net import NetPolicy
|
|
65
|
+
return NetPolicy
|
|
66
|
+
raise AttributeError(f"module 'jchat' has no attribute {name!r}")
|
jchat/beat.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Compatibility beat shim using Client and JCHAT_AGENT silently.
|
|
2
|
+
|
|
3
|
+
A delegate run registers as ``<parent>-subNN`` while running. Failures to reach
|
|
4
|
+
the node never raise or block the run, and tokens/keys are never logged.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .client import Client
|
|
17
|
+
|
|
18
|
+
CONTROL_RE = re.compile(r"[\x00-\x1f\x7f]")
|
|
19
|
+
_UNREGISTER_STATES = frozenset({"done", "offline", "stopped", "exit"})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parent_id() -> str | None:
|
|
23
|
+
"""Return this run's parent agent id from JCHAT_AGENT, or None if unset."""
|
|
24
|
+
return os.environ.get("JCHAT_AGENT") or None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _counter_file() -> Path:
|
|
28
|
+
return Path.home() / ".jchat" / "sub_counter.json"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def next_sub(parent: str) -> str:
|
|
32
|
+
"""Return the next ``{parent}-subNN`` id (01..99, wrapping 99 -> 01)."""
|
|
33
|
+
path = _counter_file()
|
|
34
|
+
try:
|
|
35
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
36
|
+
if not isinstance(data, dict):
|
|
37
|
+
data = {}
|
|
38
|
+
except Exception:
|
|
39
|
+
data = {}
|
|
40
|
+
try:
|
|
41
|
+
n = int(data.get(parent, 0))
|
|
42
|
+
except Exception:
|
|
43
|
+
n = 0
|
|
44
|
+
n += 1
|
|
45
|
+
if n < 1 or n > 99:
|
|
46
|
+
n = 1
|
|
47
|
+
data[parent] = n
|
|
48
|
+
try:
|
|
49
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
50
|
+
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=path.name + ".", suffix=".tmp")
|
|
51
|
+
try:
|
|
52
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
53
|
+
f.write(json.dumps(data))
|
|
54
|
+
os.replace(tmp, path)
|
|
55
|
+
except Exception:
|
|
56
|
+
try:
|
|
57
|
+
os.unlink(tmp)
|
|
58
|
+
except OSError:
|
|
59
|
+
pass
|
|
60
|
+
return f"{parent}-sub01"
|
|
61
|
+
except Exception:
|
|
62
|
+
return f"{parent}-sub01"
|
|
63
|
+
return f"{parent}-sub{n:02d}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _clean(task: str) -> str:
|
|
67
|
+
return CONTROL_RE.sub("", task or "")[:80]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def beat(sub_id: str, state: str, task: str = "", *, timeout: float = 10.0) -> bool:
|
|
71
|
+
"""Send one registration heartbeat for sub_id via Client.
|
|
72
|
+
|
|
73
|
+
Silent no-op (returns False) when JCHAT_AGENT is unset. Never raises and
|
|
74
|
+
never logs tokens or exception bodies (only the exception type name).
|
|
75
|
+
"""
|
|
76
|
+
if not os.environ.get("JCHAT_AGENT"):
|
|
77
|
+
return False
|
|
78
|
+
clean_task = _clean(task)
|
|
79
|
+
label = f"{state}: {clean_task}".strip(": ") if state else clean_task
|
|
80
|
+
unregister = state in _UNREGISTER_STATES
|
|
81
|
+
try:
|
|
82
|
+
client = Client(url=os.environ.get("JCHAT_URL") or None, timeout=timeout)
|
|
83
|
+
client.register(
|
|
84
|
+
sub_id,
|
|
85
|
+
pid=os.getpid(),
|
|
86
|
+
task=label,
|
|
87
|
+
unregister=unregister,
|
|
88
|
+
)
|
|
89
|
+
return True
|
|
90
|
+
except Exception as exc:
|
|
91
|
+
sys.stderr.write(f"jchat.beat: {type(exc).__name__}\n")
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
if __name__ == "__main__":
|
|
96
|
+
_state = sys.argv[1] if len(sys.argv) > 1 else "working"
|
|
97
|
+
_task = " ".join(sys.argv[2:])
|
|
98
|
+
_parent = parent_id()
|
|
99
|
+
if _parent is None:
|
|
100
|
+
print("none")
|
|
101
|
+
else:
|
|
102
|
+
_sub = next_sub(_parent)
|
|
103
|
+
beat(_sub, _state, _task)
|
|
104
|
+
print(_sub)
|
jchat/cli.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""Command-line interface and built-in doctor self-test for jchat v0.2."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import importlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sqlite3
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from .client import Client
|
|
18
|
+
from .hooks import SUPPORTED_HARNESSES, install_hooks, run_hook_pull
|
|
19
|
+
from .mcp import _make_callback_server, serve_mcp
|
|
20
|
+
from .schema import (
|
|
21
|
+
DEFAULT_LEASE_S,
|
|
22
|
+
DEFAULT_PORT,
|
|
23
|
+
DEFAULT_TTL_S,
|
|
24
|
+
JChatError,
|
|
25
|
+
KINDS,
|
|
26
|
+
MAX_BODY,
|
|
27
|
+
PRIORITIES,
|
|
28
|
+
VERSION,
|
|
29
|
+
ValidationError,
|
|
30
|
+
wrap_untrusted,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _resolve_agent(positional: str | None, flag: str | None) -> str:
|
|
35
|
+
agent = flag or positional or os.environ.get("JCHAT_AGENT")
|
|
36
|
+
if not agent:
|
|
37
|
+
raise ValidationError("agent is required (pass positional/flag or set JCHAT_AGENT)")
|
|
38
|
+
return agent
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _node_url_and_start(node: Any) -> str:
|
|
42
|
+
if hasattr(node, "start") and callable(node.start):
|
|
43
|
+
node.start()
|
|
44
|
+
elif hasattr(node, "serve_forever") and callable(node.serve_forever):
|
|
45
|
+
t = threading.Thread(target=node.serve_forever, daemon=True)
|
|
46
|
+
t.start()
|
|
47
|
+
|
|
48
|
+
url = getattr(node, "url", None)
|
|
49
|
+
if isinstance(url, str) and url:
|
|
50
|
+
return url.rstrip("/")
|
|
51
|
+
port = getattr(node, "port", None)
|
|
52
|
+
if not port and hasattr(node, "server_address"):
|
|
53
|
+
port = node.server_address[1]
|
|
54
|
+
elif not port and hasattr(node, "server") and hasattr(node.server, "server_address"):
|
|
55
|
+
port = node.server.server_address[1]
|
|
56
|
+
if not port:
|
|
57
|
+
raise RuntimeError("could not determine bound port from Node")
|
|
58
|
+
return f"http://127.0.0.1:{port}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _shutdown_node(node: Any) -> None:
|
|
62
|
+
for method in ("stop", "shutdown", "close", "server_close"):
|
|
63
|
+
fn = getattr(node, method, None)
|
|
64
|
+
if callable(fn):
|
|
65
|
+
try:
|
|
66
|
+
fn()
|
|
67
|
+
except Exception:
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _cmd_serve(args: argparse.Namespace) -> int:
|
|
72
|
+
node_mod = importlib.import_module("jchat.node")
|
|
73
|
+
Node = getattr(node_mod, "Node")
|
|
74
|
+
port = args.port if args.port is not None else None
|
|
75
|
+
node = Node.from_env(db_path=args.db, port=port) if hasattr(Node, "from_env") else Node(
|
|
76
|
+
db_path=args.db, port=args.port or DEFAULT_PORT
|
|
77
|
+
)
|
|
78
|
+
try:
|
|
79
|
+
if hasattr(node, "serve_forever") and callable(node.serve_forever):
|
|
80
|
+
url = getattr(node, "url", None) or f"http://127.0.0.1:{getattr(node, 'port', args.port)}"
|
|
81
|
+
print(f"jchat {VERSION} serving {url}", file=sys.stderr, flush=True)
|
|
82
|
+
node.serve_forever()
|
|
83
|
+
elif hasattr(node, "start") and callable(node.start):
|
|
84
|
+
url = _node_url_and_start(node)
|
|
85
|
+
print(f"jchat {VERSION} serving {url}", file=sys.stderr, flush=True)
|
|
86
|
+
stop_event = threading.Event()
|
|
87
|
+
try:
|
|
88
|
+
stop_event.wait()
|
|
89
|
+
except KeyboardInterrupt:
|
|
90
|
+
pass
|
|
91
|
+
else:
|
|
92
|
+
raise RuntimeError("Node exposes neither serve_forever() nor start()")
|
|
93
|
+
finally:
|
|
94
|
+
_shutdown_node(node)
|
|
95
|
+
return 0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _cmd_send(args: argparse.Namespace) -> int:
|
|
99
|
+
body = args.body
|
|
100
|
+
if body == "-":
|
|
101
|
+
body = sys.stdin.read()
|
|
102
|
+
if body.endswith("\n"):
|
|
103
|
+
body = body[:-1]
|
|
104
|
+
sender = args.sender or os.environ.get("JCHAT_SENDER") or os.environ.get("JCHAT_AGENT") or "anon"
|
|
105
|
+
client = Client(url=args.url)
|
|
106
|
+
res = client.send(
|
|
107
|
+
sender,
|
|
108
|
+
args.recipient,
|
|
109
|
+
body,
|
|
110
|
+
kind=args.kind,
|
|
111
|
+
ref=args.ref,
|
|
112
|
+
priority=args.priority,
|
|
113
|
+
ttl_s=args.ttl_s,
|
|
114
|
+
dedup_key=args.dedup_key,
|
|
115
|
+
reply_to=args.reply_to,
|
|
116
|
+
require_online=args.require_online,
|
|
117
|
+
)
|
|
118
|
+
if args.json:
|
|
119
|
+
print(json.dumps(res))
|
|
120
|
+
else:
|
|
121
|
+
print(f"sent {res.get('id', '?')} status={res.get('status', '?')}")
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _cmd_pull(args: argparse.Namespace) -> int:
|
|
126
|
+
agent = _resolve_agent(args.agent_pos, args.agent)
|
|
127
|
+
client = Client(url=args.url)
|
|
128
|
+
msgs = client.pull(agent, limit=args.limit, priority=args.priority, lease_s=args.lease_s)
|
|
129
|
+
if args.json:
|
|
130
|
+
print(json.dumps({"messages": msgs}))
|
|
131
|
+
elif args.raw:
|
|
132
|
+
for msg in msgs:
|
|
133
|
+
print(f"[{msg.get('id', '?')}] {msg.get('sender', '?')} ({msg.get('kind', 'notify')}): {msg.get('body', '')}")
|
|
134
|
+
else:
|
|
135
|
+
for msg in msgs:
|
|
136
|
+
print(wrap_untrusted(msg))
|
|
137
|
+
if args.ack:
|
|
138
|
+
for msg in msgs:
|
|
139
|
+
mid = msg.get("id")
|
|
140
|
+
if mid:
|
|
141
|
+
client.ack_read(str(mid), agent)
|
|
142
|
+
return 0
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _cmd_ack(args: argparse.Namespace) -> int:
|
|
146
|
+
agent = _resolve_agent(args.agent_pos, args.agent)
|
|
147
|
+
client = Client(url=args.url)
|
|
148
|
+
res = client.ack_read(args.msg_id, agent)
|
|
149
|
+
if args.json:
|
|
150
|
+
print(json.dumps(res))
|
|
151
|
+
else:
|
|
152
|
+
print(f"acked {res.get('id', args.msg_id)} status={res.get('status', 'read')} deleted={res.get('deleted', False)}")
|
|
153
|
+
return 0
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _cmd_status(args: argparse.Namespace) -> int:
|
|
157
|
+
client = Client(url=args.url)
|
|
158
|
+
res = client.status()
|
|
159
|
+
if args.json:
|
|
160
|
+
print(json.dumps(res))
|
|
161
|
+
else:
|
|
162
|
+
print(
|
|
163
|
+
f"node={res.get('node', '?')} netmode={res.get('netmode', '?')} "
|
|
164
|
+
f"queue_depth={res.get('queue_depth', 0)}"
|
|
165
|
+
)
|
|
166
|
+
for ag in res.get("agents", []):
|
|
167
|
+
state = "online" if ag.get("online") else "offline"
|
|
168
|
+
task = f" task={ag['task']}" if ag.get("task") else ""
|
|
169
|
+
print(f" {ag.get('agent', '?')}: {state}{task}")
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _cmd_register(args: argparse.Namespace) -> int:
|
|
174
|
+
client = Client(url=args.url)
|
|
175
|
+
res = client.register(
|
|
176
|
+
args.agent,
|
|
177
|
+
callback_url=args.callback or "",
|
|
178
|
+
pid=args.pid,
|
|
179
|
+
task=args.task or "",
|
|
180
|
+
ref=args.ref or "",
|
|
181
|
+
unregister=bool(args.unregister),
|
|
182
|
+
)
|
|
183
|
+
if args.json:
|
|
184
|
+
print(json.dumps(res))
|
|
185
|
+
else:
|
|
186
|
+
print(f"agent={res.get('agent', args.agent)} online={res.get('online', False)}")
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _cmd_ping(args: argparse.Namespace) -> int:
|
|
191
|
+
agent = _resolve_agent(args.agent_pos, args.agent)
|
|
192
|
+
client = Client(url=args.url)
|
|
193
|
+
res = client.ping(agent)
|
|
194
|
+
if args.json:
|
|
195
|
+
print(json.dumps(res))
|
|
196
|
+
else:
|
|
197
|
+
print(f"agent={res.get('agent', agent)} online={res.get('online', False)} rtt_ms={res.get('rtt_ms')}")
|
|
198
|
+
return 0
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _cmd_receipt(args: argparse.Namespace) -> int:
|
|
202
|
+
client = Client(url=args.url)
|
|
203
|
+
res = client.receipt(args.msg_id)
|
|
204
|
+
if args.json:
|
|
205
|
+
print(json.dumps(res))
|
|
206
|
+
else:
|
|
207
|
+
print(
|
|
208
|
+
f"id={res.get('id', args.msg_id)} status={res.get('status', '?')} "
|
|
209
|
+
f"reason={res.get('reason', '')}"
|
|
210
|
+
)
|
|
211
|
+
return 0
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _cmd_mcp(args: argparse.Namespace) -> int:
|
|
215
|
+
agent = _resolve_agent(None, args.agent)
|
|
216
|
+
return serve_mcp(agent, url=args.url, register_on_start=not args.no_register)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _cmd_hook(args: argparse.Namespace) -> int:
|
|
220
|
+
agent = _resolve_agent(None, args.agent)
|
|
221
|
+
return run_hook_pull(
|
|
222
|
+
agent,
|
|
223
|
+
url=args.url,
|
|
224
|
+
priority=args.priority,
|
|
225
|
+
auto_ack=not args.no_ack,
|
|
226
|
+
strict=args.strict,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _cmd_install_hooks(args: argparse.Namespace) -> int:
|
|
231
|
+
agent = _resolve_agent(None, args.agent)
|
|
232
|
+
path = install_hooks(
|
|
233
|
+
args.harness,
|
|
234
|
+
agent,
|
|
235
|
+
url=args.url,
|
|
236
|
+
remove=args.remove,
|
|
237
|
+
settings_path=args.settings_path,
|
|
238
|
+
)
|
|
239
|
+
action = "removed" if args.remove else "installed"
|
|
240
|
+
print(f"{action} {args.harness} hooks for {agent}: {path}")
|
|
241
|
+
return 0
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _cmd_doctor(args: argparse.Namespace) -> int:
|
|
245
|
+
try:
|
|
246
|
+
if sys.version_info < (3, 15):
|
|
247
|
+
raise RuntimeError(f"Python >= 3.15 required, got {sys.version.split()[0]}")
|
|
248
|
+
|
|
249
|
+
node_mod = importlib.import_module("jchat.node")
|
|
250
|
+
importlib.import_module("jchat.net")
|
|
251
|
+
client_mod = importlib.import_module("jchat.client")
|
|
252
|
+
Node = getattr(node_mod, "Node")
|
|
253
|
+
ClientCls = getattr(client_mod, "Client")
|
|
254
|
+
|
|
255
|
+
with tempfile.TemporaryDirectory(prefix="jchat-doctor-") as tmpdir:
|
|
256
|
+
db_path = Path(tmpdir) / "doctor.db"
|
|
257
|
+
node = Node(db_path=str(db_path), port=0)
|
|
258
|
+
cb_srv = _make_callback_server("doctor-agent")
|
|
259
|
+
cb_thread = threading.Thread(target=cb_srv.serve_forever, daemon=True)
|
|
260
|
+
cb_thread.start()
|
|
261
|
+
cb_url = f"http://127.0.0.1:{cb_srv.server_address[1]}/ping"
|
|
262
|
+
|
|
263
|
+
try:
|
|
264
|
+
node_url = _node_url_and_start(node)
|
|
265
|
+
client = ClientCls(url=node_url, timeout=5.0)
|
|
266
|
+
|
|
267
|
+
deadline = time.monotonic() + 3.0
|
|
268
|
+
while True:
|
|
269
|
+
try:
|
|
270
|
+
h = client.health()
|
|
271
|
+
if h.get("ok"):
|
|
272
|
+
break
|
|
273
|
+
except Exception:
|
|
274
|
+
if time.monotonic() >= deadline:
|
|
275
|
+
raise
|
|
276
|
+
time.sleep(0.05)
|
|
277
|
+
|
|
278
|
+
reg = client.register("doctor-agent", callback_url=cb_url, pid=os.getpid())
|
|
279
|
+
if not reg.get("ok"):
|
|
280
|
+
raise AssertionError(f"register failed: {reg}")
|
|
281
|
+
|
|
282
|
+
pong = client.ping("doctor-agent")
|
|
283
|
+
if pong.get("online") is not True:
|
|
284
|
+
raise AssertionError(f"expected online=True, got {pong}")
|
|
285
|
+
|
|
286
|
+
sent = client.send("doctor-sender", "doctor-agent", "doctor self-test")
|
|
287
|
+
msg_id = sent.get("id")
|
|
288
|
+
if not msg_id:
|
|
289
|
+
raise AssertionError(f"send returned no id: {sent}")
|
|
290
|
+
|
|
291
|
+
pulled = client.pull("doctor-agent")
|
|
292
|
+
if len(pulled) != 1 or pulled[0].get("id") != msg_id:
|
|
293
|
+
raise AssertionError(f"unexpected pull result: {pulled}")
|
|
294
|
+
|
|
295
|
+
ack = client.ack_read(msg_id, "doctor-agent")
|
|
296
|
+
if ack.get("status") != "read" or not ack.get("deleted"):
|
|
297
|
+
raise AssertionError(f"unexpected ack result: {ack}")
|
|
298
|
+
|
|
299
|
+
with sqlite3.connect(db_path) as conn:
|
|
300
|
+
row = conn.execute(
|
|
301
|
+
"SELECT COUNT(*) FROM messages WHERE id = ?",
|
|
302
|
+
(msg_id,),
|
|
303
|
+
).fetchone()
|
|
304
|
+
if not row or row[0] != 0:
|
|
305
|
+
raise AssertionError(f"message row {msg_id} was not hard-deleted")
|
|
306
|
+
|
|
307
|
+
rejected = False
|
|
308
|
+
try:
|
|
309
|
+
client.send("doctor-sender", "doctor-agent", "x" * (MAX_BODY + 1))
|
|
310
|
+
except ValidationError:
|
|
311
|
+
rejected = True
|
|
312
|
+
if not rejected:
|
|
313
|
+
raise AssertionError("1001-char body was not rejected")
|
|
314
|
+
finally:
|
|
315
|
+
try:
|
|
316
|
+
cb_srv.shutdown()
|
|
317
|
+
finally:
|
|
318
|
+
cb_srv.server_close()
|
|
319
|
+
_shutdown_node(node)
|
|
320
|
+
|
|
321
|
+
print("DOCTOR: PASS")
|
|
322
|
+
return 0
|
|
323
|
+
except Exception as exc:
|
|
324
|
+
print(f"DOCTOR: FAIL: {exc}", file=sys.stderr)
|
|
325
|
+
return 1
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
329
|
+
parser = argparse.ArgumentParser(
|
|
330
|
+
prog="jchat",
|
|
331
|
+
description="Decentralized signal & notification bus for coordinating AI agents.",
|
|
332
|
+
)
|
|
333
|
+
parser.add_argument("--version", action="version", version=f"jchat {VERSION}")
|
|
334
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
335
|
+
|
|
336
|
+
p = sub.add_parser("serve", help="run a jchat v0.2 node server")
|
|
337
|
+
p.add_argument("--port", type=int, default=None)
|
|
338
|
+
p.add_argument("--db", default=None, help="SQLite path (default env JCHAT_DB or ~/.jchat/jchat.db)")
|
|
339
|
+
p.add_argument("--verbose", action="store_true")
|
|
340
|
+
|
|
341
|
+
p = sub.add_parser("register", help="register or unregister a live agent")
|
|
342
|
+
p.add_argument("agent")
|
|
343
|
+
p.add_argument("--callback", default="")
|
|
344
|
+
p.add_argument("--pid", type=int, default=None)
|
|
345
|
+
p.add_argument("--task", default="")
|
|
346
|
+
p.add_argument("--ref", default="")
|
|
347
|
+
p.add_argument("--unregister", action="store_true")
|
|
348
|
+
p.add_argument("--url", default=None)
|
|
349
|
+
p.add_argument("--json", action="store_true")
|
|
350
|
+
|
|
351
|
+
p = sub.add_parser("send", help="send a signal or pointer message")
|
|
352
|
+
p.add_argument("recipient")
|
|
353
|
+
p.add_argument("body", nargs="?", default="", help="message body (<= 1000 chars) or '-' for stdin")
|
|
354
|
+
p.add_argument("--sender", default=None)
|
|
355
|
+
p.add_argument("--kind", default="notify", choices=KINDS)
|
|
356
|
+
p.add_argument("--ref", default="")
|
|
357
|
+
p.add_argument("--priority", default="normal", choices=PRIORITIES)
|
|
358
|
+
p.add_argument("--ttl-s", type=int, default=DEFAULT_TTL_S)
|
|
359
|
+
p.add_argument("--dedup-key", default="")
|
|
360
|
+
p.add_argument("--reply-to", default="")
|
|
361
|
+
p.add_argument("--require-online", action="store_true")
|
|
362
|
+
p.add_argument("--url", default=None)
|
|
363
|
+
p.add_argument("--json", action="store_true")
|
|
364
|
+
|
|
365
|
+
p = sub.add_parser("pull", help="pull queued messages for an agent")
|
|
366
|
+
p.add_argument("agent_pos", nargs="?", default=None, metavar="agent")
|
|
367
|
+
p.add_argument("--agent", default=None)
|
|
368
|
+
p.add_argument("--limit", type=int, default=20)
|
|
369
|
+
p.add_argument("--priority", default=None, choices=PRIORITIES)
|
|
370
|
+
p.add_argument("--lease-s", type=float, default=float(DEFAULT_LEASE_S))
|
|
371
|
+
p.add_argument("--ack", action="store_true", help="acknowledge read after printing")
|
|
372
|
+
p.add_argument("--raw", action="store_true", help="print plain summary without untrusted wrapper")
|
|
373
|
+
p.add_argument("--url", default=None)
|
|
374
|
+
p.add_argument("--json", action="store_true")
|
|
375
|
+
|
|
376
|
+
p = sub.add_parser("ack", help="acknowledge a leased message as read (hard-deletes row)")
|
|
377
|
+
p.add_argument("msg_id")
|
|
378
|
+
p.add_argument("agent_pos", nargs="?", default=None, metavar="agent")
|
|
379
|
+
p.add_argument("--agent", default=None)
|
|
380
|
+
p.add_argument("--url", default=None)
|
|
381
|
+
p.add_argument("--json", action="store_true")
|
|
382
|
+
|
|
383
|
+
p = sub.add_parser("status", help="show node status, queue depth, and agent state")
|
|
384
|
+
p.add_argument("--url", default=None)
|
|
385
|
+
p.add_argument("--json", action="store_true")
|
|
386
|
+
|
|
387
|
+
p = sub.add_parser("ping", help="probe live agent status")
|
|
388
|
+
p.add_argument("agent_pos", nargs="?", default=None, metavar="agent")
|
|
389
|
+
p.add_argument("--agent", default=None)
|
|
390
|
+
p.add_argument("--url", default=None)
|
|
391
|
+
p.add_argument("--json", action="store_true")
|
|
392
|
+
|
|
393
|
+
p = sub.add_parser("receipt", help="fetch a body-less delivery receipt")
|
|
394
|
+
p.add_argument("msg_id")
|
|
395
|
+
p.add_argument("--url", default=None)
|
|
396
|
+
p.add_argument("--json", action="store_true")
|
|
397
|
+
|
|
398
|
+
p = sub.add_parser("mcp", help="run stdio MCP server with live loopback callback")
|
|
399
|
+
p.add_argument("--agent", default=None)
|
|
400
|
+
p.add_argument("--url", default=None)
|
|
401
|
+
p.add_argument("--no-register", action="store_true")
|
|
402
|
+
|
|
403
|
+
p = sub.add_parser("hook", help="pull messages for a harness hook invocation")
|
|
404
|
+
p.add_argument("--agent", default=None)
|
|
405
|
+
p.add_argument("--url", default=None)
|
|
406
|
+
p.add_argument("--priority", default=None, choices=PRIORITIES)
|
|
407
|
+
p.add_argument("--no-ack", action="store_true")
|
|
408
|
+
p.add_argument("--strict", action="store_true")
|
|
409
|
+
|
|
410
|
+
p = sub.add_parser("install-hooks", help="install or remove harness hook/MCP wiring")
|
|
411
|
+
p.add_argument("harness", choices=SUPPORTED_HARNESSES)
|
|
412
|
+
p.add_argument("--agent", default=None)
|
|
413
|
+
p.add_argument("--url", default=f"http://127.0.0.1:{DEFAULT_PORT}")
|
|
414
|
+
p.add_argument("--remove", action="store_true")
|
|
415
|
+
p.add_argument("--settings-path", default=None)
|
|
416
|
+
|
|
417
|
+
sub.add_parser("doctor", help="run built-in loopback self-test")
|
|
418
|
+
return parser
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
_DISPATCH = {
|
|
422
|
+
"serve": _cmd_serve,
|
|
423
|
+
"register": _cmd_register,
|
|
424
|
+
"send": _cmd_send,
|
|
425
|
+
"pull": _cmd_pull,
|
|
426
|
+
"ack": _cmd_ack,
|
|
427
|
+
"status": _cmd_status,
|
|
428
|
+
"ping": _cmd_ping,
|
|
429
|
+
"receipt": _cmd_receipt,
|
|
430
|
+
"mcp": _cmd_mcp,
|
|
431
|
+
"hook": _cmd_hook,
|
|
432
|
+
"install-hooks": _cmd_install_hooks,
|
|
433
|
+
"doctor": _cmd_doctor,
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def main(argv: list[str] | None = None) -> int:
|
|
438
|
+
args = build_parser().parse_args(argv)
|
|
439
|
+
try:
|
|
440
|
+
return _DISPATCH[args.command](args)
|
|
441
|
+
except (JChatError, ValueError, OSError) as exc:
|
|
442
|
+
print(f"jchat: error: {exc}", file=sys.stderr)
|
|
443
|
+
return 1
|
|
444
|
+
except KeyboardInterrupt:
|
|
445
|
+
return 130
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
if __name__ == "__main__":
|
|
449
|
+
sys.exit(main())
|