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,69 @@
|
|
|
1
|
+
"""Capability-aware adapters over existing bridge implementations.
|
|
2
|
+
|
|
3
|
+
No subprocess is launched by creating an adapter. The existing bridge remains
|
|
4
|
+
responsible for agent execution and its local permission checks.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
# These describe capabilities exposed by the CURRENT local bridge, not claims
|
|
12
|
+
# about every version of the underlying third-party agent CLI.
|
|
13
|
+
CAPABILITIES: dict[str, dict[str, bool]] = {
|
|
14
|
+
"claude": {
|
|
15
|
+
"notify": True, "prompt": True, "resume": True, "cancel": True,
|
|
16
|
+
"list_sessions": False, "approval": False, "cloud_remote": False,
|
|
17
|
+
},
|
|
18
|
+
"codex": {
|
|
19
|
+
"notify": True, "prompt": True, "resume": False, "cancel": True,
|
|
20
|
+
"list_sessions": False, "approval": False, "cloud_remote": False,
|
|
21
|
+
},
|
|
22
|
+
"opencode": {
|
|
23
|
+
"notify": True, "prompt": True, "resume": True, "cancel": True,
|
|
24
|
+
"list_sessions": False, "approval": False, "cloud_remote": False,
|
|
25
|
+
},
|
|
26
|
+
"custom": {
|
|
27
|
+
"notify": False, "prompt": True, "resume": False, "cancel": True,
|
|
28
|
+
"list_sessions": False, "approval": False, "cloud_remote": False,
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def capabilities_for(name: str) -> dict[str, bool]:
|
|
34
|
+
"""Return a defensive copy; never guess unverified support."""
|
|
35
|
+
return dict(CAPABILITIES.get(name, CAPABILITIES["custom"]))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class AgentAdapter:
|
|
40
|
+
"""Uniform façade for existing bridge implementations.
|
|
41
|
+
|
|
42
|
+
The adapter wraps the locally authorized bridge agent and does not
|
|
43
|
+
authenticate remote requests. That belongs to a future cloud protocol.
|
|
44
|
+
"""
|
|
45
|
+
name: str
|
|
46
|
+
implementation: Any
|
|
47
|
+
|
|
48
|
+
def supports(self, operation: str) -> bool:
|
|
49
|
+
return bool(capabilities_for(self.name).get(operation, False))
|
|
50
|
+
|
|
51
|
+
def build_command(self, message: str, session_id: str | None, permissions: str) -> list[str]:
|
|
52
|
+
if not self.supports("prompt"):
|
|
53
|
+
raise ValueError("agent does not support prompts")
|
|
54
|
+
if permissions not in ("readonly", "edit", "full"):
|
|
55
|
+
raise ValueError("unsupported permission level")
|
|
56
|
+
if session_id and not self.supports("resume"):
|
|
57
|
+
raise ValueError("session resume is unsupported")
|
|
58
|
+
return self.implementation.build(message, session_id, permissions)
|
|
59
|
+
|
|
60
|
+
def parse_output(self, stdout: str, stderr: str, returncode: int):
|
|
61
|
+
return self.implementation.parse(stdout, stderr, returncode)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def from_local_bridge(name: str, template: str | None = None, settings=None) -> AgentAdapter | None:
|
|
65
|
+
"""Reuse the mature bridge's parser and command builder, without a rewrite."""
|
|
66
|
+
from .bridge import make_agent
|
|
67
|
+
|
|
68
|
+
impl = make_agent(name, template, settings)
|
|
69
|
+
return AgentAdapter(name, impl) if impl else None
|
agent_notifier/agents.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Agent detection and registry for the bridge."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .windows_process import hidden_kwargs
|
|
13
|
+
from .adapter import capabilities_for
|
|
14
|
+
|
|
15
|
+
KNOWN = ("claude", "codex", "opencode")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _resolve(name: str) -> str | None:
|
|
19
|
+
path = shutil.which(name)
|
|
20
|
+
if path:
|
|
21
|
+
return path
|
|
22
|
+
for suffix in ("", ".exe", ".cmd", ".bat"):
|
|
23
|
+
p = shutil.which(name + suffix)
|
|
24
|
+
if p:
|
|
25
|
+
return p
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _version(exe: str) -> str:
|
|
30
|
+
try:
|
|
31
|
+
r = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=8, errors="replace", **hidden_kwargs())
|
|
32
|
+
out = (r.stdout or r.stderr or "").strip().splitlines()
|
|
33
|
+
return out[0][:60] if out else ""
|
|
34
|
+
except Exception:
|
|
35
|
+
return ""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _running_processes(name: str) -> int:
|
|
39
|
+
"""Best-effort count of processes whose name matches. Never reads cmdline/env."""
|
|
40
|
+
count = 0
|
|
41
|
+
try:
|
|
42
|
+
if os.name == "nt":
|
|
43
|
+
r = subprocess.run(["tasklist", "/FO", "CSV", "/NH"], capture_output=True, text=True, timeout=10, **hidden_kwargs())
|
|
44
|
+
needle = name.lower()
|
|
45
|
+
for line in r.stdout.splitlines():
|
|
46
|
+
# CSV first field is "name"
|
|
47
|
+
if line.startswith('"'):
|
|
48
|
+
first = line.split('","', 1)[0].strip('"').lower()
|
|
49
|
+
if needle in first:
|
|
50
|
+
count += 1
|
|
51
|
+
else:
|
|
52
|
+
r = subprocess.run(["ps", "-A", "-o", "comm="], capture_output=True, text=True, timeout=10, **hidden_kwargs())
|
|
53
|
+
needle = name.lower()
|
|
54
|
+
for line in r.stdout.splitlines():
|
|
55
|
+
if needle in line.lower():
|
|
56
|
+
count += 1
|
|
57
|
+
except Exception:
|
|
58
|
+
pass
|
|
59
|
+
return count
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def detect(settings) -> list[dict[str, Any]]:
|
|
63
|
+
custom = {}
|
|
64
|
+
raw = settings.get("BRIDGE_AGENTS_CUSTOM", "")
|
|
65
|
+
for pair in raw.split(","):
|
|
66
|
+
if "=" in pair:
|
|
67
|
+
n, cmd = pair.split("=", 1)
|
|
68
|
+
custom[n.strip()] = cmd.strip()
|
|
69
|
+
agents = []
|
|
70
|
+
for name in list(KNOWN) + list(custom):
|
|
71
|
+
exe = _resolve(name) if name in KNOWN else _resolve(custom[name].split()[0]) if custom.get(name) else None
|
|
72
|
+
# for custom, resolve first token
|
|
73
|
+
if name.startswith("custom:") or name in custom:
|
|
74
|
+
cname = name if name in custom else name.split(":", 1)[1]
|
|
75
|
+
cmd = custom.get(cname, "")
|
|
76
|
+
first = cmd.split()[0] if cmd else ""
|
|
77
|
+
exe = _resolve(first) if first else None
|
|
78
|
+
display = cname
|
|
79
|
+
else:
|
|
80
|
+
display = name
|
|
81
|
+
installed = bool(exe)
|
|
82
|
+
ver = _version(exe) if installed else ""
|
|
83
|
+
folder = Path(exe).parent.name if exe else ""
|
|
84
|
+
others = _running_processes(display) if installed else 0
|
|
85
|
+
agents.append({
|
|
86
|
+
"name": display,
|
|
87
|
+
"installed": installed,
|
|
88
|
+
"version": ver,
|
|
89
|
+
"folder": folder,
|
|
90
|
+
"others": others,
|
|
91
|
+
"custom": display in custom or name.startswith("custom:"),
|
|
92
|
+
"cmd": custom.get(display, ""),
|
|
93
|
+
"capabilities": capabilities_for(name if name in KNOWN else "custom"),
|
|
94
|
+
})
|
|
95
|
+
return agents
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def find_executable(name: str, custom_cmd: str = "") -> str | None:
|
|
99
|
+
if custom_cmd:
|
|
100
|
+
first = custom_cmd.split()[0]
|
|
101
|
+
return _resolve(first)
|
|
102
|
+
return _resolve(name)
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Opt-in companion auto-start and crash supervision (Windows-first, no admin).
|
|
2
|
+
|
|
3
|
+
The companion is an outbound client: it can start installed agent CLIs on this
|
|
4
|
+
computer, but it can never power a sleeping or switched-off machine on. This
|
|
5
|
+
module only manages a per-user login launcher and supervision loop.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from .windows_process import hidden_kwargs
|
|
16
|
+
|
|
17
|
+
APP_DIR_NAME = "agent-notifier"
|
|
18
|
+
LAUNCHER_NAME = "agent-notifier-companion.vbs"
|
|
19
|
+
LEGACY_LAUNCHER_NAME = "agent-notifier-companion.cmd"
|
|
20
|
+
TASK_NAME = "AgentNotifierCompanion"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _startup_dir() -> Path:
|
|
24
|
+
"""Per-user Startup folder (or an explicit override for tests)."""
|
|
25
|
+
override = os.environ.get("AN_AUTOSTART_DIR")
|
|
26
|
+
if override:
|
|
27
|
+
return Path(override)
|
|
28
|
+
appdata = os.environ.get("APPDATA")
|
|
29
|
+
if appdata:
|
|
30
|
+
return Path(appdata) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"
|
|
31
|
+
# Non-Windows: XDG autostart is a different mechanism; keep an explicit dir.
|
|
32
|
+
return Path.home() / ".config" / "autostart"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _log_dir() -> Path:
|
|
36
|
+
base = os.environ.get("LOCALAPPDATA")
|
|
37
|
+
root = Path(base) if base else Path.home()
|
|
38
|
+
return root / APP_DIR_NAME / "logs"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _launcher_path() -> Path:
|
|
42
|
+
return _startup_dir() / LAUNCHER_NAME
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _python_windowless() -> str:
|
|
46
|
+
"""Prefer pythonw.exe so login startup does not open a console window."""
|
|
47
|
+
exe = Path(sys.executable)
|
|
48
|
+
candidate = exe.with_name("pythonw.exe")
|
|
49
|
+
return str(candidate if candidate.exists() else exe)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def build_launcher_command() -> str:
|
|
53
|
+
"""Fixed command line: no shell metacharacters, no server-selected binaries."""
|
|
54
|
+
return (
|
|
55
|
+
'"' + _python_windowless() + '" -m agent_notifier companion start --supervise'
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def install() -> int:
|
|
60
|
+
if os.name != "nt":
|
|
61
|
+
print("Auto-start is implemented for Windows. On Linux/macOS use your service manager.")
|
|
62
|
+
return 1
|
|
63
|
+
path = _launcher_path()
|
|
64
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
logs = _log_dir()
|
|
66
|
+
logs.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
log_file = logs / "companion.log"
|
|
68
|
+
# Launch pythonw.exe DIRECTLY. Do not involve cmd.exe / redirection:
|
|
69
|
+
# even a hidden WScript launch of cmd.exe can briefly create a console
|
|
70
|
+
# on some Windows installations, including at login.
|
|
71
|
+
if Path(_python_windowless()).name.lower() != "pythonw.exe":
|
|
72
|
+
print("Cannot install silent startup: this Python has no pythonw.exe.")
|
|
73
|
+
return 1
|
|
74
|
+
vb_command = '"' + build_launcher_command().replace('"', '""') + '"'
|
|
75
|
+
script = ("' Opt-in Agent Notifier hidden login launcher\r\n"
|
|
76
|
+
"Set shell = CreateObject(\"WScript.Shell\")\r\n"
|
|
77
|
+
"shell.CurrentDirectory = shell.ExpandEnvironmentStrings(\"%USERPROFILE%\")\r\n"
|
|
78
|
+
f"shell.Run {vb_command}, 0, False\r\n")
|
|
79
|
+
path.write_text(script, encoding="utf-8", newline="")
|
|
80
|
+
legacy = _startup_dir() / LEGACY_LAUNCHER_NAME
|
|
81
|
+
try:
|
|
82
|
+
legacy.unlink(missing_ok=True)
|
|
83
|
+
except OSError:
|
|
84
|
+
print("WARNING: legacy CMD startup launcher could not be removed; check Startup folder.")
|
|
85
|
+
print(f"Auto-start installed: {path}")
|
|
86
|
+
print("It runs at your next Windows sign-in and only while you are logged in.")
|
|
87
|
+
print("Disable anytime with: agent-notifier companion uninstall-autostart")
|
|
88
|
+
return 0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def uninstall() -> int:
|
|
92
|
+
path = _launcher_path()
|
|
93
|
+
removed = False
|
|
94
|
+
for target in (path, _startup_dir() / (LAUNCHER_NAME + ".disabled"),
|
|
95
|
+
_startup_dir() / LEGACY_LAUNCHER_NAME,
|
|
96
|
+
_startup_dir() / (LEGACY_LAUNCHER_NAME + ".disabled")):
|
|
97
|
+
try:
|
|
98
|
+
if target.exists():
|
|
99
|
+
target.unlink()
|
|
100
|
+
removed = True
|
|
101
|
+
except OSError as exc:
|
|
102
|
+
print(f"Could not remove {target}: {exc}")
|
|
103
|
+
return 1
|
|
104
|
+
print("Auto-start removed." if removed else "Auto-start was not installed.")
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def task_state() -> str:
|
|
109
|
+
"""Read-only look at a legacy scheduled task, if one exists."""
|
|
110
|
+
if os.name != "nt" or not shutil.which("schtasks"):
|
|
111
|
+
return "n/a"
|
|
112
|
+
try:
|
|
113
|
+
result = subprocess.run(
|
|
114
|
+
["schtasks", "/Query", "/TN", TASK_NAME, "/FO", "LIST"],
|
|
115
|
+
capture_output=True, text=True, timeout=10, **hidden_kwargs(),
|
|
116
|
+
)
|
|
117
|
+
except (OSError, subprocess.SubprocessError):
|
|
118
|
+
return "unknown"
|
|
119
|
+
return "present" if result.returncode == 0 else "absent"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def status() -> dict:
|
|
123
|
+
path = _launcher_path()
|
|
124
|
+
legacy = _startup_dir() / LEGACY_LAUNCHER_NAME
|
|
125
|
+
actual = path if path.exists() else legacy if legacy.exists() else path
|
|
126
|
+
return {
|
|
127
|
+
"platform": os.name,
|
|
128
|
+
"installed": actual.exists(),
|
|
129
|
+
"path": str(actual),
|
|
130
|
+
"command": build_launcher_command(),
|
|
131
|
+
"log": str(_log_dir() / "companion.log"),
|
|
132
|
+
"task": task_state(),
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def supervise(run_once, sleep=time.sleep) -> int:
|
|
137
|
+
"""Restart the companion loop after crashes until the user stops it.
|
|
138
|
+
|
|
139
|
+
Returns 0 on a clean operator interrupt, otherwise keeps retrying with a
|
|
140
|
+
bounded backoff. A revoked device (exit code 1 with a terminal message)
|
|
141
|
+
is not retried forever: after repeated immediate failures we stop.
|
|
142
|
+
"""
|
|
143
|
+
delay = 3
|
|
144
|
+
immediate_failures = 0
|
|
145
|
+
while True:
|
|
146
|
+
started = time.monotonic()
|
|
147
|
+
code = run_once()
|
|
148
|
+
lasted = time.monotonic() - started
|
|
149
|
+
if code == 0:
|
|
150
|
+
return 0
|
|
151
|
+
if lasted < 10:
|
|
152
|
+
immediate_failures += 1
|
|
153
|
+
else:
|
|
154
|
+
immediate_failures = 0
|
|
155
|
+
if immediate_failures >= 5:
|
|
156
|
+
print("Companion keeps failing immediately; stopping supervision. "
|
|
157
|
+
"Check pairing and logs, then run `agent-notifier companion start`.")
|
|
158
|
+
return code
|
|
159
|
+
print(f"Companion exited (code {code}); restarting in {delay}s...")
|
|
160
|
+
try:
|
|
161
|
+
sleep(delay)
|
|
162
|
+
except KeyboardInterrupt:
|
|
163
|
+
print("Supervision stopped.")
|
|
164
|
+
return 0
|
|
165
|
+
delay = min(delay * 2, 60)
|