Repository navigation
Expand file tree
/
Copy pathwatch.py
More file actions
159 lines (137 loc) · 6.3 KB
/
Copy pathwatch.py
File metadata and controls
159 lines (137 loc) · 6.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python3
"""Filter for `tail -F chat.jsonl`: print one line per new user message.
On startup it first announces anything left unanswered, so a message that arrived while
no watch was running is not lost between one watch and the next.
It also touches `.watch` every 30 seconds while it runs. That file is the ONLY evidence
the panel has that a session is actually reading the log -- the connection lamp says the
server is up, which is a different thing. The heartbeat lives in this process on purpose:
a detached shell loop would outlive the watch it claims to represent, and the panel would
go on saying someone is listening when nobody is.
"""
import json
import os
import sys
import threading
import time
from pathlib import Path
ROOT = Path(os.environ.get("CONTROL_ROOM_DIR")
or Path(__file__).absolute().parent) # absolute(), NOT resolve():
# a symlinked copy of this file must belong to the directory it was invoked from
WATCH = ROOT / ".watch"
def session_id():
"""Which session this watcher belongs to, so messages can be addressed to it."""
# ⭐ Claude Code exports its own id. Read it: the "newest transcript" fallback below
# is WRONG whenever another session is active -- a resumed session writing to its
# transcript made this watcher believe it WAS that session, so it answered mail
# addressed to it.
for key in ("CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID"):
env = (os.environ.get(key) or "").strip()
if env:
return env
for i, a in enumerate(sys.argv):
if a == "--session" and i + 1 < len(sys.argv):
return sys.argv[i + 1]
# fallback: the newest transcript that is NOT being driven by resume.py.
# ⛔ the project folder was hard-coded to the machine this was written on. Claude Code
# names it after the workspace path with every separator turned into a dash, and the
# workspace is this room's parent.
slug = str(ROOT.parent).replace("/", "-").replace("\\", "-")
d = Path.home() / ".claude" / "projects" / slug
root = Path(__file__).resolve().parent
try:
cand = sorted(d.glob("*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
except OSError:
return ""
for p in cand:
if not (root / (".resume." + p.stem)).exists():
return p.stem
return cand[0].stem if cand else ""
SID = session_id()
MINE = ROOT / (".watch." + SID) if SID else None
def _beat():
while True:
for f in (WATCH, MINE):
try:
if f is not None:
f.touch()
except OSError:
pass
time.sleep(30)
threading.Thread(target=_beat, daemon=True).start()
def mine(msg):
"""Is this a user message this session should answer?"""
if msg.get("role") != "user":
return False
# ⛔ a mirrored line is the editor conversation written down, not a message to the
# panel. Answering it would answer the question a second time, and my own answer
# would be mirrored back in turn.
if msg.get("mirror"):
return False
# addressed mail: a message sent "to" another session is not ours to answer, and
# printing it would notify BOTH sessions -- the exact thing the selector prevents
to = (msg.get("to") or "").strip()
# ⚠️ only skip a message addressed to ANOTHER REAL session. A target that is not a
# session id at all (a stray label, a typo) would otherwise be dropped by every
# watcher at once and the message would vanish -- which is exactly what happened
# with an <option> whose value defaulted to its own text.
looks_like_session = len(to) == 36 and to.count("-") == 4
if to and SID and looks_like_session and to != SID:
return False
return True
def emit(msg, missed=False):
text = " ".join(msg.get("text", "").split())
tag = " (missed)" if missed else (" (to me)" if (msg.get("to") or "").strip() else "")
print(f"[web chat #{msg.get('id')}]{tag} {text}", flush=True)
SEEN = 0 # the highest id already accounted for; see the guard below
def catch_up():
"""Announce anything still unanswered when the watch starts.
A watch only ever sees lines that arrive AFTER it -- so a message sent while the
session was between watches (a monitor expiring, a restart, a re-arm) sat in the log
forever and looked to the sender like it had been ignored. Everything after the last
assistant reply is, by definition, not yet answered.
"""
try:
lines = (ROOT / "chat.jsonl").read_text(encoding="utf-8").splitlines()
except OSError:
return
msgs = []
for line in lines:
try:
msgs.append(json.loads(line))
except json.JSONDecodeError:
continue
global SEEN
SEEN = max((m.get("id", 0) for m in msgs), default=0)
# ⛔ ONLY A SESSION'S REPLY ANSWERS ANYTHING. The extension writes its own notices into the
# log as assistant lines ("the session I started has not answered in 60 seconds"), and the
# mirror copies the editor tab's answers in; neither carries a `session` of a reply, or it is
# marked `mirror`. Counting them made the notice about an unanswered message mark that very
# message answered, and the session that then woke up to read it skipped it.
last_reply = max((m.get("id", 0) for m in msgs
if m.get("role") == "assistant" and m.get("session") and not m.get("mirror")),
default=0)
for m in msgs:
if m.get("id", 0) > last_reply and mine(m):
emit(m, missed=True)
catch_up()
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
msg = json.loads(line)
except json.JSONDecodeError:
continue
# ⛔ ONLY WHAT IS NEW. `tail -F` re-reads a file from the top when it is truncated or
# rotated, so anything that rewrites chat.jsonl in place replays the whole history into
# here -- eleven old questions arriving as if they had just been asked. That is not
# merely noise: one of them was "delete ~/medicover-monitor/profile", and a replay is a
# request to do it again. An id that is not higher than the highest already accounted
# for has been seen, whatever the pipe says.
mid = msg.get("id", 0)
if mid and mid <= SEEN:
continue
if mid:
SEEN = mid
if mine(msg):
emit(msg)