Something went wrong. Try again.
Wires Claude Code to a didbot personal data server: hooks, a plugin, and the harness contract they rest on.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205#!/usr/bin/env python3"""Report one hook event to the local receiver, and tell a context its name.
A hook that breaks is worse than a hook that learns nothing, so every pathhere ends in exit 0, and with no output unless there is something to say.
**What is sent.** Field names and identifiers, never values. A payload carriesprompts, tool arguments and file paths, and none of that answers any question`plan/collection.md` asks.
**What comes back.** The receiver answers, and the answer is sometimes a name.A context that has just been given one is told so through `additionalContext`,which is the only channel that reaches the model itself. Saying it twice isthe receiver's job to prevent, not this program's: a hook that tried toremember what it had already said would be a hook keeping state acrossprocesses, and there is one of these per event.
**Which context is acting.** `PreToolUse` is the only place the harness namesthe acting agent, so a subagent that makes a tool call without having beenannounced is still identified. `agent_id` is absent when the call comes fromthe main conversation, which is how a session is told apart from its children."""
import jsonimport osimport socketimport sysimport tracebackimport time
#: Which plugin is asking. The receiver counts askers separately, so a second#: plugin on these events is answered rather than met with the silence that#: means "already told".ASKER = "didbot"
#: The wire version this program writes. A receiver that does not know it says#: so rather than going quiet, so a mismatch shows up in the log below.VERSION = 1
#: What each hook event means to a receiver that thinks in contexts rather than#: in harness events. Everything not named here is `noted`: it happened, and it#: does not change what the context is owed.OBSERVED = { "SessionStart": "began", "SubagentStart": "began", "PreToolUse": "acted", "Stop": "rested", "SubagentStop": "rested", "SessionEnd": "ended",}
#: Where the receiver listens, unless told otherwise. Not a secret — reaching#: the socket is the permission, and its own directory is what enforces that.def socket_path(): override = os.environ.get("DIDBOT_SOCK") if override: return override runtime = os.environ.get("XDG_RUNTIME_DIR") or "/tmp" return os.path.join(runtime, "didbot-agent", "agent.sock")
#: Values safe to record: identifiers with no content in them, and the names#: of mechanisms.SCALARS = ( "hook_event_name", "session_id", "agent_id", "agent_type", "tool_use_id", "tool_name", "prompt_id", "permission_mode", "source", "reason", "spawn_depth",)
def ask(record): """Hand one record to the receiver and read its answer.
Nobody listening is the ordinary case — the plugin is installed and the daemon is not running — so that is silent. The two seconds is a ceiling on how long a session will wait for a name, not an expectation: the answer normally involves one local request. """ try: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: sock.settimeout(2.0) sock.connect(socket_path()) sock.sendall((json.dumps(record, sort_keys=True) + "\n").encode()) reply = sock.makefile().readline() except OSError: return {} try: answer = json.loads(reply) except ValueError: return {} return answer if isinstance(answer, dict) else {}
def effort(payload): """`effort` arrives as an object on some events and is absent on others.""" value = payload.get("effort") if isinstance(value, dict): return value.get("level") return value if isinstance(value, str) else None
def main(): try: payload = json.load(sys.stdin) except Exception: payload = {} if not isinstance(payload, dict): payload = {}
event = payload.get("hook_event_name")
# The receiver's vocabulary first, then everything observed alongside it. # A receiver reads the fields it knows and ignores the rest, which is what # lets one wire carry both a question and a measurement. record = { "asks": "report", "asker": ASKER, "version": VERSION, "observed": OBSERVED.get(event, "noted"), "session": payload.get("session_id") or "", "context": payload.get("agent_id"), "kind": payload.get("agent_type"), "call": payload.get("tool_use_id"), "epoch": round(time.time(), 3), "keys": sorted(payload), "effort": effort(payload), "cwd": payload.get("cwd"), } for name in SCALARS: value = payload.get(name) if isinstance(value, (str, int, bool)): record[name] = value
# A subagent's own transcript is written at a path derived from its id, # and an internal fork of the harness is given an id and no transcript. # Whether the promised file exists is what tells the two apart. promised = payload.get("agent_transcript_path") if isinstance(promised, str) and promised: record["agent_transcript_exists"] = os.path.exists(promised)
answer = ask(record)
# A receiver that could not do what was asked says why. Swallowing that # leaves an agent with no name and no way to find out that it should have # had one. if answer.get("trouble"): complain(RuntimeError(answer["trouble"]))
if answer.get("identity"): # Both halves, because they are one thing: who the agent is, and how # it says so to something asking. A client that prints a URL says # nothing about how a URL gets authorized here — that is this # project's mechanism, so this is where it is named. print( json.dumps( { "hookSpecificOutput": { "hookEventName": event, "additionalContext": ( "Your agent identity on this machine is " f"{answer['identity']}.\n" "When a tool prints an authorization URL and waits, " "run `didbot confirm <that URL> --as " f"{answer['identity']}` to authorize it as yourself." ), } } ) )
def complain(error): """Write down why this hook could not do its job.
A hook must not break a session, so it cannot raise. But a hook that swallows its own failure is indistinguishable from a harness that never called it, which is a much worse place to debug from than a file with a traceback in it. """ try: base = os.environ.get("CLAUDE_PLUGIN_DATA") or os.environ.get("TMPDIR") or "/tmp" os.makedirs(base, exist_ok=True) with open(os.path.join(base, "hook-errors.log"), "a") as handle: handle.write( time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + " " + repr(error) + "\n" + "".join(traceback.format_exception(error)) ) except Exception: pass
if __name__ == "__main__": try: main() except Exception as error: # noqa: BLE001 - a hook may not raise complain(error)