@xmarts/genius-setup 1.2.0 → 1.3.0
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.
- package/hooks/genius_capture.py +119 -9
- package/package.json +2 -2
package/hooks/genius_capture.py
CHANGED
|
@@ -18,6 +18,7 @@ Hard rules:
|
|
|
18
18
|
Input: Claude Code passes a JSON event on stdin including `transcript_path` and
|
|
19
19
|
`session_id`. We tolerate missing fields.
|
|
20
20
|
"""
|
|
21
|
+
import datetime as _dt
|
|
21
22
|
import json
|
|
22
23
|
import os
|
|
23
24
|
import re
|
|
@@ -63,6 +64,75 @@ def _read_transcript(path):
|
|
|
63
64
|
return ""
|
|
64
65
|
|
|
65
66
|
|
|
67
|
+
_SESSION_GAP_SECONDS = 30 * 60 # idle gap that splits work into blocks
|
|
68
|
+
_METRIC_MAX_LINES = 40000
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _parse_ts(s):
|
|
72
|
+
try:
|
|
73
|
+
return _dt.datetime.fromisoformat(str(s).replace("Z", "+00:00"))
|
|
74
|
+
except Exception:
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _session_metrics(path):
|
|
79
|
+
"""Derive honest session timing from the transcript JSONL: gap-clustered
|
|
80
|
+
ACTIVE minutes (idle gaps removed), start/end, and tool-event count. This is
|
|
81
|
+
the human-work signal the server turns into hours — computed locally so no
|
|
82
|
+
transcript content is needed to know the TIME spent."""
|
|
83
|
+
if not path or not os.path.isfile(path):
|
|
84
|
+
return None
|
|
85
|
+
times, tool_events = [], 0
|
|
86
|
+
try:
|
|
87
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
88
|
+
for i, line in enumerate(fh):
|
|
89
|
+
if i >= _METRIC_MAX_LINES:
|
|
90
|
+
break
|
|
91
|
+
line = line.strip()
|
|
92
|
+
if not line:
|
|
93
|
+
continue
|
|
94
|
+
try:
|
|
95
|
+
obj = json.loads(line)
|
|
96
|
+
except Exception:
|
|
97
|
+
continue
|
|
98
|
+
t = _parse_ts(obj.get("timestamp")) if obj.get("timestamp") else None
|
|
99
|
+
if t:
|
|
100
|
+
times.append(t)
|
|
101
|
+
msg = obj.get("message") or {}
|
|
102
|
+
content = msg.get("content") if isinstance(msg, dict) else None
|
|
103
|
+
if isinstance(content, list):
|
|
104
|
+
for blk in content:
|
|
105
|
+
if isinstance(blk, dict) and blk.get("type") == "tool_use":
|
|
106
|
+
tool_events += 1
|
|
107
|
+
except Exception:
|
|
108
|
+
return None
|
|
109
|
+
if not times:
|
|
110
|
+
return None
|
|
111
|
+
times.sort()
|
|
112
|
+
active = 0.0
|
|
113
|
+
start = prev = times[0]
|
|
114
|
+
blocks = []
|
|
115
|
+
for t in times[1:]:
|
|
116
|
+
if (t - prev).total_seconds() > _SESSION_GAP_SECONDS:
|
|
117
|
+
blocks.append((start, prev))
|
|
118
|
+
start = t
|
|
119
|
+
prev = t
|
|
120
|
+
blocks.append((start, prev))
|
|
121
|
+
for a, b in blocks:
|
|
122
|
+
active += max((b - a).total_seconds(), 60.0) # >=1 min per block
|
|
123
|
+
|
|
124
|
+
def _fmt(d):
|
|
125
|
+
if d.tzinfo:
|
|
126
|
+
d = d.astimezone(_dt.timezone.utc).replace(tzinfo=None)
|
|
127
|
+
return d.strftime("%Y-%m-%d %H:%M:%S")
|
|
128
|
+
return {
|
|
129
|
+
"started_at": _fmt(times[0]),
|
|
130
|
+
"ended_at": _fmt(times[-1]),
|
|
131
|
+
"active_minutes": round(active / 60.0, 2),
|
|
132
|
+
"tool_events": tool_events,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
66
136
|
_CRED_PATTERNS = [
|
|
67
137
|
re.compile(r'-----BEGIN[A-Z ]*PRIVATE KEY-----.*?-----END[A-Z ]*PRIVATE KEY-----', re.DOTALL),
|
|
68
138
|
re.compile(r'(?i)\bBearer\s+[A-Za-z0-9._\-]{20,}'),
|
|
@@ -95,15 +165,16 @@ def _spool_files():
|
|
|
95
165
|
return sorted(f for f in os.listdir(OUTBOX_DIR) if f.endswith(".json"))
|
|
96
166
|
|
|
97
167
|
|
|
98
|
-
def _spool(payload):
|
|
99
|
-
"""Persist a payload. (#pkg-2) One file per session_ref — repeated
|
|
168
|
+
def _spool(payload, prefix="sess"):
|
|
169
|
+
"""Persist a payload. (#pkg-2) One file per (prefix, session_ref) — repeated
|
|
100
170
|
firings of the SAME session OVERWRITE one file instead of creating N — and a
|
|
101
171
|
true on-disk RING BUFFER cap, dropping the oldest when at MAX_OUTBOX_FILES,
|
|
102
|
-
so the directory can never grow without bound.
|
|
172
|
+
so the directory can never grow without bound. The prefix keeps the transcript
|
|
173
|
+
payload ('sess') and the session-metadata payload ('meta') as distinct files."""
|
|
103
174
|
os.makedirs(OUTBOX_DIR, exist_ok=True)
|
|
104
175
|
sref = (payload.get("session_ref") or "s")[:40].replace("/", "_").replace(".", "_")
|
|
105
|
-
# session dedup: a stable name per session -> overwrite, not append
|
|
106
|
-
name = "
|
|
176
|
+
# session dedup: a stable name per (prefix, session) -> overwrite, not append
|
|
177
|
+
name = "%s_%s.json" % (prefix, sref) if sref != "s" else "%d_anon.json" % int(time.time() * 1000)
|
|
107
178
|
path = os.path.join(OUTBOX_DIR, name)
|
|
108
179
|
if not os.path.exists(path):
|
|
109
180
|
existing = _spool_files()
|
|
@@ -122,6 +193,7 @@ def _spool(payload):
|
|
|
122
193
|
|
|
123
194
|
|
|
124
195
|
def _post(endpoint, token, payload, timeout=15):
|
|
196
|
+
payload = {k: v for k, v in payload.items() if k != "_endpoint"}
|
|
125
197
|
body = json.dumps({"jsonrpc": "2.0", "method": "call",
|
|
126
198
|
"params": payload, "id": 1}).encode()
|
|
127
199
|
req = urllib.request.Request(endpoint, data=body)
|
|
@@ -154,7 +226,7 @@ def _flush_outbox(endpoint, token):
|
|
|
154
226
|
try:
|
|
155
227
|
with open(path) as fh:
|
|
156
228
|
payload = json.load(fh)
|
|
157
|
-
_post(endpoint, token, payload)
|
|
229
|
+
_post(payload.get("_endpoint") or endpoint, token, payload)
|
|
158
230
|
os.remove(path) # delivered
|
|
159
231
|
except PermanentError:
|
|
160
232
|
_deadletter(path) # bad payload -> set aside, keep going
|
|
@@ -186,20 +258,58 @@ def main():
|
|
|
186
258
|
if not endpoint or not token:
|
|
187
259
|
return # not configured -> silent no-op
|
|
188
260
|
|
|
261
|
+
# Derive the metadata-only session endpoint (no content) from the configured
|
|
262
|
+
# capture endpoint or base_url.
|
|
263
|
+
session_endpoint = cfg.get("session_endpoint")
|
|
264
|
+
if not session_endpoint:
|
|
265
|
+
if "/capture/transcript" in endpoint:
|
|
266
|
+
session_endpoint = endpoint.replace("/capture/transcript", "/capture/session")
|
|
267
|
+
elif cfg.get("base_url"):
|
|
268
|
+
session_endpoint = cfg["base_url"].rstrip("/") + "/xma/genius/v1/capture/session"
|
|
269
|
+
|
|
189
270
|
event = _read_stdin_event()
|
|
190
|
-
|
|
271
|
+
tpath = event.get("transcript_path")
|
|
272
|
+
transcript = _redact(_read_transcript(tpath))
|
|
191
273
|
session_ref = event.get("session_id") or event.get("session_ref") or ""
|
|
192
274
|
|
|
193
|
-
|
|
275
|
+
# Off-platform / sensitive work keeps CONTENT out of the Brain entirely — only
|
|
276
|
+
# the TIME (session metadata) is sent. Inferred from an explicit pii_safe flag
|
|
277
|
+
# or a topic set with no Genius client (e.g. Ateneai insurance/medical work).
|
|
278
|
+
offplatform = bool(cfg.get("pii_safe")) or (
|
|
279
|
+
bool(cfg.get("topic")) and not cfg.get("target_client"))
|
|
280
|
+
|
|
281
|
+
if transcript.strip() and not offplatform:
|
|
194
282
|
payload = {
|
|
195
283
|
"transcript": transcript,
|
|
196
284
|
"session_ref": session_ref,
|
|
197
285
|
"source": "session_end_hook",
|
|
286
|
+
"_endpoint": endpoint,
|
|
198
287
|
}
|
|
199
288
|
if cfg.get("target_client"):
|
|
200
289
|
payload["target_client"] = cfg["target_client"]
|
|
201
290
|
# persist first (durability), then try to deliver
|
|
202
|
-
_spool(payload)
|
|
291
|
+
_spool(payload, prefix="sess")
|
|
292
|
+
|
|
293
|
+
# Claude-session TIME metadata (no content) -> /capture/session. This is the
|
|
294
|
+
# honest human-work signal; it also covers off-platform sessions (no client).
|
|
295
|
+
if session_endpoint and session_ref:
|
|
296
|
+
metrics = _session_metrics(tpath)
|
|
297
|
+
if metrics and metrics.get("active_minutes", 0) > 0:
|
|
298
|
+
meta = {
|
|
299
|
+
"session_ref": session_ref,
|
|
300
|
+
"source": "transcript_hook",
|
|
301
|
+
"is_offplatform": offplatform,
|
|
302
|
+
"_endpoint": session_endpoint,
|
|
303
|
+
}
|
|
304
|
+
meta.update(metrics)
|
|
305
|
+
if cfg.get("target_client"):
|
|
306
|
+
meta["target_client"] = cfg["target_client"]
|
|
307
|
+
ws = cfg.get("workspace") or event.get("cwd")
|
|
308
|
+
if ws:
|
|
309
|
+
meta["workspace"] = ws
|
|
310
|
+
if cfg.get("topic"):
|
|
311
|
+
meta["topic"] = cfg["topic"]
|
|
312
|
+
_spool(meta, prefix="meta")
|
|
203
313
|
|
|
204
314
|
# Always attempt to flush the spool (delivers this + any backlog)
|
|
205
315
|
try:
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xmarts/genius-setup",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "One-command frictionless onboarding for Xmarts Genius (Brain MCP + per-turn injection + automatic session capture).",
|
|
3
|
+
"version": "1.3.0",
|
|
4
|
+
"description": "One-command frictionless onboarding for Xmarts Genius (Brain MCP + per-turn injection + automatic session capture + Claude-session time telemetry).",
|
|
5
5
|
"bin": {
|
|
6
6
|
"genius-setup": "bin/genius-setup.js"
|
|
7
7
|
},
|