agent-notifiers 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.
- agent_notifier/__init__.py +3 -0
- agent_notifier/__main__.py +3 -0
- agent_notifier/adapter.py +69 -0
- agent_notifier/agents.py +102 -0
- agent_notifier/autostart.py +165 -0
- agent_notifier/bridge.py +1384 -0
- agent_notifier/channels.py +213 -0
- agent_notifier/cli.py +308 -0
- agent_notifier/codex_models.py +64 -0
- agent_notifier/codex_workspace.py +23 -0
- agent_notifier/companion.py +371 -0
- agent_notifier/config.py +68 -0
- agent_notifier/core.py +89 -0
- agent_notifier/device.py +134 -0
- agent_notifier/hooks.py +133 -0
- agent_notifier/inbox.py +63 -0
- agent_notifier/local_models.py +72 -0
- agent_notifier/recovery.py +127 -0
- agent_notifier/redact.py +42 -0
- agent_notifier/runtime.py +184 -0
- agent_notifier/server.py +89 -0
- agent_notifier/state.py +64 -0
- agent_notifier/windows_process.py +24 -0
- agent_notifiers-0.2.0.dist-info/METADATA +25 -0
- agent_notifiers-0.2.0.dist-info/RECORD +28 -0
- agent_notifiers-0.2.0.dist-info/WHEEL +5 -0
- agent_notifiers-0.2.0.dist-info/entry_points.txt +4 -0
- agent_notifiers-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Channels: Telegram, ntfy, Gmail (SMTP), WhatsApp (CallMeBot).
|
|
2
|
+
|
|
3
|
+
Inbound (user -> Claude) is supported for Telegram and ntfy only.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import smtplib
|
|
8
|
+
import ssl
|
|
9
|
+
import time
|
|
10
|
+
from email.message import EmailMessage
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from .config import Settings
|
|
15
|
+
|
|
16
|
+
TIMEOUT = 15.0
|
|
17
|
+
NTFY_PRIORITY = {"low": 2, "normal": 3, "high": 4, "urgent": 5}
|
|
18
|
+
NTFY_TAGS = {"low": "robot", "normal": "robot", "high": "warning", "urgent": "rotating_light"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ChannelError(Exception):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _check(resp: httpx.Response) -> None:
|
|
26
|
+
if resp.status_code >= 400:
|
|
27
|
+
raise ChannelError(f"HTTP {resp.status_code}: {resp.text[:200]}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Channel:
|
|
31
|
+
name = ""
|
|
32
|
+
inbound = False
|
|
33
|
+
needs = "" # human hint for status output
|
|
34
|
+
|
|
35
|
+
def __init__(self, settings: Settings):
|
|
36
|
+
self.s = settings
|
|
37
|
+
|
|
38
|
+
def configured(self) -> bool:
|
|
39
|
+
raise NotImplementedError
|
|
40
|
+
|
|
41
|
+
def send(self, title: str, message: str, priority: str = "normal") -> None:
|
|
42
|
+
raise NotImplementedError
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Telegram(Channel):
|
|
46
|
+
name = "telegram"
|
|
47
|
+
inbound = True
|
|
48
|
+
needs = "TG_TOKEN, TG_CHAT_ID"
|
|
49
|
+
|
|
50
|
+
def configured(self) -> bool:
|
|
51
|
+
return bool(self.s.get("TG_TOKEN") and self.s.get("TG_CHAT_ID"))
|
|
52
|
+
|
|
53
|
+
def _url(self, method: str) -> str:
|
|
54
|
+
return f"https://api.telegram.org/bot{self.s.get('TG_TOKEN')}/{method}"
|
|
55
|
+
|
|
56
|
+
def send(self, title: str, message: str, priority: str = "normal") -> None:
|
|
57
|
+
text = f"{title}\n\n{message}" if title else message
|
|
58
|
+
resp = httpx.post(
|
|
59
|
+
self._url("sendMessage"),
|
|
60
|
+
json={
|
|
61
|
+
"chat_id": self.s.get("TG_CHAT_ID"),
|
|
62
|
+
"text": text[:4000],
|
|
63
|
+
"disable_notification": priority == "low",
|
|
64
|
+
},
|
|
65
|
+
timeout=TIMEOUT,
|
|
66
|
+
)
|
|
67
|
+
_check(resp)
|
|
68
|
+
|
|
69
|
+
def poll(self, offset: int | None, wait: int = 0) -> tuple[list[dict], int | None]:
|
|
70
|
+
params: dict = {"timeout": wait, "allowed_updates": '["message"]'}
|
|
71
|
+
if offset:
|
|
72
|
+
params["offset"] = offset
|
|
73
|
+
resp = httpx.get(self._url("getUpdates"), params=params, timeout=wait + TIMEOUT)
|
|
74
|
+
_check(resp)
|
|
75
|
+
chat_id = self.s.get("TG_CHAT_ID")
|
|
76
|
+
msgs: list[dict] = []
|
|
77
|
+
nxt = offset
|
|
78
|
+
for upd in resp.json().get("result", []):
|
|
79
|
+
nxt = max(nxt or 0, upd["update_id"] + 1)
|
|
80
|
+
msg = upd.get("message") or {}
|
|
81
|
+
# Security: only accept messages from YOUR chat. Replies become instructions.
|
|
82
|
+
if str(msg.get("chat", {}).get("id")) != chat_id:
|
|
83
|
+
continue
|
|
84
|
+
if msg.get("text"):
|
|
85
|
+
msgs.append({"channel": "telegram", "text": msg["text"], "ts": msg.get("date", 0)})
|
|
86
|
+
return msgs, nxt
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def discover_telegram_chats(token: str) -> list[tuple[str, str]]:
|
|
90
|
+
resp = httpx.get(f"https://api.telegram.org/bot{token}/getUpdates", timeout=TIMEOUT)
|
|
91
|
+
_check(resp)
|
|
92
|
+
seen: dict[str, str] = {}
|
|
93
|
+
for upd in resp.json().get("result", []):
|
|
94
|
+
chat = (upd.get("message") or {}).get("chat") or {}
|
|
95
|
+
if "id" in chat:
|
|
96
|
+
name = chat.get("username") or chat.get("first_name") or chat.get("title") or ""
|
|
97
|
+
seen[str(chat["id"])] = name
|
|
98
|
+
return list(seen.items())
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Ntfy(Channel):
|
|
102
|
+
name = "ntfy"
|
|
103
|
+
inbound = True
|
|
104
|
+
needs = "NTFY_TOPIC"
|
|
105
|
+
|
|
106
|
+
def configured(self) -> bool:
|
|
107
|
+
return bool(self.s.get("NTFY_TOPIC"))
|
|
108
|
+
|
|
109
|
+
def _server(self) -> str:
|
|
110
|
+
return self.s.get("NTFY_SERVER", "https://ntfy.sh").rstrip("/")
|
|
111
|
+
|
|
112
|
+
def _headers(self) -> dict[str, str]:
|
|
113
|
+
token = self.s.get("NTFY_TOKEN")
|
|
114
|
+
return {"Authorization": f"Bearer {token}"} if token else {}
|
|
115
|
+
|
|
116
|
+
def send(self, title: str, message: str, priority: str = "normal") -> None:
|
|
117
|
+
resp = httpx.post(
|
|
118
|
+
self._server(),
|
|
119
|
+
json={
|
|
120
|
+
"topic": self.s.get("NTFY_TOPIC"),
|
|
121
|
+
"title": title,
|
|
122
|
+
"message": message[:3900],
|
|
123
|
+
"priority": NTFY_PRIORITY.get(priority, 3),
|
|
124
|
+
"tags": [NTFY_TAGS.get(priority, "robot")],
|
|
125
|
+
},
|
|
126
|
+
headers=self._headers(),
|
|
127
|
+
timeout=TIMEOUT,
|
|
128
|
+
)
|
|
129
|
+
_check(resp)
|
|
130
|
+
|
|
131
|
+
def poll(self, since: str | None) -> tuple[list[dict], str | None]:
|
|
132
|
+
inbox = self.s.get("NTFY_INBOX_TOPIC")
|
|
133
|
+
if not inbox:
|
|
134
|
+
return [], since
|
|
135
|
+
# First run: start from "now" so old backlog is not replayed.
|
|
136
|
+
cursor = since or str(int(time.time()))
|
|
137
|
+
resp = httpx.get(
|
|
138
|
+
f"{self._server()}/{inbox}/json",
|
|
139
|
+
params={"poll": "1", "since": cursor},
|
|
140
|
+
headers=self._headers(),
|
|
141
|
+
timeout=TIMEOUT,
|
|
142
|
+
)
|
|
143
|
+
_check(resp)
|
|
144
|
+
import json
|
|
145
|
+
|
|
146
|
+
msgs: list[dict] = []
|
|
147
|
+
last = since
|
|
148
|
+
for line in resp.text.splitlines():
|
|
149
|
+
try:
|
|
150
|
+
ev = json.loads(line)
|
|
151
|
+
except ValueError:
|
|
152
|
+
continue
|
|
153
|
+
if ev.get("event") != "message":
|
|
154
|
+
continue
|
|
155
|
+
last = ev.get("id", last)
|
|
156
|
+
msgs.append({"channel": "ntfy", "text": ev.get("message", ""), "ts": ev.get("time", 0)})
|
|
157
|
+
return msgs, last or cursor
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Gmail(Channel):
|
|
161
|
+
name = "gmail"
|
|
162
|
+
needs = "GMAIL_USER, GMAIL_APP_PASSWORD"
|
|
163
|
+
|
|
164
|
+
def configured(self) -> bool:
|
|
165
|
+
return bool(self.s.get("GMAIL_USER") and self.s.get("GMAIL_APP_PASSWORD"))
|
|
166
|
+
|
|
167
|
+
def send(self, title: str, message: str, priority: str = "normal") -> None:
|
|
168
|
+
user = self.s.get("GMAIL_USER")
|
|
169
|
+
msg = EmailMessage()
|
|
170
|
+
msg["From"] = user
|
|
171
|
+
msg["To"] = self.s.get("GMAIL_TO") or user
|
|
172
|
+
prefix = {"high": "[!] ", "urgent": "[!!] "}.get(priority, "")
|
|
173
|
+
msg["Subject"] = f"{prefix}[Claude] {title}"[:200]
|
|
174
|
+
if priority in ("high", "urgent"):
|
|
175
|
+
msg["X-Priority"] = "1"
|
|
176
|
+
msg.set_content(message)
|
|
177
|
+
password = self.s.get("GMAIL_APP_PASSWORD").replace(" ", "")
|
|
178
|
+
try:
|
|
179
|
+
with smtplib.SMTP_SSL(
|
|
180
|
+
"smtp.gmail.com", 465, context=ssl.create_default_context(), timeout=TIMEOUT
|
|
181
|
+
) as smtp:
|
|
182
|
+
smtp.login(user, password)
|
|
183
|
+
smtp.send_message(msg)
|
|
184
|
+
except smtplib.SMTPException as exc:
|
|
185
|
+
raise ChannelError(f"SMTP error: {exc.__class__.__name__}") from None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class WhatsApp(Channel):
|
|
189
|
+
name = "whatsapp"
|
|
190
|
+
needs = "CALLMEBOT_PHONE, CALLMEBOT_APIKEY"
|
|
191
|
+
|
|
192
|
+
def configured(self) -> bool:
|
|
193
|
+
return bool(self.s.get("CALLMEBOT_PHONE") and self.s.get("CALLMEBOT_APIKEY"))
|
|
194
|
+
|
|
195
|
+
def send(self, title: str, message: str, priority: str = "normal") -> None:
|
|
196
|
+
text = f"{title}\n{message}" if title else message
|
|
197
|
+
resp = httpx.get(
|
|
198
|
+
"https://api.callmebot.com/whatsapp.php",
|
|
199
|
+
params={
|
|
200
|
+
"phone": self.s.get("CALLMEBOT_PHONE"),
|
|
201
|
+
"text": text[:1000],
|
|
202
|
+
"apikey": self.s.get("CALLMEBOT_APIKEY"),
|
|
203
|
+
},
|
|
204
|
+
timeout=TIMEOUT,
|
|
205
|
+
)
|
|
206
|
+
_check(resp)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
ALL_CHANNELS = (Telegram, Ntfy, Gmail, WhatsApp)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def build(settings: Settings) -> dict[str, Channel]:
|
|
213
|
+
return {cls.name: cls(settings) for cls in ALL_CHANNELS}
|
agent_notifier/cli.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""agent-notifier CLI: send, test, status, telegram-id, inbox, hook, install-hooks."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import channels as ch
|
|
11
|
+
from .config import HOME, PACKAGE_ROOT, Settings
|
|
12
|
+
from .core import notify
|
|
13
|
+
|
|
14
|
+
HOOK_MARK = "agent_notifier hook"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _hook_command() -> str:
|
|
18
|
+
return f'"{sys.executable}" -m agent_notifier hook'
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def cmd_status(_: argparse.Namespace) -> int:
|
|
22
|
+
s = Settings()
|
|
23
|
+
print(f"default channels: {', '.join(s.default_channels)} min seconds: {s.min_seconds}")
|
|
24
|
+
for name, c in ch.build(s).items():
|
|
25
|
+
state = "OK " if c.configured() else "missing"
|
|
26
|
+
way = "two-way" if c.inbound else "send-only"
|
|
27
|
+
print(f" {name:<9} {state} {way:<9} needs: {c.needs}")
|
|
28
|
+
return 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def cmd_send(a: argparse.Namespace) -> int:
|
|
32
|
+
res = notify(a.message, a.title, a.priority, a.channel or None)
|
|
33
|
+
print(json.dumps(res, indent=2))
|
|
34
|
+
return 0 if res.get("sent") else 1
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cmd_test(_: argparse.Namespace) -> int:
|
|
38
|
+
res = notify("agent-notifier test: if you see this, the channel works.", "Test", "high")
|
|
39
|
+
print(json.dumps(res, indent=2))
|
|
40
|
+
return 0 if res.get("sent") else 1
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def cmd_bridge_id(_: argparse.Namespace) -> int:
|
|
44
|
+
from .bridge import cmd_bridge_id as _cmd
|
|
45
|
+
|
|
46
|
+
return _cmd(_)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cmd_device_pair(a: argparse.Namespace) -> int:
|
|
50
|
+
from .device import cmd_device_pair as _cmd
|
|
51
|
+
|
|
52
|
+
return _cmd(a)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cmd_device_status(a: argparse.Namespace) -> int:
|
|
56
|
+
from .device import cmd_device_status as _cmd
|
|
57
|
+
|
|
58
|
+
return _cmd(a)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def cmd_device_unpair(a: argparse.Namespace) -> int:
|
|
62
|
+
from .device import cmd_device_unpair as _cmd
|
|
63
|
+
|
|
64
|
+
return _cmd(a)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def cmd_companion_start(a: argparse.Namespace) -> int:
|
|
68
|
+
from .companion import cmd_companion_start as _cmd
|
|
69
|
+
|
|
70
|
+
return _cmd(a)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cmd_companion_status(a: argparse.Namespace) -> int:
|
|
74
|
+
from .companion import cmd_companion_status as _cmd
|
|
75
|
+
|
|
76
|
+
return _cmd(a)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def cmd_companion_stop(a: argparse.Namespace) -> int:
|
|
80
|
+
from .companion import cmd_companion_stop as _cmd
|
|
81
|
+
|
|
82
|
+
return _cmd(a)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cmd_autostart_install(a: argparse.Namespace) -> int:
|
|
86
|
+
from .autostart import install
|
|
87
|
+
|
|
88
|
+
return install()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def cmd_autostart_uninstall(a: argparse.Namespace) -> int:
|
|
92
|
+
from .autostart import uninstall
|
|
93
|
+
|
|
94
|
+
return uninstall()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_autostart_status(a: argparse.Namespace) -> int:
|
|
98
|
+
from .autostart import status
|
|
99
|
+
|
|
100
|
+
state = status()
|
|
101
|
+
print(json.dumps(state, indent=2))
|
|
102
|
+
return 0
|
|
103
|
+
|
|
104
|
+
def cmd_install_bridge_service(_: argparse.Namespace) -> int:
|
|
105
|
+
from .bridge import cmd_install_bridge_service as _cmd
|
|
106
|
+
|
|
107
|
+
return _cmd(_)
|
|
108
|
+
|
|
109
|
+
def cmd_telegram_id(_: argparse.Namespace) -> int:
|
|
110
|
+
token = Settings().get("TG_TOKEN")
|
|
111
|
+
if not token:
|
|
112
|
+
print("Set TG_TOKEN first (from @BotFather), then message your bot once.")
|
|
113
|
+
return 1
|
|
114
|
+
chats = ch.discover_telegram_chats(token)
|
|
115
|
+
if not chats:
|
|
116
|
+
print("No messages found. Send any message to your bot in Telegram, then run again.")
|
|
117
|
+
return 1
|
|
118
|
+
for cid, name in chats:
|
|
119
|
+
print(f"TG_CHAT_ID={cid} ({name})")
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_inbox(a: argparse.Namespace) -> int:
|
|
124
|
+
from .inbox import poll_inbox
|
|
125
|
+
|
|
126
|
+
msgs = poll_inbox(wait=a.wait, consume=not a.peek)
|
|
127
|
+
for m in msgs:
|
|
128
|
+
print(f"[{m['channel']}] {m['text']}")
|
|
129
|
+
if not msgs:
|
|
130
|
+
print("(no new messages)")
|
|
131
|
+
return 0
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def cmd_hook(_: argparse.Namespace) -> int:
|
|
135
|
+
from .hooks import run_from_stdin
|
|
136
|
+
|
|
137
|
+
return run_from_stdin()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def cmd_listen(a: argparse.Namespace) -> int:
|
|
141
|
+
from .bridge import cmd_listen as _cmd
|
|
142
|
+
|
|
143
|
+
return _cmd(a)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def cmd_run(a: argparse.Namespace) -> int:
|
|
147
|
+
"""Run any command, then notify when it exits. Works with every agent, script or build."""
|
|
148
|
+
import subprocess
|
|
149
|
+
import time
|
|
150
|
+
|
|
151
|
+
from .hooks import _fmt_duration
|
|
152
|
+
|
|
153
|
+
cmd = list(a.command)
|
|
154
|
+
if cmd and cmd[0] == "--":
|
|
155
|
+
cmd = cmd[1:]
|
|
156
|
+
if not cmd:
|
|
157
|
+
print("usage: agent-notifier run [--title T] [--min-seconds N] -- <command ...>", file=sys.stderr)
|
|
158
|
+
return 2
|
|
159
|
+
start = time.time()
|
|
160
|
+
try:
|
|
161
|
+
rc = subprocess.call(cmd)
|
|
162
|
+
except FileNotFoundError:
|
|
163
|
+
print(f"agent-notifier: command not found: {cmd[0]}", file=sys.stderr)
|
|
164
|
+
return 127
|
|
165
|
+
except KeyboardInterrupt:
|
|
166
|
+
rc = 130
|
|
167
|
+
elapsed = time.time() - start
|
|
168
|
+
if rc == 0 and elapsed < a.min_seconds:
|
|
169
|
+
return rc
|
|
170
|
+
# Only the program name and folder are sent, never its arguments (they may contain API keys).
|
|
171
|
+
label = a.title or Path(cmd[0]).name
|
|
172
|
+
where = Path.cwd().name
|
|
173
|
+
took = _fmt_duration(elapsed)
|
|
174
|
+
if rc == 0:
|
|
175
|
+
notify(f"Finished OK in {took} ({where})", title=f"{label} finished", priority="normal")
|
|
176
|
+
else:
|
|
177
|
+
notify(f"Exited with code {rc} after {took} ({where})", title=f"{label} FAILED", priority="high")
|
|
178
|
+
return rc
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def cmd_codex_notify(a: argparse.Namespace) -> int:
|
|
182
|
+
from .hooks import handle_codex
|
|
183
|
+
|
|
184
|
+
try:
|
|
185
|
+
raw = a.payload if a.payload else sys.stdin.read()
|
|
186
|
+
handle_codex(json.loads(raw) if raw and raw.strip() else {})
|
|
187
|
+
except Exception: # noqa: BLE001 - a hook must never break the agent
|
|
188
|
+
pass
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def cmd_init(_: argparse.Namespace) -> int:
|
|
193
|
+
HOME.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
target = HOME / ".env"
|
|
195
|
+
if target.exists():
|
|
196
|
+
print(f"already exists: {target}")
|
|
197
|
+
return 0
|
|
198
|
+
src = PACKAGE_ROOT / ".env.example"
|
|
199
|
+
if not src.exists():
|
|
200
|
+
src = PACKAGE_ROOT / "_env.example"
|
|
201
|
+
shutil.copy(src, target)
|
|
202
|
+
try:
|
|
203
|
+
target.chmod(0o600)
|
|
204
|
+
except OSError:
|
|
205
|
+
pass
|
|
206
|
+
print(f"created {target} - fill it in, then run: agent-notifier status")
|
|
207
|
+
return 0
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def cmd_install_hooks(a: argparse.Namespace) -> int:
|
|
211
|
+
path = Path.home() / ".claude" / "settings.json" if a.scope == "user" else Path.cwd() / ".claude" / "settings.json"
|
|
212
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
213
|
+
try:
|
|
214
|
+
data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
215
|
+
except ValueError:
|
|
216
|
+
print(f"{path} is not valid JSON - fix it first.")
|
|
217
|
+
return 1
|
|
218
|
+
hooks = data.setdefault("hooks", {})
|
|
219
|
+
for event in ("UserPromptSubmit", "Stop", "Notification"):
|
|
220
|
+
groups = hooks.setdefault(event, [])
|
|
221
|
+
for g in groups: # idempotent: drop any previous agent-notifier entry
|
|
222
|
+
g["hooks"] = [h for h in g.get("hooks", []) if HOOK_MARK not in h.get("command", "")]
|
|
223
|
+
groups[:] = [g for g in groups if g.get("hooks")]
|
|
224
|
+
groups.append({"hooks": [{"type": "command", "command": _hook_command(), "timeout": 30}]})
|
|
225
|
+
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
|
226
|
+
print(f"hooks installed in {path}")
|
|
227
|
+
print("\nAdd the MCP server too (so Claude can choose when/where to ping you):")
|
|
228
|
+
print(f' claude mcp add agent-notifier -- "{sys.executable}" -m agent_notifier.server')
|
|
229
|
+
return 0
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def main(argv: list[str] | None = None) -> int:
|
|
233
|
+
p = argparse.ArgumentParser(prog="agent-notifier", description=__doc__)
|
|
234
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
235
|
+
sub.add_parser("status").set_defaults(fn=cmd_status)
|
|
236
|
+
sub.add_parser("test").set_defaults(fn=cmd_test)
|
|
237
|
+
sub.add_parser("telegram-id").set_defaults(fn=cmd_telegram_id)
|
|
238
|
+
sub.add_parser("hook").set_defaults(fn=cmd_hook)
|
|
239
|
+
sub.add_parser("init").set_defaults(fn=cmd_init)
|
|
240
|
+
s = sub.add_parser("send")
|
|
241
|
+
s.add_argument("message")
|
|
242
|
+
s.add_argument("--title", default="Claude")
|
|
243
|
+
s.add_argument("--priority", default="normal", choices=["low", "normal", "high", "urgent"])
|
|
244
|
+
s.add_argument("--channel", action="append", help="repeatable; default = routing rules")
|
|
245
|
+
s.set_defaults(fn=cmd_send)
|
|
246
|
+
i = sub.add_parser("inbox")
|
|
247
|
+
i.add_argument("--wait", type=int, default=0)
|
|
248
|
+
i.add_argument("--peek", action="store_true")
|
|
249
|
+
i.set_defaults(fn=cmd_inbox)
|
|
250
|
+
r = sub.add_parser("run", help="run a command and notify when it exits")
|
|
251
|
+
r.add_argument("--title", default="")
|
|
252
|
+
r.add_argument("--min-seconds", type=int, default=0, help="skip the ping if it finished faster (success only)")
|
|
253
|
+
r.add_argument("command", nargs=argparse.REMAINDER)
|
|
254
|
+
r.set_defaults(fn=cmd_run)
|
|
255
|
+
cx = sub.add_parser("codex-notify", help="Codex CLI notify hook (JSON argument)")
|
|
256
|
+
cx.add_argument("payload", nargs="?", default="")
|
|
257
|
+
cx.set_defaults(fn=cmd_codex_notify)
|
|
258
|
+
h = sub.add_parser("install-hooks")
|
|
259
|
+
h.add_argument("--scope", choices=["user", "project"], default="user")
|
|
260
|
+
h.set_defaults(fn=cmd_install_hooks)
|
|
261
|
+
|
|
262
|
+
bi = sub.add_parser("bridge-id", help="print the chat id that messaged the bridge bot")
|
|
263
|
+
bi.set_defaults(fn=cmd_bridge_id)
|
|
264
|
+
|
|
265
|
+
ibs = sub.add_parser("install-bridge-service", help="print (do not run) service install steps")
|
|
266
|
+
ibs.set_defaults(fn=cmd_install_bridge_service)
|
|
267
|
+
|
|
268
|
+
dev = sub.add_parser("device", help="manage paired devices")
|
|
269
|
+
dev_sub = dev.add_subparsers(dest="device_cmd", required=True)
|
|
270
|
+
dp = dev_sub.add_parser("pair", help="pair this computer with your account")
|
|
271
|
+
dp.add_argument("--name", default=None)
|
|
272
|
+
dp.set_defaults(fn=cmd_device_pair)
|
|
273
|
+
ds = dev_sub.add_parser("status", help="show pairing status")
|
|
274
|
+
ds.set_defaults(fn=cmd_device_status)
|
|
275
|
+
du = dev_sub.add_parser("unpair", help="remove pairing")
|
|
276
|
+
du.set_defaults(fn=cmd_device_unpair)
|
|
277
|
+
|
|
278
|
+
comp = sub.add_parser("companion", help="connect this computer to the hosted service")
|
|
279
|
+
comp_sub = comp.add_subparsers(dest="companion_cmd", required=True)
|
|
280
|
+
cps = comp_sub.add_parser("start", help="connect and send heartbeats")
|
|
281
|
+
cps.add_argument("--supervise", action="store_true",
|
|
282
|
+
help="restart automatically after a crash (opt-in at login via install-autostart)")
|
|
283
|
+
cps.set_defaults(fn=cmd_companion_start)
|
|
284
|
+
cpa = comp_sub.add_parser("install-autostart", help="opt in: start the companion at Windows sign-in")
|
|
285
|
+
cpa.set_defaults(fn=cmd_autostart_install)
|
|
286
|
+
cpau = comp_sub.add_parser("uninstall-autostart", help="remove the login launcher")
|
|
287
|
+
cpau.set_defaults(fn=cmd_autostart_uninstall)
|
|
288
|
+
cpas = comp_sub.add_parser("autostart-status", help="show auto-start configuration")
|
|
289
|
+
cpas.set_defaults(fn=cmd_autostart_status)
|
|
290
|
+
cpst = comp_sub.add_parser("status", help="show companion status")
|
|
291
|
+
cpst.set_defaults(fn=cmd_companion_status)
|
|
292
|
+
cpstp = comp_sub.add_parser("stop", help="stop companion (run in its terminal)")
|
|
293
|
+
cpstp.set_defaults(fn=cmd_companion_stop)
|
|
294
|
+
|
|
295
|
+
li = sub.add_parser("listen", help="Telegram wake-up bridge: message -> headless agent -> reply")
|
|
296
|
+
li.add_argument("--agent", choices=["claude", "codex", "opencode", "custom"], default=None)
|
|
297
|
+
li.add_argument("--workdir", default=None)
|
|
298
|
+
li.add_argument("--permissions", choices=["readonly", "edit", "full"], default=None)
|
|
299
|
+
li.add_argument("--timeout", type=int, default=None)
|
|
300
|
+
li.add_argument("--dry-run", action="store_true")
|
|
301
|
+
li.add_argument("--i-understand-the-risk", action="store_true")
|
|
302
|
+
li.set_defaults(fn=cmd_listen)
|
|
303
|
+
args = p.parse_args(argv)
|
|
304
|
+
return args.fn(args)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
if __name__ == "__main__":
|
|
308
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Local Codex CLI model catalog discovery. No API key or cloud provider calls.
|
|
2
|
+
|
|
3
|
+
The companion executes the already-installed user's Codex binary in a bounded
|
|
4
|
+
subprocess and reports only model identifiers and display names. Experimental
|
|
5
|
+
Codex CLI versions lacking 'debug models' report no selectable models.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import subprocess
|
|
11
|
+
from .agents import _resolve
|
|
12
|
+
from .windows_process import hidden_kwargs
|
|
13
|
+
|
|
14
|
+
MODEL_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,119}\Z")
|
|
15
|
+
MAX_OUTPUT = 700_000
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_catalog(raw: str) -> list[dict]:
|
|
19
|
+
if len(raw) > MAX_OUTPUT:
|
|
20
|
+
return []
|
|
21
|
+
try:
|
|
22
|
+
data = json.loads(raw)
|
|
23
|
+
except (TypeError, ValueError):
|
|
24
|
+
return []
|
|
25
|
+
if isinstance(data, list):
|
|
26
|
+
items = data
|
|
27
|
+
elif isinstance(data, dict):
|
|
28
|
+
items = data.get("models", data.get("data", []))
|
|
29
|
+
if isinstance(items, dict):
|
|
30
|
+
items = items.get("models", [])
|
|
31
|
+
else:
|
|
32
|
+
return []
|
|
33
|
+
if not isinstance(items, list):
|
|
34
|
+
return []
|
|
35
|
+
result, seen = [], set()
|
|
36
|
+
for item in items[:1500]:
|
|
37
|
+
if not isinstance(item, dict):
|
|
38
|
+
continue
|
|
39
|
+
if item.get("visibility") in ("hide", "hidden", "disabled") or item.get("is_supported") is False:
|
|
40
|
+
continue
|
|
41
|
+
ident = item.get("slug") or item.get("id")
|
|
42
|
+
if not isinstance(ident, str) or not MODEL_ID.fullmatch(ident) or ident in seen:
|
|
43
|
+
continue
|
|
44
|
+
label = item.get("display_name") or item.get("name") or ident
|
|
45
|
+
if not isinstance(label, str) or len(label) > 140 or any(ord(c) < 32 for c in label):
|
|
46
|
+
label = ident
|
|
47
|
+
seen.add(ident)
|
|
48
|
+
result.append({"id": ident, "name": label})
|
|
49
|
+
return result[:150]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def discover() -> list[dict]:
|
|
53
|
+
exe = _resolve("codex")
|
|
54
|
+
if not exe:
|
|
55
|
+
return []
|
|
56
|
+
try:
|
|
57
|
+
done = subprocess.run([exe, "debug", "models"], capture_output=True,
|
|
58
|
+
text=True, timeout=18, errors="replace",
|
|
59
|
+
stdin=subprocess.DEVNULL, **hidden_kwargs())
|
|
60
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
61
|
+
return []
|
|
62
|
+
if done.returncode != 0:
|
|
63
|
+
return []
|
|
64
|
+
return parse_catalog(done.stdout)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Codex requires an explicit Git workspace unless the owner opts out locally.
|
|
2
|
+
|
|
3
|
+
Never follow a remote instruction to bypass the git repository trust check.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from .windows_process import hidden_kwargs
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def is_git_worktree(path: Path) -> bool:
|
|
13
|
+
git = shutil.which("git")
|
|
14
|
+
if not git:
|
|
15
|
+
return False
|
|
16
|
+
try:
|
|
17
|
+
proc = subprocess.run([git, "-C", str(path), "rev-parse", "--is-inside-work-tree"],
|
|
18
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
19
|
+
stderr=subprocess.DEVNULL, text=True, timeout=5,
|
|
20
|
+
**hidden_kwargs())
|
|
21
|
+
return proc.returncode == 0 and proc.stdout.strip() == "true"
|
|
22
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
23
|
+
return False
|