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
agent_notifier/hooks.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Claude Code hook handler. One command handles every event: `agent-notifier hook`.
|
|
2
|
+
|
|
3
|
+
Events (JSON on stdin, `hook_event_name`):
|
|
4
|
+
UserPromptSubmit -> remember when the run started
|
|
5
|
+
Stop -> "finished" ping (skipped if the run was shorter than NOTIFY_MIN_SECONDS)
|
|
6
|
+
Notification -> "Claude needs you" ping (permission prompt / idle), high priority
|
|
7
|
+
|
|
8
|
+
Hooks must never break Claude: every path swallows errors and exits 0 silently.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from . import state
|
|
19
|
+
from .config import Settings
|
|
20
|
+
from .core import notify
|
|
21
|
+
|
|
22
|
+
DEBOUNCE_SECONDS = 30
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _fmt_duration(seconds: float) -> str:
|
|
26
|
+
seconds = int(seconds)
|
|
27
|
+
if seconds < 60:
|
|
28
|
+
return f"{seconds}s"
|
|
29
|
+
minutes, sec = divmod(seconds, 60)
|
|
30
|
+
if minutes < 60:
|
|
31
|
+
return f"{minutes}m {sec:02d}s"
|
|
32
|
+
hours, minutes = divmod(minutes, 60)
|
|
33
|
+
return f"{hours}h {minutes:02d}m"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _last_assistant_text(transcript_path: str | None, limit: int = 400) -> str:
|
|
37
|
+
"""Best-effort: tail of the transcript JSONL -> last assistant text block."""
|
|
38
|
+
if not transcript_path:
|
|
39
|
+
return ""
|
|
40
|
+
try:
|
|
41
|
+
path = Path(transcript_path).expanduser()
|
|
42
|
+
with open(path, "rb") as fh:
|
|
43
|
+
fh.seek(0, 2)
|
|
44
|
+
size = fh.tell()
|
|
45
|
+
fh.seek(max(0, size - 200_000))
|
|
46
|
+
lines = fh.read().decode("utf-8", errors="ignore").splitlines()
|
|
47
|
+
for line in reversed(lines):
|
|
48
|
+
try:
|
|
49
|
+
entry = json.loads(line)
|
|
50
|
+
except ValueError:
|
|
51
|
+
continue
|
|
52
|
+
msg = entry.get("message") if isinstance(entry, dict) else None
|
|
53
|
+
if not msg or msg.get("role") != "assistant":
|
|
54
|
+
continue
|
|
55
|
+
content = msg.get("content")
|
|
56
|
+
if isinstance(content, str):
|
|
57
|
+
text = content
|
|
58
|
+
else:
|
|
59
|
+
text = " ".join(
|
|
60
|
+
b.get("text", "") for b in content or [] if isinstance(b, dict) and b.get("type") == "text"
|
|
61
|
+
)
|
|
62
|
+
text = " ".join(text.split())
|
|
63
|
+
if text:
|
|
64
|
+
return text[:limit] + ("..." if len(text) > limit else "")
|
|
65
|
+
except OSError:
|
|
66
|
+
pass
|
|
67
|
+
return ""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _debounced(key: str) -> bool:
|
|
71
|
+
st = state.load()
|
|
72
|
+
now = time.time()
|
|
73
|
+
if now - st.get(key, 0) < DEBOUNCE_SECONDS:
|
|
74
|
+
return True
|
|
75
|
+
st[key] = now
|
|
76
|
+
state.save(st)
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def handle(payload: dict, settings: Settings | None = None) -> None:
|
|
81
|
+
settings = settings or Settings()
|
|
82
|
+
event = payload.get("hook_event_name", "")
|
|
83
|
+
session = str(payload.get("session_id", "default"))
|
|
84
|
+
project = Path(payload.get("cwd") or ".").resolve().name or "project"
|
|
85
|
+
|
|
86
|
+
if event == "UserPromptSubmit":
|
|
87
|
+
state.mark_run_start(session)
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
if event == "Stop":
|
|
91
|
+
if payload.get("stop_hook_active"):
|
|
92
|
+
return
|
|
93
|
+
start = state.run_start(session)
|
|
94
|
+
elapsed = time.time() - start if start else None
|
|
95
|
+
if elapsed is not None and elapsed < settings.min_seconds:
|
|
96
|
+
return
|
|
97
|
+
if _debounced("last_stop"):
|
|
98
|
+
return
|
|
99
|
+
took = f" in {_fmt_duration(elapsed)}" if elapsed is not None else ""
|
|
100
|
+
summary = _last_assistant_text(payload.get("transcript_path"))
|
|
101
|
+
body = f"Finished{took} ({project})" + (f"\n\n{summary}" if summary else "")
|
|
102
|
+
notify(body, title="Claude finished", priority="normal", settings=settings)
|
|
103
|
+
return
|
|
104
|
+
|
|
105
|
+
if event == "Notification":
|
|
106
|
+
if _debounced("last_attention"):
|
|
107
|
+
return
|
|
108
|
+
text = payload.get("message") or "Claude needs your attention"
|
|
109
|
+
notify(f"{text} ({project})", title="Claude needs you", priority="high", settings=settings)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def handle_codex(payload: dict, settings: Settings | None = None) -> None:
|
|
113
|
+
"""Codex CLI `notify` hook: Codex passes one JSON argument; only `agent-turn-complete` exists."""
|
|
114
|
+
settings = settings or Settings()
|
|
115
|
+
if payload.get("type") != "agent-turn-complete":
|
|
116
|
+
return
|
|
117
|
+
if _debounced("last_codex"):
|
|
118
|
+
return
|
|
119
|
+
project = Path(payload.get("cwd") or os.getcwd()).resolve().name or "project"
|
|
120
|
+
last = " ".join(str(payload.get("last-assistant-message") or "").split())
|
|
121
|
+
summary = last[:400] + ("..." if len(last) > 400 else "")
|
|
122
|
+
body = f"Turn complete ({project})" + (f"\n\n{summary}" if summary else "")
|
|
123
|
+
notify(body, title="Codex finished", priority="normal", settings=settings)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def run_from_stdin() -> int:
|
|
127
|
+
try:
|
|
128
|
+
raw = sys.stdin.read()
|
|
129
|
+
payload = json.loads(raw) if raw.strip() else {}
|
|
130
|
+
handle(payload)
|
|
131
|
+
except Exception as exc: # noqa: BLE001
|
|
132
|
+
state.log(f"hook error: {exc.__class__.__name__}")
|
|
133
|
+
return 0
|
agent_notifier/inbox.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Inbound messages (you -> Claude): Telegram replies and an ntfy inbox topic."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from . import channels as ch
|
|
7
|
+
from . import state
|
|
8
|
+
from .config import Settings
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def poll_inbox(settings: Settings | None = None, wait: int = 0, consume: bool = True) -> list[dict]:
|
|
12
|
+
"""Fetch new messages. consume=False peeks without advancing cursors."""
|
|
13
|
+
settings = settings or Settings()
|
|
14
|
+
available = ch.build(settings)
|
|
15
|
+
st = state.load()
|
|
16
|
+
msgs: list[dict] = []
|
|
17
|
+
|
|
18
|
+
tg = available["telegram"]
|
|
19
|
+
if tg.configured():
|
|
20
|
+
try:
|
|
21
|
+
new, nxt = tg.poll(st.get("tg_offset"), wait=wait)
|
|
22
|
+
msgs += new
|
|
23
|
+
if consume and nxt:
|
|
24
|
+
st["tg_offset"] = nxt
|
|
25
|
+
except Exception as exc: # noqa: BLE001
|
|
26
|
+
state.log("telegram poll failed: " + settings.redact(str(exc)))
|
|
27
|
+
|
|
28
|
+
nt = available["ntfy"]
|
|
29
|
+
if nt.configured() and settings.get("NTFY_INBOX_TOPIC"):
|
|
30
|
+
try:
|
|
31
|
+
new, last = nt.poll(st.get("ntfy_last_id"))
|
|
32
|
+
msgs += new
|
|
33
|
+
if consume and last:
|
|
34
|
+
st["ntfy_last_id"] = last
|
|
35
|
+
except Exception as exc: # noqa: BLE001
|
|
36
|
+
state.log("ntfy poll failed: " + settings.redact(str(exc)))
|
|
37
|
+
|
|
38
|
+
if consume:
|
|
39
|
+
state.save(st)
|
|
40
|
+
return sorted(msgs, key=lambda m: m.get("ts", 0))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def wait_for_reply(
|
|
44
|
+
settings: Settings | None = None, timeout: int = 300, since_ts: float | None = None
|
|
45
|
+
) -> tuple[dict | None, list[dict]]:
|
|
46
|
+
"""Block until a reply newer than since_ts arrives.
|
|
47
|
+
|
|
48
|
+
Returns (reply, earlier). `earlier` holds messages queued before the question
|
|
49
|
+
so nothing you sent while Claude was away is silently lost.
|
|
50
|
+
"""
|
|
51
|
+
settings = settings or Settings()
|
|
52
|
+
since_ts = since_ts if since_ts is not None else time.time()
|
|
53
|
+
deadline = time.time() + timeout
|
|
54
|
+
earlier: list[dict] = []
|
|
55
|
+
while True:
|
|
56
|
+
remaining = deadline - time.time()
|
|
57
|
+
if remaining <= 0:
|
|
58
|
+
return None, earlier
|
|
59
|
+
for msg in poll_inbox(settings, wait=int(min(3, remaining))):
|
|
60
|
+
if msg.get("ts", 0) >= since_ts - 2:
|
|
61
|
+
return msg, earlier
|
|
62
|
+
earlier.append(msg)
|
|
63
|
+
time.sleep(1.0)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Discover the installed CLI model catalogs without reading credentials or using API keys.
|
|
2
|
+
|
|
3
|
+
Codex uses its local debug catalog. OpenCode models are read through its official
|
|
4
|
+
CLI. Claude Code does not expose a portable machine-readable catalog; the three
|
|
5
|
+
documented CLI model aliases are offered as unverified choices if Claude is installed.
|
|
6
|
+
The remote owner approves every job and the local CLI performs final access checks.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
from .agents import _resolve
|
|
13
|
+
from .windows_process import hidden_kwargs
|
|
14
|
+
from . import codex_models
|
|
15
|
+
|
|
16
|
+
MODEL_ID = codex_models.MODEL_ID
|
|
17
|
+
AGENTS = ("codex", "claude", "opencode")
|
|
18
|
+
MAX_MODELS = 150
|
|
19
|
+
MAX_BYTES = 100_000
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parse_opencode(raw: str) -> list[dict]:
|
|
23
|
+
"""Parse lines emitted by 'opencode models': provider/model, optionally labels."""
|
|
24
|
+
if not isinstance(raw, str) or len(raw) > MAX_BYTES:
|
|
25
|
+
return []
|
|
26
|
+
found, seen = [], set()
|
|
27
|
+
for line in raw.splitlines():
|
|
28
|
+
ident = line.strip().split(maxsplit=1)[0] if line.strip() else ""
|
|
29
|
+
if (not MODEL_ID.fullmatch(ident) or "/" not in ident
|
|
30
|
+
or ident in seen or ident.startswith(("http:", "https:"))):
|
|
31
|
+
continue
|
|
32
|
+
seen.add(ident)
|
|
33
|
+
found.append({"id": ident, "name": ident})
|
|
34
|
+
if len(found) >= MAX_MODELS:
|
|
35
|
+
break
|
|
36
|
+
return found
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _cmd(executable: str, args: list[str], timeout: int = 12) -> str:
|
|
40
|
+
try:
|
|
41
|
+
process = subprocess.run(
|
|
42
|
+
[executable, *args], capture_output=True, text=True, errors="replace",
|
|
43
|
+
timeout=timeout, stdin=subprocess.DEVNULL, **hidden_kwargs(),
|
|
44
|
+
)
|
|
45
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
46
|
+
return ""
|
|
47
|
+
if process.returncode != 0 or len(process.stdout) > MAX_BYTES:
|
|
48
|
+
return ""
|
|
49
|
+
return process.stdout
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def discover(agent: str) -> list[dict]:
|
|
53
|
+
"""A model list is not a guarantee of entitlement or remaining quota."""
|
|
54
|
+
if agent not in AGENTS:
|
|
55
|
+
return []
|
|
56
|
+
if agent == "codex":
|
|
57
|
+
# Codex's own discovery validates its executable; do not resolve twice.
|
|
58
|
+
return codex_models.discover()
|
|
59
|
+
executable = _resolve(agent)
|
|
60
|
+
if not executable:
|
|
61
|
+
return []
|
|
62
|
+
if agent == "opencode":
|
|
63
|
+
return parse_opencode(_cmd(executable, ["models"]))
|
|
64
|
+
# Claude Code's documented --model flag accepts these stable aliases.
|
|
65
|
+
# This is an alias list, not authenticated account model discovery.
|
|
66
|
+
# The UI labels them as unverified; CLI will reject unavailable models.
|
|
67
|
+
return [{"id": name, "name": f"{name.title()} (CLI alias; access unverified)"}
|
|
68
|
+
for name in ("sonnet", "opus", "haiku")]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def all_installed(installed: set[str]) -> dict[str, list[dict]]:
|
|
72
|
+
return {agent: discover(agent) for agent in AGENTS if agent in installed}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Crash-safe delivery journal for approved companion jobs (Task 025).
|
|
2
|
+
|
|
3
|
+
Claim records contain no credentials, prompts or executable commands.
|
|
4
|
+
Result records may include private agent output; never log or publish them.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import secrets
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from .config import HOME
|
|
16
|
+
|
|
17
|
+
_JOB_RE = re.compile(r"j_[0-9a-f]{16}\Z")
|
|
18
|
+
_MAX_RECORD_SIZE = 45000
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _root() -> Path:
|
|
22
|
+
home = Path(os.environ.get("AGENT_NOTIFIER_HOME") or str(HOME))
|
|
23
|
+
return home / "job-recovery"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _file(kind: str, job_id: str) -> Path:
|
|
27
|
+
if kind not in ("claim", "result") or not _JOB_RE.fullmatch(job_id):
|
|
28
|
+
raise ValueError("invalid journal key")
|
|
29
|
+
return _root() / (kind + "-" + job_id + ".json")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _write(kind: str, job_id: str, device_id: str, payload: dict | None = None) -> None:
|
|
33
|
+
if not device_id or len(device_id) > 120:
|
|
34
|
+
raise ValueError("invalid device")
|
|
35
|
+
path = _file(kind, job_id)
|
|
36
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
37
|
+
try:
|
|
38
|
+
os.chmod(path.parent, 0o700)
|
|
39
|
+
except OSError:
|
|
40
|
+
pass
|
|
41
|
+
item = {"v":1,"device_id":device_id,"job_id":job_id,"created":time.time()}
|
|
42
|
+
if kind == "result":
|
|
43
|
+
if not isinstance(payload, dict) or payload.get("job_id") != job_id:
|
|
44
|
+
raise ValueError("invalid completed result")
|
|
45
|
+
item["payload"] = payload
|
|
46
|
+
content = json.dumps(item, separators=(",",":"), ensure_ascii=False)
|
|
47
|
+
if len(content.encode("utf-8")) > _MAX_RECORD_SIZE:
|
|
48
|
+
raise ValueError("result too large for recovery journal")
|
|
49
|
+
temporary = path.with_name("." + path.name + "." + secrets.token_hex(6) + ".tmp")
|
|
50
|
+
try:
|
|
51
|
+
with temporary.open("x", encoding="utf-8") as handle:
|
|
52
|
+
try:
|
|
53
|
+
os.chmod(temporary, 0o600)
|
|
54
|
+
except OSError:
|
|
55
|
+
pass
|
|
56
|
+
handle.write(content)
|
|
57
|
+
handle.flush()
|
|
58
|
+
os.fsync(handle.fileno())
|
|
59
|
+
os.replace(temporary, path)
|
|
60
|
+
if hasattr(os, "O_DIRECTORY"):
|
|
61
|
+
try:
|
|
62
|
+
fd = os.open(str(path.parent), os.O_RDONLY | os.O_DIRECTORY)
|
|
63
|
+
try:
|
|
64
|
+
os.fsync(fd)
|
|
65
|
+
finally:
|
|
66
|
+
os.close(fd)
|
|
67
|
+
except OSError:
|
|
68
|
+
pass
|
|
69
|
+
finally:
|
|
70
|
+
try:
|
|
71
|
+
temporary.unlink()
|
|
72
|
+
except FileNotFoundError:
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def save_claim(job_id: str, device_id: str) -> None:
|
|
77
|
+
_write("claim",job_id,device_id)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def save_result(job_id: str, device_id: str, payload: dict) -> None:
|
|
81
|
+
_write("result",job_id,device_id,payload)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def records(kind: str, device_id: str) -> list[dict]:
|
|
85
|
+
root = _root()
|
|
86
|
+
if not root.is_dir():
|
|
87
|
+
return []
|
|
88
|
+
found = []
|
|
89
|
+
for path in sorted(root.glob(kind + "-j_*.json")):
|
|
90
|
+
if path.is_symlink() or not path.is_file():
|
|
91
|
+
continue
|
|
92
|
+
try:
|
|
93
|
+
if path.stat().st_size > _MAX_RECORD_SIZE:
|
|
94
|
+
continue
|
|
95
|
+
item = json.loads(path.read_text(encoding="utf-8"))
|
|
96
|
+
if (not isinstance(item,dict) or item.get("v")!=1
|
|
97
|
+
or item.get("device_id")!=device_id
|
|
98
|
+
or not isinstance(item.get("job_id"),str)
|
|
99
|
+
or path!=_file(kind,item["job_id"])):
|
|
100
|
+
continue
|
|
101
|
+
if kind=="result":
|
|
102
|
+
payload=item.get("payload")
|
|
103
|
+
if not isinstance(payload,dict) or payload.get("job_id")!=item["job_id"]:
|
|
104
|
+
continue
|
|
105
|
+
found.append(item)
|
|
106
|
+
except (OSError, ValueError, TypeError, KeyError):
|
|
107
|
+
continue
|
|
108
|
+
return found
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def exists(kind: str, job_id: str) -> bool:
|
|
112
|
+
return _file(kind,job_id).exists()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def discard(kind: str, job_id: str) -> None:
|
|
116
|
+
try:
|
|
117
|
+
_file(kind,job_id).unlink()
|
|
118
|
+
except FileNotFoundError:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def has_unresolved() -> bool:
|
|
123
|
+
"""Fail closed even for corrupt recovery entries."""
|
|
124
|
+
root = _root()
|
|
125
|
+
if not root.is_dir():
|
|
126
|
+
return False
|
|
127
|
+
return any(root.glob("claim-j_*.json")) or any(root.glob("result-j_*.json"))
|
agent_notifier/redact.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Outbound secret redaction for notifications."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .config import Settings
|
|
8
|
+
|
|
9
|
+
_API_KEY_PATTERNS = [
|
|
10
|
+
re.compile(r"\b(sk-[A-Za-z0-9_-]{10,}|AKIA[A-Z0-9]{12,}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b"),
|
|
11
|
+
]
|
|
12
|
+
_PEM_RE = re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S)
|
|
13
|
+
_BEARER_RE = re.compile(r"(?i)Authorization:\s*Bearer\s+\S+")
|
|
14
|
+
_KV_RE = re.compile(r"(?i)(key|token|secret|password)\s*[:=]\s*[\"']?([A-Za-z0-9+/=_-]{12,})[\"']?")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _mask_kv(m: re.Match) -> str:
|
|
18
|
+
return m.group(0).replace(m.group(2), "***")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def redact(text: Any, settings: Settings | None = None, extra: list[str] | None = None) -> str:
|
|
22
|
+
if text is None:
|
|
23
|
+
return ""
|
|
24
|
+
if not isinstance(text, str):
|
|
25
|
+
text = str(text)
|
|
26
|
+
secrets_list: list[str] = []
|
|
27
|
+
if settings is not None:
|
|
28
|
+
try:
|
|
29
|
+
secrets_list.extend(settings.secrets())
|
|
30
|
+
except Exception:
|
|
31
|
+
pass
|
|
32
|
+
if extra:
|
|
33
|
+
secrets_list.extend(x for x in extra if x)
|
|
34
|
+
for s in secrets_list:
|
|
35
|
+
if s and len(s) >= 4:
|
|
36
|
+
text = text.replace(s, "***")
|
|
37
|
+
text = _BEARER_RE.sub("Authorization: Bearer ***", text)
|
|
38
|
+
text = _PEM_RE.sub("[REDACTED PRIVATE KEY]", text)
|
|
39
|
+
for pat in _API_KEY_PATTERNS:
|
|
40
|
+
text = pat.sub("***", text)
|
|
41
|
+
text = _KV_RE.sub(_mask_kv, text)
|
|
42
|
+
return text
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Companion runtime guards: one instance, authorized workspaces, diagnostics."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import contextlib
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .config import HOME
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _state_root() -> Path:
|
|
13
|
+
return Path(os.environ.get("AGENT_NOTIFIER_HOME") or str(HOME))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def lock_path() -> Path:
|
|
17
|
+
return _state_root() / "companion.lock"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def pid_path() -> Path:
|
|
21
|
+
"""The owner PID lives in its own file: Windows byte-range locks also block
|
|
22
|
+
reads of the locked region, so it cannot be stored inside the lock file."""
|
|
23
|
+
return _state_root() / "companion.pid"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _lock(handle) -> None:
|
|
27
|
+
if os.name == "nt":
|
|
28
|
+
import msvcrt
|
|
29
|
+
|
|
30
|
+
handle.seek(0)
|
|
31
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
32
|
+
else:
|
|
33
|
+
import fcntl
|
|
34
|
+
|
|
35
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _unlock(handle) -> None:
|
|
39
|
+
if os.name == "nt":
|
|
40
|
+
import msvcrt
|
|
41
|
+
|
|
42
|
+
handle.seek(0)
|
|
43
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
|
44
|
+
else:
|
|
45
|
+
import fcntl
|
|
46
|
+
|
|
47
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@contextlib.contextmanager
|
|
51
|
+
def instance_lock():
|
|
52
|
+
"""Yield True when this process owns the companion, False if one already runs.
|
|
53
|
+
|
|
54
|
+
The lock is advisory and per-user: it never needs Administrator rights and a
|
|
55
|
+
crashed process releases it automatically when the OS closes the handle.
|
|
56
|
+
"""
|
|
57
|
+
path = lock_path()
|
|
58
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
59
|
+
try:
|
|
60
|
+
os.chmod(path.parent, 0o700)
|
|
61
|
+
except OSError:
|
|
62
|
+
pass
|
|
63
|
+
handle = path.open("a+", encoding="utf-8")
|
|
64
|
+
try:
|
|
65
|
+
_lock(handle)
|
|
66
|
+
except OSError:
|
|
67
|
+
handle.close()
|
|
68
|
+
yield False
|
|
69
|
+
return
|
|
70
|
+
owner = pid_path()
|
|
71
|
+
try:
|
|
72
|
+
owner.write_text(str(os.getpid()), encoding="utf-8")
|
|
73
|
+
yield True
|
|
74
|
+
finally:
|
|
75
|
+
try:
|
|
76
|
+
owner.unlink()
|
|
77
|
+
except OSError:
|
|
78
|
+
pass
|
|
79
|
+
try:
|
|
80
|
+
_unlock(handle)
|
|
81
|
+
finally:
|
|
82
|
+
handle.close()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _lock_held() -> bool:
|
|
86
|
+
"""True when another process (or this one) owns the companion lock."""
|
|
87
|
+
path = lock_path()
|
|
88
|
+
if not path.exists():
|
|
89
|
+
return False
|
|
90
|
+
try:
|
|
91
|
+
handle = path.open("a+", encoding="utf-8")
|
|
92
|
+
except OSError:
|
|
93
|
+
return False
|
|
94
|
+
try:
|
|
95
|
+
_lock(handle)
|
|
96
|
+
except OSError:
|
|
97
|
+
handle.close()
|
|
98
|
+
return True
|
|
99
|
+
try:
|
|
100
|
+
_unlock(handle)
|
|
101
|
+
except OSError:
|
|
102
|
+
pass
|
|
103
|
+
finally:
|
|
104
|
+
handle.close()
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def status() -> dict:
|
|
109
|
+
"""Diagnostics for the companion lock; takes it only for an instant."""
|
|
110
|
+
path = lock_path()
|
|
111
|
+
owner = ""
|
|
112
|
+
try:
|
|
113
|
+
owner = pid_path().read_text(encoding="utf-8").strip()
|
|
114
|
+
except OSError:
|
|
115
|
+
pass
|
|
116
|
+
pid = int(owner) if owner.isdigit() else 0
|
|
117
|
+
return {
|
|
118
|
+
"lock": str(path),
|
|
119
|
+
"pid": pid,
|
|
120
|
+
"running": _lock_held(),
|
|
121
|
+
"workdirs": [str(p) for p in authorized_roots()],
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _configured(settings=None) -> str:
|
|
126
|
+
if settings is not None:
|
|
127
|
+
return settings.get("COMPANION_WORKDIRS", "")
|
|
128
|
+
return os.environ.get("COMPANION_WORKDIRS", "")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def authorized_roots(settings=None) -> list[Path]:
|
|
132
|
+
"""Configured workspaces the companion may launch agents in."""
|
|
133
|
+
raw = _configured(settings)
|
|
134
|
+
parts = [p.strip() for p in raw.replace(";", ",").split(",") if p.strip()]
|
|
135
|
+
roots: list[Path] = []
|
|
136
|
+
for part in parts:
|
|
137
|
+
try:
|
|
138
|
+
resolved = Path(part).expanduser().resolve()
|
|
139
|
+
except (OSError, RuntimeError):
|
|
140
|
+
continue
|
|
141
|
+
if resolved.is_dir() and resolved not in roots:
|
|
142
|
+
roots.append(resolved)
|
|
143
|
+
return roots
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def authorized_workdir(settings=None) -> Path:
|
|
147
|
+
"""The directory a launched agent runs in.
|
|
148
|
+
|
|
149
|
+
With no configuration the user's home directory is the only workspace, so
|
|
150
|
+
an unconfigured companion still works without granting extra access. When
|
|
151
|
+
workspaces are configured, a job never runs outside them.
|
|
152
|
+
"""
|
|
153
|
+
roots = authorized_roots(settings)
|
|
154
|
+
if not roots:
|
|
155
|
+
if _configured(settings).strip():
|
|
156
|
+
# Configured but unusable: fail closed rather than widening access.
|
|
157
|
+
raise ValueError("configured workspaces are unavailable")
|
|
158
|
+
home = Path.home().resolve()
|
|
159
|
+
if home.is_dir():
|
|
160
|
+
return home
|
|
161
|
+
raise ValueError("no authorized working directory is available")
|
|
162
|
+
return roots[0]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def inside(root: Path, candidate: Path) -> bool:
|
|
166
|
+
try:
|
|
167
|
+
candidate.resolve().relative_to(root.resolve())
|
|
168
|
+
except (ValueError, OSError, RuntimeError):
|
|
169
|
+
return False
|
|
170
|
+
return True
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def describe(settings=None) -> str:
|
|
174
|
+
state = status()
|
|
175
|
+
agent_line = "running" if state["running"] else "not running"
|
|
176
|
+
dirs = ", ".join(state["workdirs"]) if state["workdirs"] else str(Path.home())
|
|
177
|
+
return (f"Companion: {agent_line}"
|
|
178
|
+
+ (f" (pid {state['pid']})" if state["running"] else "")
|
|
179
|
+
+ f"\nAuthorized workspaces: {dirs}"
|
|
180
|
+
+ f"\nLock: {state['lock']}")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
if __name__ == "__main__":
|
|
184
|
+
sys.stdout.write(describe() + "\n")
|