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/client.py ADDED
@@ -0,0 +1,218 @@
1
+ """Stdlib-only HTTP client for jchat v0.2 with optional HMAC-SHA256 signing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import json
8
+ import os
9
+ import time
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+ import uuid
14
+ from typing import Any
15
+
16
+ from .schema import (
17
+ AuthError,
18
+ DEFAULT_LEASE_S,
19
+ DEFAULT_PORT,
20
+ DEFAULT_TTL_S,
21
+ DeliveryError,
22
+ Envelope,
23
+ JChatError,
24
+ PRIORITIES,
25
+ ValidationError,
26
+ validate_envelope,
27
+ validate_name,
28
+ validate_ref,
29
+ )
30
+
31
+
32
+ def _extract_error(exc: urllib.error.HTTPError) -> str:
33
+ try:
34
+ raw = exc.read().decode("utf-8", errors="replace")
35
+ data = json.loads(raw)
36
+ if isinstance(data, dict):
37
+ return str(data.get("error") or data.get("reason") or data.get("detail") or exc.reason)
38
+ except Exception:
39
+ pass
40
+ return str(exc.reason)
41
+
42
+
43
+ class Client:
44
+ """HTTP client for a jchat v0.2 node."""
45
+
46
+ def __init__(
47
+ self,
48
+ url: str | None = None,
49
+ key: str | None = None,
50
+ timeout: float = 10.0,
51
+ ) -> None:
52
+ resolved_url = url if url is not None else os.environ.get("JCHAT_URL")
53
+ if not resolved_url:
54
+ resolved_url = f"http://127.0.0.1:{DEFAULT_PORT}"
55
+ self.url = resolved_url.rstrip("/")
56
+ resolved_key = key if key is not None else os.environ.get("JCHAT_KEY")
57
+ self.key: str | None = resolved_key or None
58
+ self.timeout = float(timeout)
59
+
60
+ def _sign_headers(self, body: bytes, method: str = "", path: str = "") -> dict[str, str]:
61
+ if not self.key:
62
+ return {}
63
+ ts = str(int(time.time()))
64
+ nonce = uuid.uuid4().hex
65
+ if method or path:
66
+ msg = f"{ts}.{nonce}.{method.upper()}.{path}.".encode("utf-8") + body
67
+ else:
68
+ msg = f"{ts}.{nonce}.".encode("utf-8") + body
69
+ sig = hmac.new(self.key.encode("utf-8"), msg, hashlib.sha256).hexdigest()
70
+ return {
71
+ "X-JChat-Ts": ts,
72
+ "X-JChat-Nonce": nonce,
73
+ "X-JChat-Sig": sig,
74
+ }
75
+
76
+ def _request(
77
+ self,
78
+ method: str,
79
+ path: str,
80
+ payload: dict[str, Any] | None = None,
81
+ ) -> dict[str, Any]:
82
+ target = f"{self.url}{path}"
83
+ headers: dict[str, str] = {"Accept": "application/json"}
84
+ data: bytes | None = None
85
+ if payload is not None:
86
+ data = json.dumps(payload).encode("utf-8")
87
+ headers["Content-Type"] = "application/json"
88
+ body_bytes = data if data is not None else b""
89
+ clean_path = urllib.parse.urlsplit(path).path
90
+ headers.update(self._sign_headers(body_bytes, method=method, path=clean_path))
91
+
92
+ req = urllib.request.Request(target, data=data, headers=headers, method=method)
93
+ try:
94
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
95
+ raw = resp.read()
96
+ except urllib.error.HTTPError as exc:
97
+ detail = _extract_error(exc)
98
+ if exc.code in (401, 403):
99
+ raise AuthError(f"HTTP {exc.code}: {detail}") from None
100
+ if exc.code == 400:
101
+ raise ValidationError(f"HTTP {exc.code}: {detail}") from None
102
+ if exc.code in (422, 502, 503, 504):
103
+ raise DeliveryError(f"HTTP {exc.code}: {detail}") from None
104
+ raise JChatError(f"HTTP {exc.code}: {detail}") from None
105
+ except OSError as exc:
106
+ reason = getattr(exc, "reason", exc)
107
+ raise JChatError(f"cannot reach jchat at {target}: {reason}") from None
108
+
109
+ try:
110
+ parsed = json.loads(raw.decode("utf-8"))
111
+ except ValueError:
112
+ raise JChatError("server sent a non-JSON reply") from None
113
+ if not isinstance(parsed, dict):
114
+ raise JChatError("server sent a non-object JSON reply")
115
+ return parsed
116
+
117
+ def health(self) -> dict[str, Any]:
118
+ return self._request("GET", "/health")
119
+
120
+ def register(
121
+ self,
122
+ agent: str,
123
+ callback_url: str = "",
124
+ pid: int | None = None,
125
+ task: str = "",
126
+ ref: str = "",
127
+ unregister: bool = False,
128
+ ) -> dict[str, Any]:
129
+ validate_name(agent, "agent")
130
+ if ref:
131
+ validate_ref(ref)
132
+ payload: dict[str, Any] = {
133
+ "agent": agent,
134
+ "callback_url": callback_url,
135
+ "task": task,
136
+ "ref": ref,
137
+ "unregister": bool(unregister),
138
+ }
139
+ if pid is not None:
140
+ payload["pid"] = int(pid)
141
+ return self._request("POST", "/register", payload)
142
+
143
+ def ping(self, agent: str) -> dict[str, Any]:
144
+ validate_name(agent, "agent")
145
+ return self._request("POST", "/ping", {"agent": agent})
146
+
147
+ def send(
148
+ self,
149
+ sender: str,
150
+ recipient: str,
151
+ body: str = "",
152
+ *,
153
+ kind: str = "notify",
154
+ ref: str = "",
155
+ priority: str = "normal",
156
+ ttl_s: int = DEFAULT_TTL_S,
157
+ dedup_key: str = "",
158
+ reply_to: str = "",
159
+ require_online: bool = False,
160
+ ) -> dict[str, Any]:
161
+ env = validate_envelope(
162
+ Envelope(
163
+ sender=sender,
164
+ recipient=recipient,
165
+ kind=kind,
166
+ body=body,
167
+ ref=ref,
168
+ priority=priority,
169
+ ttl_s=ttl_s,
170
+ dedup_key=dedup_key,
171
+ reply_to=reply_to,
172
+ )
173
+ )
174
+ payload = env.to_dict()
175
+ payload["require_online"] = bool(require_online)
176
+ return self._request("POST", "/send", payload)
177
+
178
+ def pull(
179
+ self,
180
+ agent: str,
181
+ limit: int = 20,
182
+ priority: str | None = None,
183
+ lease_s: float = DEFAULT_LEASE_S,
184
+ ) -> list[dict[str, Any]]:
185
+ validate_name(agent, "agent")
186
+ if limit <= 0:
187
+ raise ValidationError("limit must be positive")
188
+ if lease_s <= 0:
189
+ raise ValidationError("lease_s must be positive")
190
+ if priority is not None and priority not in PRIORITIES:
191
+ raise ValidationError(f"invalid priority {priority!r}; expected {PRIORITIES}")
192
+ payload: dict[str, Any] = {
193
+ "agent": agent,
194
+ "limit": int(limit),
195
+ "lease_s": float(lease_s),
196
+ }
197
+ if priority is not None:
198
+ payload["priority"] = priority
199
+ res = self._request("POST", "/pull", payload)
200
+ msgs = res.get("messages", [])
201
+ if not isinstance(msgs, list):
202
+ raise JChatError("server returned invalid messages list")
203
+ return msgs
204
+
205
+ def ack_read(self, msg_id: str, agent: str) -> dict[str, Any]:
206
+ if not isinstance(msg_id, str) or not msg_id:
207
+ raise ValidationError("msg_id must be a non-empty string")
208
+ validate_name(agent, "agent")
209
+ return self._request("POST", "/ack", {"id": msg_id, "agent": agent, "status": "read"})
210
+
211
+ def receipt(self, msg_id: str) -> dict[str, Any]:
212
+ if not isinstance(msg_id, str) or not msg_id:
213
+ raise ValidationError("msg_id must be a non-empty string")
214
+ quoted = urllib.parse.quote(msg_id, safe="")
215
+ return self._request("GET", f"/receipt/{quoted}")
216
+
217
+ def status(self) -> dict[str, Any]:
218
+ return self._request("GET", "/status")
jchat/hooks.py ADDED
@@ -0,0 +1,220 @@
1
+ """Hook installer and turn-boundary pull runner for claude, agy, opencode, and cursor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from .client import Client
14
+ from .schema import DEFAULT_PORT, JChatError, ValidationError, validate_name, wrap_untrusted
15
+
16
+ SUPPORTED_HARNESSES = ("claude", "agy", "opencode", "cursor")
17
+ HOOK_EVENTS = ("SessionStart", "UserPromptSubmit", "PreToolUse")
18
+
19
+
20
+ def default_settings_path(harness: str) -> Path:
21
+ """Return the default config file path for a supported agent harness."""
22
+ h = harness.lower()
23
+ home = Path.home()
24
+ if h == "claude":
25
+ return home / ".claude" / "settings.json"
26
+ if h == "agy":
27
+ return home / ".gemini" / "antigravity" / "mcp_config.json"
28
+ if h == "opencode":
29
+ return home / ".config" / "opencode" / "opencode.json"
30
+ if h == "cursor":
31
+ return home / ".cursor" / "mcp.json"
32
+ raise ValidationError(f"unsupported harness {harness!r}; expected {SUPPORTED_HARNESSES}")
33
+
34
+
35
+ def _backup_file(path: Path) -> Path:
36
+ ts = str(int(time.time()))
37
+ candidate = path.with_name(f"{path.name}.bak-{ts}")
38
+ idx = 1
39
+ while candidate.exists():
40
+ candidate = path.with_name(f"{path.name}.bak-{ts}-{idx}")
41
+ idx += 1
42
+ candidate.write_bytes(path.read_bytes())
43
+ return candidate
44
+
45
+
46
+ def _is_jchat_hook_entry(entry: Any) -> bool:
47
+ if not isinstance(entry, dict):
48
+ return False
49
+ cmd = entry.get("command")
50
+ if isinstance(cmd, str) and "jchat hook" in cmd:
51
+ return True
52
+ inner = entry.get("hooks")
53
+ if isinstance(inner, list):
54
+ for h in inner:
55
+ if isinstance(h, dict) and "jchat hook" in str(h.get("command", "")):
56
+ return True
57
+ return False
58
+
59
+
60
+ def _atomic_write_json(path: Path, data: dict[str, Any]) -> None:
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ content = json.dumps(data, indent=2) + "\n"
63
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=path.name + ".", suffix=".tmp")
64
+ try:
65
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
66
+ f.write(content)
67
+ os.replace(tmp, path)
68
+ except Exception:
69
+ try:
70
+ os.unlink(tmp)
71
+ except OSError:
72
+ pass
73
+ raise
74
+
75
+
76
+ def install_hooks(
77
+ harness: str,
78
+ agent_id: str,
79
+ url: str = f"http://127.0.0.1:{DEFAULT_PORT}",
80
+ remove: bool = False,
81
+ settings_path: str | Path | None = None,
82
+ ) -> Path:
83
+ """Idempotently install (or remove) jchat hook and MCP wiring for a harness."""
84
+ h = harness.lower()
85
+ if h not in SUPPORTED_HARNESSES:
86
+ raise ValidationError(f"unsupported harness {harness!r}; expected {SUPPORTED_HARNESSES}")
87
+ validate_name(agent_id, "agent_id")
88
+
89
+ target = Path(settings_path) if settings_path is not None else default_settings_path(h)
90
+ if remove and not target.exists():
91
+ return target
92
+
93
+ data: dict[str, Any] = {}
94
+ if target.exists():
95
+ raw = target.read_text(encoding="utf-8")
96
+ if raw.strip():
97
+ try:
98
+ loaded = json.loads(raw)
99
+ except ValueError as exc:
100
+ raise ValidationError(f"existing config is not valid JSON ({target}): {exc}") from None
101
+ if not isinstance(loaded, dict):
102
+ raise ValidationError(f"existing config must be a JSON object ({target})")
103
+ data = loaded
104
+ _backup_file(target)
105
+
106
+ default_url = f"http://127.0.0.1:{DEFAULT_PORT}"
107
+ clean_url = (url or default_url).rstrip("/")
108
+ if not clean_url.startswith(("http://", "https://")) or any(c.isspace() for c in clean_url):
109
+ raise ValidationError(f"invalid hook url: {url!r}")
110
+ import shlex
111
+ q_agent = shlex.quote(agent_id)
112
+ q_url = shlex.quote(clean_url)
113
+ hook_cmd = (
114
+ f"jchat hook --agent {q_agent}"
115
+ if clean_url == default_url
116
+ else f"jchat hook --agent {q_agent} --url {q_url}"
117
+ )
118
+
119
+ hooks_obj = data.get("hooks")
120
+ if hooks_obj is None:
121
+ hooks_obj = {}
122
+ if not isinstance(hooks_obj, dict):
123
+ raise ValidationError(f"'hooks' field in {target} must be a JSON object")
124
+
125
+ for event in HOOK_EVENTS:
126
+ existing_list = hooks_obj.get(event)
127
+ if existing_list is None:
128
+ filtered: list[Any] = []
129
+ elif isinstance(existing_list, list):
130
+ filtered = [item for item in existing_list if not _is_jchat_hook_entry(item)]
131
+ else:
132
+ raise ValidationError(f"'hooks.{event}' in {target} must be a JSON list")
133
+
134
+ if not remove:
135
+ filtered.append(
136
+ {
137
+ "matcher": "",
138
+ "hooks": [{"type": "command", "command": hook_cmd}],
139
+ }
140
+ )
141
+ hooks_obj[event] = filtered
142
+ else:
143
+ if filtered:
144
+ hooks_obj[event] = filtered
145
+ else:
146
+ hooks_obj.pop(event, None)
147
+
148
+ if hooks_obj:
149
+ data["hooks"] = hooks_obj
150
+ else:
151
+ data.pop("hooks", None)
152
+
153
+ if h in ("agy", "cursor"):
154
+ servers = data.get("mcpServers")
155
+ if servers is None:
156
+ servers = {}
157
+ if not isinstance(servers, dict):
158
+ raise ValidationError(f"'mcpServers' field in {target} must be a JSON object")
159
+ if remove:
160
+ servers.pop("jchat", None)
161
+ if servers:
162
+ data["mcpServers"] = servers
163
+ else:
164
+ data.pop("mcpServers", None)
165
+ else:
166
+ servers["jchat"] = {
167
+ "command": "jchat",
168
+ "args": ["mcp", "--agent", agent_id, "--url", clean_url],
169
+ }
170
+ data["mcpServers"] = servers
171
+ elif h == "opencode":
172
+ mcp_obj = data.get("mcp")
173
+ if mcp_obj is None:
174
+ mcp_obj = {}
175
+ if not isinstance(mcp_obj, dict):
176
+ raise ValidationError(f"'mcp' field in {target} must be a JSON object")
177
+ if remove:
178
+ mcp_obj.pop("jchat", None)
179
+ if mcp_obj:
180
+ data["mcp"] = mcp_obj
181
+ else:
182
+ data.pop("mcp", None)
183
+ else:
184
+ mcp_obj["jchat"] = {
185
+ "type": "local",
186
+ "command": ["jchat", "mcp", "--agent", agent_id, "--url", clean_url],
187
+ }
188
+ data["mcp"] = mcp_obj
189
+
190
+ _atomic_write_json(target, data)
191
+ return target
192
+
193
+
194
+ def run_hook_pull(
195
+ agent_id: str,
196
+ url: str | None = None,
197
+ priority: str | None = None,
198
+ auto_ack: bool = True,
199
+ strict: bool = False,
200
+ ) -> int:
201
+ """Pull messages for a hook invocation, print wrapped untrusted data, then ack."""
202
+ try:
203
+ client = Client(url=url)
204
+ msgs = client.pull(agent_id, priority=priority)
205
+ if not msgs:
206
+ return 0
207
+ output = "\n\n".join(wrap_untrusted(m) for m in msgs) + "\n"
208
+ sys.stdout.write(output)
209
+ sys.stdout.flush()
210
+ if auto_ack:
211
+ for m in msgs:
212
+ mid = m.get("id")
213
+ if mid:
214
+ client.ack_read(str(mid), agent_id)
215
+ return 0
216
+ except (JChatError, OSError, Exception) as exc:
217
+ msg = str(exc).splitlines()[0] if str(exc) else ""
218
+ detail = f"{type(exc).__name__}: {msg}" if msg else type(exc).__name__
219
+ sys.stderr.write(f"jchat hook: {detail}\n")
220
+ return 1 if strict else 0