divan-cli 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.
divan/hooks.py ADDED
@@ -0,0 +1,475 @@
1
+ """`divan hook <agent> <event>`: the agent-side half of "search before research, save after".
2
+
3
+ The hook never breaks the agent: every failure path exits 0 with no output.
4
+ It makes no network calls and writes only small per-session state files under
5
+ the XDG state dir. Each behaviour can be changed or turned off in the `[agent]`
6
+ table of the user config (see settings.py), or all at once with DIVAN_AGENT=off.
7
+
8
+ Behaviour, by event:
9
+ SessionStart add the standing rule and the corpora this profile sees.
10
+ PreToolUse on a web research tool, deny the first call if `divan find` has not run.
11
+ PostToolUse record `divan find`, `divan land`, and web research (reminder once).
12
+ PreCompact if research happened and nothing was landed, remind. (Not in Antigravity.)
13
+ Stop if research happened and nothing was landed, block once.
14
+ """
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import signal
20
+ import stat
21
+ import sys
22
+ import time
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+
26
+ from . import privdir, settings
27
+
28
+ AGENTS = ("claude", "codex", "antigravity")
29
+ PRUNE_AFTER = 14 * 86400
30
+ MAX_STDIN = 1 << 20 # a hook payload past this gets no decision
31
+ MAX_TRANSCRIPT_SCAN = 4 << 20 # bytes read from the end of a transcript
32
+ DEADLINE = 3.0 # hard wall-clock limit for a whole hook run (DIVAN_HOOK_DEADLINE overrides, for tests)
33
+ SCAN_BUDGET = 1.0 # seconds; hook timeouts are several times this
34
+ WEB_TOOLS = {
35
+ "claude": {"websearch", "webfetch"},
36
+ "codex": {"websearch", "webfetch", "web_search", "web_fetch"},
37
+ "antigravity": {"search_web", "read_url_content"},
38
+ }
39
+ FIND_RE = re.compile(r"(?:^|[\s;&|(])divan\s+find\b")
40
+ LAND_RE = re.compile(r"(?:^|[\s;&|(])divan\s+land\b")
41
+
42
+ RULE = ("Before web research, run `divan find \"<topic>\"` to see what is already known. "
43
+ "Save durable findings about the world (not your own project's work) with `divan new` and `divan land`.")
44
+
45
+
46
+ def change_line(key: str) -> str:
47
+ return f"To change this: divan agent set {key} remind (or off)"
48
+
49
+
50
+ def off_line(key: str) -> str:
51
+ return f"To turn this off: divan agent set {key} off"
52
+
53
+
54
+ def state_dir() -> Path:
55
+ base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
56
+ return Path(base) / "divan" / "hooks"
57
+
58
+
59
+ MARKER_RE = re.compile(r"(?:claude|codex|antigravity)-[A-Za-z0-9_-]{1,80}(?:\.[a-z_]+\.once|\.json)")
60
+
61
+
62
+ class State:
63
+ """Per-session flags, one marker file each (`<agent>-<sid>.<flag>.once`) in the state folder.
64
+ Setting a flag only creates its own file, so concurrent hook processes cannot erase each
65
+ other's flags. The folder is opened safely (see privdir); if it is unsafe or unwritable there
66
+ is no durable state and nothing that needs it (deny, block) happens."""
67
+
68
+ def __init__(self, agent: str, sid: str):
69
+ self.prefix = f"{agent}-{sid}" if sid else None
70
+ self.d = {}
71
+ self._fd = None
72
+ self._opened = False
73
+
74
+ def _dir(self):
75
+ if not self._opened:
76
+ self._opened = True
77
+ self._fd = privdir.open_dir(state_dir(), create=True, forbidden_mode=0o022)
78
+ return self._fd
79
+
80
+ def _name(self, k):
81
+ return f"{self.prefix}.{k}.once"
82
+
83
+ def get(self, k) -> bool:
84
+ if self.d.get(k):
85
+ return True
86
+ fd = self._dir() if self.prefix else None
87
+ return fd is not None and privdir.exists(fd, self._name(k))
88
+
89
+ done = get
90
+
91
+ def _create(self, k, excl: bool) -> bool:
92
+ fd = self._dir() if self.prefix else None
93
+ if fd is None:
94
+ return False
95
+ try:
96
+ os.close(privdir.create_file(fd, self._name(k), excl))
97
+ return True
98
+ except OSError:
99
+ return False
100
+
101
+ def set(self, k):
102
+ self.d[k] = True # still true for this process if the folder is unusable
103
+ self._create(k, excl=False)
104
+
105
+ def claim(self, k) -> bool:
106
+ """Win the one-time right to act on `k` for this session. Atomic across concurrent
107
+ hook processes (O_CREAT|O_EXCL) and durable. False when we cannot be sure we won
108
+ (no session id, unsafe or unwritable state dir, lost race): callers then stay silent and allow."""
109
+ if not self._create(k, excl=True):
110
+ return False
111
+ self.d[k] = True
112
+ return True
113
+
114
+
115
+ def prune(now: float | None = None) -> None:
116
+ """Delete old regular files that carry divan's own marker names; nothing else."""
117
+ now = now or time.time()
118
+ fd = privdir.open_dir(state_dir(), create=False, forbidden_mode=0o022)
119
+ if fd is None:
120
+ return
121
+ try:
122
+ for name in os.listdir(fd):
123
+ if not MARKER_RE.fullmatch(name):
124
+ continue
125
+ try:
126
+ st = os.stat(name, dir_fd=fd, follow_symlinks=False)
127
+ if stat.S_ISREG(st.st_mode) and now - st.st_mtime > PRUNE_AFTER:
128
+ os.unlink(name, dir_fd=fd)
129
+ except OSError:
130
+ continue
131
+ except OSError:
132
+ pass
133
+ finally:
134
+ os.close(fd)
135
+
136
+
137
+ # ---- per-agent field shims -------------------------------------------------
138
+
139
+ @dataclass
140
+ class Event:
141
+ agent: str
142
+ sid: str
143
+ tool: str # tool name as the agent reports it
144
+ command: str # shell command, if the tool is a shell tool
145
+ ok: bool # the tool call succeeded (PostToolUse)
146
+ transcript: str
147
+ continuing: bool # a stop hook already kept the agent going (loop guard)
148
+ subagent: bool
149
+ headless: bool = False
150
+
151
+ @property
152
+ def web(self) -> bool:
153
+ return self.tool.lower() in WEB_TOOLS[self.agent]
154
+
155
+
156
+ def _sid(raw) -> str:
157
+ raw = str(raw or "")
158
+ if not raw:
159
+ return ""
160
+ if re.fullmatch(r"[A-Za-z0-9_-]{1,80}", raw):
161
+ return raw
162
+ return hashlib.sha1(raw.encode()).hexdigest()[:20]
163
+
164
+
165
+ def _exit_code(v):
166
+ if isinstance(v, dict):
167
+ for k in ("exit_code", "exitCode", "returncode"):
168
+ if isinstance(v.get(k), int):
169
+ return v[k]
170
+ for x in v.values():
171
+ r = _exit_code(x)
172
+ if r is not None:
173
+ return r
174
+ elif isinstance(v, str) and v.lstrip().startswith("{"):
175
+ try:
176
+ return _exit_code(json.loads(v))
177
+ except ValueError:
178
+ return None
179
+ return None
180
+
181
+
182
+ def _claude_like(agent: str, d: dict) -> Event:
183
+ """Claude Code and Codex: snake_case fields, tool_name/tool_input/tool_response."""
184
+ ti = d.get("tool_input") or d.get("toolInput") or {}
185
+ if isinstance(ti, str):
186
+ cmd = ti
187
+ else:
188
+ c = ti.get("command") or ti.get("cmd") or ""
189
+ cmd = " ".join(map(str, c)) if isinstance(c, list) else str(c)
190
+ resp = d.get("tool_response", d.get("toolResponse"))
191
+ ok = True
192
+ if isinstance(resp, dict) and (resp.get("is_error") or resp.get("isError") or resp.get("interrupted")):
193
+ ok = False
194
+ elif _exit_code(resp) not in (None, 0):
195
+ ok = False
196
+ return Event(agent, _sid(d.get("session_id") or d.get("sessionId") or d.get("conversation_id")),
197
+ str(d.get("tool_name") or d.get("toolName") or ""), cmd, ok,
198
+ str(d.get("transcript_path") or ""), bool(d.get("stop_hook_active")),
199
+ bool(d.get("agent_id")))
200
+
201
+
202
+ def _antigravity(d: dict) -> Event:
203
+ """Antigravity: camelCase protojson; toolCall {name, args}; `error` set when the tool failed."""
204
+ tc = d.get("toolCall") or {}
205
+ args = tc.get("args") or {}
206
+ cmd = args.get("CommandLine") or args.get("command") or ""
207
+ return Event("antigravity", _sid(d.get("conversationId")), str(tc.get("name") or ""), str(cmd),
208
+ not d.get("error"), str(d.get("transcriptPath") or ""),
209
+ bool(d.get("continuationActive")), bool(d.get("parentConversationId")))
210
+
211
+
212
+ def is_headless(agent: str, env) -> bool:
213
+ """A run whose last message is a result for a parent process, not a person.
214
+ Claude: CLAUDE_CODE_ENTRYPOINT is sdk-cli (-p), sdk-ts or sdk-py; `cli`, `t3-code`
215
+ and anything unknown or absent are interactive.
216
+ TODO(codex, antigravity): no documented or observed headless signal in their hook
217
+ payloads or environment; capture a real `codex exec` / `agy` run with DIVAN_HOOK_LOG
218
+ to settle it. Until then they count as not headless."""
219
+ if agent == "claude":
220
+ return str(env.get("CLAUDE_CODE_ENTRYPOINT", "")).startswith("sdk")
221
+ return False
222
+
223
+
224
+ def parse(agent: str, d: dict) -> Event:
225
+ return _antigravity(d) if agent == "antigravity" else _claude_like(agent, d)
226
+
227
+
228
+ def native_web_search(ev: Event) -> bool:
229
+ """Codex's hosted web search skips hooks; it shows only in the rollout file.
230
+ Scan from the end, bounded in bytes and time; any doubt means "no"."""
231
+ if not ev.transcript:
232
+ return False
233
+ needle = b'"web_search_call"'
234
+ chunk = 1 << 18
235
+ deadline = time.monotonic() + SCAN_BUDGET
236
+ try:
237
+ with open(ev.transcript, "rb") as f:
238
+ pos = f.seek(0, os.SEEK_END)
239
+ floor = max(0, pos - MAX_TRANSCRIPT_SCAN)
240
+ tail = b""
241
+ while pos > floor:
242
+ if time.monotonic() > deadline:
243
+ return False
244
+ start = max(floor, pos - chunk)
245
+ f.seek(start)
246
+ buf = f.read(pos - start) + tail
247
+ if needle in buf:
248
+ return True
249
+ tail = buf[:len(needle) - 1]
250
+ pos = start
251
+ except (OSError, ValueError):
252
+ return False
253
+ return False
254
+
255
+
256
+ # ---- output, per agent -----------------------------------------------------
257
+
258
+ def out_context(agent: str, event: str, text: str):
259
+ """Text the agent's model sees. Antigravity only accepts injected steps at session start."""
260
+ if agent == "antigravity":
261
+ if event == "SessionStart":
262
+ return {"injectSteps": [{"systemMessage": {"systemMessage": text}}]}
263
+ return None
264
+ return {"hookSpecificOutput": {"hookEventName": event, "additionalContext": text}}
265
+
266
+
267
+ def out_deny(agent: str, reason: str):
268
+ if agent == "antigravity":
269
+ return {"decision": "deny", "reason": reason}
270
+ return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
271
+ "permissionDecisionReason": reason}}
272
+
273
+
274
+ def out_remind_tool(agent: str, text: str):
275
+ if agent == "antigravity":
276
+ return {"decision": "allow", "reason": text}
277
+ return out_context(agent, "PreToolUse", text)
278
+
279
+
280
+ def out_block_stop(agent: str, reason: str):
281
+ return {"decision": "continue" if agent == "antigravity" else "block", "reason": reason}
282
+
283
+
284
+ def out_note_to_user(agent: str, text: str):
285
+ return None if agent == "antigravity" else {"systemMessage": text}
286
+
287
+
288
+ # ---- handlers --------------------------------------------------------------
289
+
290
+ def _corpora_line() -> str:
291
+ try:
292
+ from .config import load_context
293
+ ctx = load_context(None, None)
294
+ except Exception:
295
+ return ""
296
+ if not ctx.corpora:
297
+ return ""
298
+ names = ", ".join(c.name + (" (write)" if c.name == ctx.write else "") for c in ctx.corpora.values())
299
+ return (f"Corpora in profile '{ctx.profile}': {names}. "
300
+ "Run `divan guide <corpus>` before writing to one.")
301
+
302
+
303
+ def session_start(ev, st, cfg):
304
+ prune()
305
+ if not cfg["session_note"]:
306
+ return None
307
+ lines = ["divan knowledge base is installed.", RULE]
308
+ c = _corpora_line()
309
+ if c:
310
+ lines.append(c)
311
+ extra = settings.note_extra_text(cfg["note_extra"])
312
+ if extra:
313
+ lines.append(extra)
314
+ return out_context(ev.agent, "SessionStart", "\n".join(lines))
315
+
316
+
317
+ def pre_tool_use(ev, st, cfg):
318
+ mode = cfg["search_first"]
319
+ if mode == "off" or ev.subagent or not ev.web or st.get("found") or st.done("denied"):
320
+ return None
321
+ if not st.claim("denied"):
322
+ return None
323
+ if mode == "remind":
324
+ return out_remind_tool(ev.agent, "Reminder: run `divan find \"<topic>\"` before web research, "
325
+ "so you do not redo what the knowledge base already holds. "
326
+ + off_line("search_first"))
327
+ return out_deny(ev.agent, (
328
+ "Run `divan find \"<topic>\"` first to see what the knowledge base already holds, "
329
+ "then retry this call. This check happens once per session. " + change_line("search_first")))
330
+
331
+
332
+ def post_tool_use(ev, st, cfg):
333
+ if ev.web:
334
+ st.set("researched")
335
+ if cfg["capture_reminder"] and not st.done("reminded") and st.claim("reminded"):
336
+ return out_context(ev.agent, "PostToolUse",
337
+ "You did web research. Before finishing, save durable findings with "
338
+ "`divan new` + `divan land` (run `divan guide <corpus>` first). "
339
+ + off_line("capture_reminder"))
340
+ return None
341
+ if ev.command and ev.ok:
342
+ if FIND_RE.search(ev.command):
343
+ st.set("found")
344
+ if LAND_RE.search(ev.command):
345
+ st.set("landed")
346
+ return None
347
+
348
+
349
+ def pre_compact(ev, st, cfg):
350
+ if cfg["compact_reminder"] and st.get("researched") and not st.get("landed"):
351
+ return out_note_to_user(ev.agent, "divan: research happened this session and nothing was landed. "
352
+ "Capture durable findings with `divan new` + `divan land` before context is lost. "
353
+ + off_line("compact_reminder"))
354
+ return None
355
+
356
+
357
+ def stop(ev, st, cfg):
358
+ mode = cfg["stop_gate"]
359
+ if mode == "off" or ev.continuing or ev.subagent or st.done("blocked"):
360
+ return None
361
+ if ev.headless and not cfg["gate_headless"]:
362
+ return None
363
+ if ev.agent == "codex" and not st.get("researched") and native_web_search(ev):
364
+ st.set("researched")
365
+ if not (st.get("researched") and not st.get("landed")):
366
+ return None
367
+ if not st.claim("blocked"):
368
+ return None
369
+ if mode == "remind":
370
+ return out_note_to_user(ev.agent, "divan: you did research this session and nothing was landed. "
371
+ "Save durable findings with `divan new` + `divan land`. " + off_line("stop_gate"))
372
+ return out_block_stop(ev.agent, (
373
+ "You did research this session and landed nothing. Capture the durable findings with "
374
+ "`divan new` + `divan land`, or say in one sentence why nothing here is durable, then finish. "
375
+ + change_line("stop_gate")))
376
+
377
+
378
+ HANDLERS = {"SessionStart": session_start, "PreToolUse": pre_tool_use, "PostToolUse": post_tool_use,
379
+ "PreCompact": pre_compact, "Stop": stop}
380
+
381
+
382
+ def run(agent: str, event: str, raw: str, env=os.environ) -> dict | None:
383
+ """Pure-ish entry point: returns the JSON object to print, or None."""
384
+ h = HANDLERS.get(event)
385
+ if h is None or agent not in AGENTS:
386
+ return None
387
+ try:
388
+ cfg = settings.values(env)
389
+ if not cfg["enabled"]:
390
+ return None
391
+ data = json.loads(raw) if raw.strip() else {}
392
+ if not isinstance(data, dict):
393
+ return None
394
+ ev = parse(agent, data)
395
+ ev.headless = is_headless(agent, env)
396
+ return h(ev, State(agent, ev.sid), cfg)
397
+ except Exception:
398
+ return None
399
+
400
+
401
+ def _expire(*_):
402
+ os._exit(0) # out of time: no output, no decision, exit 0
403
+
404
+
405
+ def _arm_deadline() -> None:
406
+ try:
407
+ limit = float(os.environ.get("DIVAN_HOOK_DEADLINE") or DEADLINE)
408
+ signal.signal(signal.SIGALRM, _expire)
409
+ signal.setitimer(signal.ITIMER_REAL, limit)
410
+ except (ValueError, OSError, AttributeError):
411
+ pass
412
+
413
+
414
+ def main(agent: str, event: str) -> int:
415
+ _arm_deadline() # covers a stdin that never closes and any slow file read
416
+ try:
417
+ data = sys.stdin.buffer.read(MAX_STDIN + 1)
418
+ except Exception:
419
+ data = b""
420
+ too_big = len(data) > MAX_STDIN
421
+ raw = data.decode("utf-8", "replace")
422
+ out = None if too_big else run(agent, event, raw)
423
+ if out is None and agent == "antigravity":
424
+ # Antigravity's contract wants a JSON object on every call; PreToolUse needs a decision.
425
+ out = {"decision": "allow"} if event == "PreToolUse" else {}
426
+ text = json.dumps(out) if out is not None else ""
427
+ # The deadline stays armed through every write and the final flush; if it fires, _expire exits 0 at once.
428
+ _log(agent, event, raw, text)
429
+ try:
430
+ if text:
431
+ sys.stdout.write(text)
432
+ sys.stdout.flush()
433
+ except (OSError, ValueError): # BrokenPipeError is an OSError: the reader went away
434
+ _disarm()
435
+ _quiet_exit()
436
+ _disarm()
437
+ return 0
438
+
439
+
440
+ def _quiet_exit():
441
+ """Exit 0 without Python's own flush-at-exit trying (and failing) to write again."""
442
+ try:
443
+ os.dup2(os.open(os.devnull, os.O_WRONLY), 1)
444
+ except OSError:
445
+ pass
446
+ os._exit(0)
447
+
448
+
449
+ def _disarm() -> None:
450
+ try:
451
+ signal.setitimer(signal.ITIMER_REAL, 0)
452
+ except (ValueError, OSError, AttributeError):
453
+ pass
454
+
455
+
456
+ def _log(agent: str, event: str, raw: str, out: str) -> None:
457
+ """DIVAN_HOOK_LOG=<dir>: keep each call's raw stdin and output, for capturing real payloads.
458
+ These files hold raw prompts and tool input: the folder must be private to you (0700, created
459
+ so if we make it), each file is 0600, and everything is written relative to the opened folder."""
460
+ d = os.environ.get("DIVAN_HOOK_LOG")
461
+ if not d:
462
+ return
463
+ fd = privdir.open_dir(Path(d), create=True, forbidden_mode=0o077)
464
+ if fd is None:
465
+ return
466
+ try:
467
+ stem = f"{time.time_ns()}-{os.getpid()}-{agent}-{event}"
468
+ for ext, text in (("stdin", raw), ("stdout", out)):
469
+ f = os.fdopen(privdir.create_file(fd, f"{stem}.{ext}", excl=True), "w")
470
+ with f:
471
+ f.write(text)
472
+ except OSError:
473
+ pass
474
+ finally:
475
+ os.close(fd)