jchat 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.
jchat-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HNXJ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
jchat-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: jchat
3
+ Version: 0.2.0
4
+ Summary: Decentralized signal & notification bus for coordinating AI agents (Python API, CLI, MCP).
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.15
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # jchat
12
+
13
+ Decentralized signal & notification bus for coordinating AI agents (Python API, CLI, MCP). Standard library only, SQLite-backed, zero runtime dependencies.
14
+
15
+ ## Install
16
+
17
+ Requires Python >= 3.15.
18
+
19
+ ```bash
20
+ pip install jchat
21
+ ```
22
+
23
+ Verify your environment with the built-in loopback self-test:
24
+
25
+ ```bash
26
+ jchat doctor
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ### CLI
32
+
33
+ ```bash
34
+ jchat serve # start node on 127.0.0.1:8765
35
+ jchat register agent-b --pid $$ # register live agent
36
+ jchat ping agent-b # live online handshake
37
+ jchat send agent-b "review ready" --sender agent-a --ref git:HEAD --kind verify
38
+ jchat pull agent-b # lease messages (30 s default)
39
+ jchat ack <msg-id> agent-b # hard-delete message on read
40
+ jchat status # node, agents, queue depth (no bodies)
41
+ ```
42
+
43
+ ### Python API
44
+
45
+ ```python
46
+ from jchat import Client, NetPolicy, Node, wrap_untrusted
47
+
48
+ policy = NetPolicy(netmode="localhost")
49
+ with Node(node_name="local", db_path="/tmp/jchat.db", net_policy=policy, port=0) as node:
50
+ client = Client(node.url)
51
+ client.send(sender="agent-a", recipient="agent-b", kind="notify", body="done", ref="git:HEAD")
52
+ for msg in client.pull("agent-b"):
53
+ print(wrap_untrusted(msg))
54
+ client.ack_read(msg["id"], "agent-b")
55
+ ```
56
+
57
+ ### MCP (stdio)
58
+
59
+ Run the MCP stdio server for agent harnesses:
60
+
61
+ ```bash
62
+ jchat mcp
63
+ ```
64
+
65
+ ## Envelope Contract (`<= 1000` chars)
66
+
67
+ `jchat` is a signal and pointer bus, not a chat history store:
68
+
69
+ - `body`: strictly `<= 1000` characters (`ValidationError` / `400 payload_too_large` if exceeded).
70
+ - `ref`: optional resource pointer (`<= 512` chars, no newlines or embedded tokens/secrets) prefixed with `git:`, `gh:`, `drive:`, `file:`, or `https:`.
71
+ - `kind`: `notify`, `verify`, `claim`, `ask`, or `status`.
72
+ - `priority`: `normal` or `urgent` (`urgent` delivered first).
73
+ - `ttl_s`: `1..604800` (default `86400`), plus optional `dedup_key` (idempotent push) and `reply_to`.
74
+
75
+ ## Message Lifecycle
76
+
77
+ 1. **`queued`**: validated envelope persisted in SQLite (`messages`) awaiting pull or peer `/ingest`.
78
+ 2. **`delivered`**: leased by `POST /pull` (`lease_s=30` default). If a consumer crashes before `ack`, the lease expires and the message returns to `queued`.
79
+ 3. **`read`**: `POST /ack` hard-deletes the row (`DELETE FROM messages WHERE id = ?`) and leaves only a 1 h in-memory body-less receipt (`id -> {status, reason, ts}`).
80
+ 4. **`failed`**: body-less receipt recorded on `ttl_expired`, `agent_offline` (when `require_online=True`), `node_unreachable`, or `node_out_of_mesh`.
81
+
82
+ ## Netmodes (`JCHAT_NETMODE`)
83
+
84
+ Wildcard binds (`0.0.0.0`, `::`, `*`) are always refused. Non-`localhost` modes authenticate every request with HMAC-SHA256 (`X-JChat-Ts`, `X-JChat-Nonce`, `X-JChat-Sig`) using a 30 s skew window and nonce replay cache.
85
+
86
+ | Mode | Requirements | Inbound / Outbound Rule |
87
+ |---|---|---|
88
+ | `localhost` (default) | None | Binds `127.0.0.1` only; remote peer pushes refused (`node_out_of_mesh`). |
89
+ | `allowlist` | `JCHAT_KEY`, `JCHAT_ALLOW_IPS` | Loopback + listed `JCHAT_ALLOW_IPS` only (DNS-resolved outbound). |
90
+ | `tailscale` | `JCHAT_KEY` | Loopback, `100.64.0.0/10`, or `fd7a:115c:a1e0::/48` only. |
91
+ | `cloud` | `JCHAT_KEY`, `https://` `JCHAT_CLOUD_URL` | Relays via configured HTTPS endpoint. |
92
+
93
+ Key environment variables: `JCHAT_NETMODE`, `JCHAT_KEY`, `JCHAT_ALLOW_IPS`, `JCHAT_CLOUD_URL`, `JCHAT_BIND`, `JCHAT_PEERS`, `JCHAT_NODE`, `JCHAT_DB`, `JCHAT_URL`.
94
+
95
+ ## Hooks & Diagnostics
96
+
97
+ - `jchat install-hooks <claude|agy|opencode|cursor>` installs turn-boundary hooks with automatic backups (`--remove` restores).
98
+ - `jchat doctor` runs an isolated loopback self-test covering send, pull, ack, and delete-on-read.
99
+
100
+ ## License
101
+
102
+ MIT. See [LICENSE](LICENSE).
jchat-0.2.0/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # jchat
2
+
3
+ Decentralized signal & notification bus for coordinating AI agents (Python API, CLI, MCP). Standard library only, SQLite-backed, zero runtime dependencies.
4
+
5
+ ## Install
6
+
7
+ Requires Python >= 3.15.
8
+
9
+ ```bash
10
+ pip install jchat
11
+ ```
12
+
13
+ Verify your environment with the built-in loopback self-test:
14
+
15
+ ```bash
16
+ jchat doctor
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ### CLI
22
+
23
+ ```bash
24
+ jchat serve # start node on 127.0.0.1:8765
25
+ jchat register agent-b --pid $$ # register live agent
26
+ jchat ping agent-b # live online handshake
27
+ jchat send agent-b "review ready" --sender agent-a --ref git:HEAD --kind verify
28
+ jchat pull agent-b # lease messages (30 s default)
29
+ jchat ack <msg-id> agent-b # hard-delete message on read
30
+ jchat status # node, agents, queue depth (no bodies)
31
+ ```
32
+
33
+ ### Python API
34
+
35
+ ```python
36
+ from jchat import Client, NetPolicy, Node, wrap_untrusted
37
+
38
+ policy = NetPolicy(netmode="localhost")
39
+ with Node(node_name="local", db_path="/tmp/jchat.db", net_policy=policy, port=0) as node:
40
+ client = Client(node.url)
41
+ client.send(sender="agent-a", recipient="agent-b", kind="notify", body="done", ref="git:HEAD")
42
+ for msg in client.pull("agent-b"):
43
+ print(wrap_untrusted(msg))
44
+ client.ack_read(msg["id"], "agent-b")
45
+ ```
46
+
47
+ ### MCP (stdio)
48
+
49
+ Run the MCP stdio server for agent harnesses:
50
+
51
+ ```bash
52
+ jchat mcp
53
+ ```
54
+
55
+ ## Envelope Contract (`<= 1000` chars)
56
+
57
+ `jchat` is a signal and pointer bus, not a chat history store:
58
+
59
+ - `body`: strictly `<= 1000` characters (`ValidationError` / `400 payload_too_large` if exceeded).
60
+ - `ref`: optional resource pointer (`<= 512` chars, no newlines or embedded tokens/secrets) prefixed with `git:`, `gh:`, `drive:`, `file:`, or `https:`.
61
+ - `kind`: `notify`, `verify`, `claim`, `ask`, or `status`.
62
+ - `priority`: `normal` or `urgent` (`urgent` delivered first).
63
+ - `ttl_s`: `1..604800` (default `86400`), plus optional `dedup_key` (idempotent push) and `reply_to`.
64
+
65
+ ## Message Lifecycle
66
+
67
+ 1. **`queued`**: validated envelope persisted in SQLite (`messages`) awaiting pull or peer `/ingest`.
68
+ 2. **`delivered`**: leased by `POST /pull` (`lease_s=30` default). If a consumer crashes before `ack`, the lease expires and the message returns to `queued`.
69
+ 3. **`read`**: `POST /ack` hard-deletes the row (`DELETE FROM messages WHERE id = ?`) and leaves only a 1 h in-memory body-less receipt (`id -> {status, reason, ts}`).
70
+ 4. **`failed`**: body-less receipt recorded on `ttl_expired`, `agent_offline` (when `require_online=True`), `node_unreachable`, or `node_out_of_mesh`.
71
+
72
+ ## Netmodes (`JCHAT_NETMODE`)
73
+
74
+ Wildcard binds (`0.0.0.0`, `::`, `*`) are always refused. Non-`localhost` modes authenticate every request with HMAC-SHA256 (`X-JChat-Ts`, `X-JChat-Nonce`, `X-JChat-Sig`) using a 30 s skew window and nonce replay cache.
75
+
76
+ | Mode | Requirements | Inbound / Outbound Rule |
77
+ |---|---|---|
78
+ | `localhost` (default) | None | Binds `127.0.0.1` only; remote peer pushes refused (`node_out_of_mesh`). |
79
+ | `allowlist` | `JCHAT_KEY`, `JCHAT_ALLOW_IPS` | Loopback + listed `JCHAT_ALLOW_IPS` only (DNS-resolved outbound). |
80
+ | `tailscale` | `JCHAT_KEY` | Loopback, `100.64.0.0/10`, or `fd7a:115c:a1e0::/48` only. |
81
+ | `cloud` | `JCHAT_KEY`, `https://` `JCHAT_CLOUD_URL` | Relays via configured HTTPS endpoint. |
82
+
83
+ Key environment variables: `JCHAT_NETMODE`, `JCHAT_KEY`, `JCHAT_ALLOW_IPS`, `JCHAT_CLOUD_URL`, `JCHAT_BIND`, `JCHAT_PEERS`, `JCHAT_NODE`, `JCHAT_DB`, `JCHAT_URL`.
84
+
85
+ ## Hooks & Diagnostics
86
+
87
+ - `jchat install-hooks <claude|agy|opencode|cursor>` installs turn-boundary hooks with automatic backups (`--remove` restores).
88
+ - `jchat doctor` runs an isolated loopback self-test covering send, pull, ack, and delete-on-read.
89
+
90
+ ## License
91
+
92
+ MIT. See [LICENSE](LICENSE).
@@ -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}")
@@ -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)