Hooks stay light: per-tool meter path imports no worker or git code; tools/measure_hooks.py. done: timing
This commit is contained in:
1 parent
0377407a78
commit
424993fa9e
5 files changed
+81
-29
No files matched your search
@@ -17,7 +17,7 @@ canon/orchestration-tools.json. Per-session state is in <state>/sessions/<id>.me
|
|||||||
every counted event is also appended to <state>/orchestration.jsonl for the unit record. Every entry point
|
every counted event is also appended to <state>/orchestration.jsonl for the unit record. Every entry point
|
||||||
fails open (the caller wraps it): an error here must never hold up the user's tool.
|
fails open (the caller wraps it): an error here must never hold up the user's tool.
|
||||||
"""
|
"""
|
||||||
import fcntl, json, os, re, shlex, time, uuid
|
import fcntl, json, os, re, shlex, time
|
||||||
|
|
||||||
from . import paths, store
|
from . import paths, store
|
||||||
|
|
||||||
@@ -408,8 +408,7 @@ def _norm(cmd):
|
|||||||
|
|
||||||
|
|
||||||
def _is_worker(payload, sess, m):
|
def _is_worker(payload, sess, m):
|
||||||
from . import workers
|
return bool(m.get("worker") or sess.get("subagent") or store.is_subagent_payload(payload))
|
||||||
return bool(m.get("worker") or sess.get("subagent") or workers.is_subagent_payload(payload))
|
|
||||||
|
|
||||||
|
|
||||||
def _transcript_model(path):
|
def _transcript_model(path):
|
||||||
@@ -471,11 +470,11 @@ def _before(payload, host=None):
|
|||||||
c = cfg()
|
c = cfg()
|
||||||
if not c["enabled"]:
|
if not c["enabled"]:
|
||||||
return {}
|
return {}
|
||||||
from . import watch, workers
|
from . import watch
|
||||||
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
tool, cmd, _ev, cwd, sid = watch.extract(payload)
|
||||||
host = host or store.tool() or "claude-code"
|
host = host or store.tool() or "claude-code"
|
||||||
hd = host_data(host)
|
hd = host_data(host)
|
||||||
if not hd or workers.is_subagent_payload(payload):
|
if not hd or store.is_subagent_payload(payload):
|
||||||
return {}
|
return {}
|
||||||
sid = sid or "cwd-" + cwd
|
sid = sid or "cwd-" + cwd
|
||||||
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
||||||
@@ -579,6 +578,7 @@ def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd):
|
|||||||
m["refusals"] += 1
|
m["refusals"] += 1
|
||||||
_event(m, sid, "refusal", why="route", tool=tool)
|
_event(m, sid, "refusal", why="route", tool=tool)
|
||||||
return {"deny": route_text()}
|
return {"deny": route_text()}
|
||||||
|
import uuid
|
||||||
run_id = uuid.uuid4().hex[:8]
|
run_id = uuid.uuid4().hex[:8]
|
||||||
worker = model or own or "(inherited)"
|
worker = model or own or "(inherited)"
|
||||||
against = None
|
against = None
|
||||||
@@ -619,11 +619,11 @@ def after(payload, host=None):
|
|||||||
c = cfg()
|
c = cfg()
|
||||||
if not c["enabled"]:
|
if not c["enabled"]:
|
||||||
return {}
|
return {}
|
||||||
from . import watch, workers
|
from . import watch
|
||||||
tool, cmd, ev, cwd, sid = watch.extract(payload)
|
tool, cmd, ev, cwd, sid = watch.extract(payload)
|
||||||
host = host or store.tool() or "claude-code"
|
host = host or store.tool() or "claude-code"
|
||||||
hd = host_data(host)
|
hd = host_data(host)
|
||||||
if not hd or workers.is_subagent_payload(payload):
|
if not hd or store.is_subagent_payload(payload):
|
||||||
return {}
|
return {}
|
||||||
sid = sid or "cwd-" + cwd
|
sid = sid or "cwd-" + cwd
|
||||||
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {})
|
||||||
|
|||||||
@@ -78,6 +78,19 @@ def tool():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def is_subagent_payload(payload):
|
||||||
|
"""Is this hook call from a worker: started by `sisi delegate`, or marked by the host as a subagent? Kept here
|
||||||
|
(not in workers.py) so the per-tool hooks need not import the worker code."""
|
||||||
|
if os.environ.get("SISI_WORKER_RUN"):
|
||||||
|
return True
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return False
|
||||||
|
if payload.get("agent_id") or payload.get("agentId") or payload.get("agent_transcript_path"):
|
||||||
|
return True
|
||||||
|
tp = str(payload.get("transcript_path") or "")
|
||||||
|
return "/subagents/" in tp or tp.endswith("/subagents")
|
||||||
|
|
||||||
|
|
||||||
def session_id():
|
def session_id():
|
||||||
return os.environ.get("SISI_SESSION_ID") or None
|
return os.environ.get("SISI_SESSION_ID") or None
|
||||||
|
|
||||||
|
|||||||
+29
-14
@@ -14,7 +14,13 @@ Both hooks fail open: any error is logged and the tool call proceeds.
|
|||||||
"""
|
"""
|
||||||
import json, os, re, time
|
import json, os, re, time
|
||||||
|
|
||||||
from . import gitutil, paths, store
|
from . import paths, store
|
||||||
|
|
||||||
|
|
||||||
|
def _git():
|
||||||
|
"""gitutil, imported when a measurement needs it: a hook call that only meters (most tools) must stay light."""
|
||||||
|
from . import gitutil
|
||||||
|
return gitutil
|
||||||
|
|
||||||
BEFORE_EVENTS = {"PreToolUse", "BeforeTool", "preToolUse", "beforeShellExecution", "tool_call"}
|
BEFORE_EVENTS = {"PreToolUse", "BeforeTool", "preToolUse", "beforeShellExecution", "tool_call"}
|
||||||
AFTER_EVENTS = {"PostToolUse", "AfterTool", "postToolUse", "afterShellExecution",
|
AFTER_EVENTS = {"PostToolUse", "AfterTool", "postToolUse", "afterShellExecution",
|
||||||
@@ -57,8 +63,8 @@ def is_shell(tool, cmd):
|
|||||||
|
|
||||||
|
|
||||||
def _may_write(cmd):
|
def _may_write(cmd):
|
||||||
from . import gate
|
from . import attribution # the classifier the gate uses (gate._shell_may_write is this function)
|
||||||
return gate._shell_may_write(cmd)
|
return attribution.shell_may_write(cmd)
|
||||||
|
|
||||||
|
|
||||||
def snap_file(sid, kind):
|
def snap_file(sid, kind):
|
||||||
@@ -113,9 +119,8 @@ def note_shell(sess, cmd, payload):
|
|||||||
its hook payload came from a subagent (an agent id or a subagent transcript path). `sisi retro`
|
its hook payload came from a subagent (an agent id or a subagent transcript path). `sisi retro`
|
||||||
reads this from the session record to quarantine what a subagent records; it never trusts the
|
reads this from the session record to quarantine what a subagent records; it never trusts the
|
||||||
caller's environment. The command text itself is not kept."""
|
caller's environment. The command text itself is not kept."""
|
||||||
from . import workers
|
|
||||||
shells = sess.setdefault("shells", [])
|
shells = sess.setdefault("shells", [])
|
||||||
shells.append({"retro": "retro" in (cmd or ""), "subagent": bool(workers.is_subagent_payload(payload)),
|
shells.append({"retro": "retro" in (cmd or ""), "subagent": bool(store.is_subagent_payload(payload)),
|
||||||
"ts": time.time()})
|
"ts": time.time()})
|
||||||
del shells[:-8]
|
del shells[:-8]
|
||||||
|
|
||||||
@@ -130,7 +135,7 @@ def before(payload):
|
|||||||
store.save_session(sid, sess)
|
store.save_session(sid, sess)
|
||||||
if _may_write(cmd) is False:
|
if _may_write(cmd) is False:
|
||||||
return # provably read-only (incl. sisi's own and git commit): no measurement paid
|
return # provably read-only (incl. sisi's own and git commit): no measurement paid
|
||||||
snap = gitutil.snapshot(cwd)
|
snap = _git().snapshot(cwd)
|
||||||
_save(snap_file(sid, "watch"), {"root": snap["root"], "files": snap["files"],
|
_save(snap_file(sid, "watch"), {"root": snap["root"], "files": snap["files"],
|
||||||
"command": (cmd or "")[:500], "ts": time.time()})
|
"command": (cmd or "")[:500], "ts": time.time()})
|
||||||
|
|
||||||
@@ -151,16 +156,16 @@ def after(payload):
|
|||||||
os.unlink(snap_file(sid, "watch"))
|
os.unlink(snap_file(sid, "watch"))
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
root = pend.get("root") or gitutil.root(cwd) or cwd
|
root = pend.get("root") or _git().root(cwd) or cwd
|
||||||
now = gitutil.snapshot(root)
|
now = _git().snapshot(root)
|
||||||
changed = gitutil.snapshot_diff(pend, now)
|
changed = _git().snapshot_diff(pend, now)
|
||||||
if changed:
|
if changed:
|
||||||
note_edit(sess, changed, root)
|
note_edit(sess, changed, root)
|
||||||
store.save_session(sid, sess)
|
store.save_session(sid, sess)
|
||||||
|
|
||||||
|
|
||||||
def pend_root(sess, cwd):
|
def pend_root(sess, cwd):
|
||||||
return gitutil.root(cwd) or sess.get("req_project") or cwd
|
return _git().root(cwd) or sess.get("req_project") or cwd
|
||||||
|
|
||||||
|
|
||||||
def consume_pending(sess, sid, cwd):
|
def consume_pending(sess, sid, cwd):
|
||||||
@@ -178,7 +183,7 @@ def consume_pending(sess, sid, cwd):
|
|||||||
|
|
||||||
|
|
||||||
def save_pass_snapshot(sid, cwd):
|
def save_pass_snapshot(sid, cwd):
|
||||||
snap = gitutil.snapshot(cwd)
|
snap = _git().snapshot(cwd)
|
||||||
_save(snap_file(sid, "pass"), snap)
|
_save(snap_file(sid, "pass"), snap)
|
||||||
return snap
|
return snap
|
||||||
|
|
||||||
@@ -188,7 +193,7 @@ def changed_since_pass(sid, cwd):
|
|||||||
pend = _load(snap_file(sid, "pass"))
|
pend = _load(snap_file(sid, "pass"))
|
||||||
if pend is None:
|
if pend is None:
|
||||||
return None
|
return None
|
||||||
return gitutil.snapshot_diff(pend, gitutil.snapshot(cwd))
|
return _git().snapshot_diff(pend, _git().snapshot(cwd))
|
||||||
|
|
||||||
|
|
||||||
_COMMIT_RE = re.compile(r"(?:^|[;&|(]\s*)(?:\w+=\S+\s+)*git\s+(?:(?:-C|-c)\s+\S+\s+|--[\w-]+\s+)*(?:commit|merge)\b")
|
_COMMIT_RE = re.compile(r"(?:^|[;&|(]\s*)(?:\w+=\S+\s+)*git\s+(?:(?:-C|-c)\s+\S+\s+|--[\w-]+\s+)*(?:commit|merge)\b")
|
||||||
@@ -213,6 +218,17 @@ def commit_notice(payload):
|
|||||||
"`sisi verify` first (a notice, not a block)." % c.get("id"))
|
"`sisi verify` first (a notice, not a block)." % c.get("id"))
|
||||||
|
|
||||||
|
|
||||||
|
def _read_payload():
|
||||||
|
try:
|
||||||
|
import sys
|
||||||
|
if sys.stdin is None or sys.stdin.isatty():
|
||||||
|
return {}
|
||||||
|
d = json.loads(store.read_stdin() or "{}")
|
||||||
|
return d if isinstance(d, dict) else {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
def meter(payload, after_call, host=None):
|
def meter(payload, after_call, host=None):
|
||||||
"""The orchestration meter's answer for one tool call ({"deny": text} / {"context": text} / {}); never
|
"""The orchestration meter's answer for one tool call ({"deny": text} / {"context": text} / {}); never
|
||||||
raises: an error inside the meter lets the call through."""
|
raises: an error inside the meter lets the call through."""
|
||||||
@@ -268,8 +284,7 @@ def render_claude(out, event):
|
|||||||
|
|
||||||
def main(args=()):
|
def main(args=()):
|
||||||
try:
|
try:
|
||||||
from . import gate
|
payload = _read_payload()
|
||||||
payload = gate._read_payload()
|
|
||||||
_tool, _cmd, ev, _cwd, _sid = extract(payload)
|
_tool, _cmd, ev, _cwd, _sid = extract(payload)
|
||||||
out = run(payload, args)
|
out = run(payload, args)
|
||||||
before_call = "--before" in args or ev in BEFORE_EVENTS
|
before_call = "--before" in args or ev in BEFORE_EVENTS
|
||||||
|
|||||||
+1
-8
@@ -1415,14 +1415,7 @@ def _cached_candidates(records=None):
|
|||||||
|
|
||||||
|
|
||||||
def is_subagent_payload(payload):
|
def is_subagent_payload(payload):
|
||||||
if os.environ.get("SISI_WORKER_RUN"):
|
return store.is_subagent_payload(payload)
|
||||||
return True
|
|
||||||
if not isinstance(payload, dict):
|
|
||||||
return False
|
|
||||||
if payload.get("agent_id") or payload.get("agentId") or payload.get("agent_transcript_path"):
|
|
||||||
return True
|
|
||||||
tp = str(payload.get("transcript_path") or "")
|
|
||||||
return "/subagents/" in tp or tp.endswith("/subagents")
|
|
||||||
|
|
||||||
|
|
||||||
def _with_facts(lines):
|
def _with_facts(lines):
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""Median wall and CPU time of the per-tool hooks (`sisi watch`), against a bare interpreter start. Run it when the
|
||||||
|
machine is quiet; under load every process start is slow and the baseline line shows by how much."""
|
||||||
|
import subprocess, tempfile, os, json, time, statistics, sys
|
||||||
|
T=tempfile.mkdtemp(); proj=os.path.join(T,"p"); os.makedirs(proj); subprocess.run(["git","init","-q"],cwd=proj)
|
||||||
|
env=dict(os.environ,SISI_STATE=T+"/s",SISI_DATA=T+"/d",SISI_LIB=T+"/l",SISI_TOOL="claude-code")
|
||||||
|
B="bin/sisi"
|
||||||
|
import resource
|
||||||
|
def one(args,inp=""):
|
||||||
|
r0=resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||||
|
t=time.perf_counter(); subprocess.run(args,input=inp,text=True,capture_output=True,env=env); w=(time.perf_counter()-t)*1000
|
||||||
|
r1=resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||||
|
cpu=((r1.ru_utime-r0.ru_utime)+(r1.ru_stime-r0.ru_stime))*1000
|
||||||
|
return (w,cpu)
|
||||||
|
def payload(ev,tool,inp,extra=None):
|
||||||
|
d={"session_id":"tm","cwd":proj,"hook_event_name":ev,"tool_name":tool,"tool_input":inp}; d.update(extra or {}); return json.dumps(d)
|
||||||
|
os.makedirs(T+"/d",exist_ok=True); open(T+"/d/config.json","w").write(json.dumps({"orchestrate":{"direct_calls":100000,"direct_chars":10**12}}))
|
||||||
|
one([sys.executable,B,"prompt","--tool","claude-code"],json.dumps({"session_id":"tm","cwd":proj,"prompt":"x"*30}))
|
||||||
|
N=int(sys.argv[1]) if len(sys.argv)>1 else 40
|
||||||
|
def med(f):
|
||||||
|
xs=[f() for _ in range(N)]; return statistics.median(x[0] for x in xs), statistics.median(x[1] for x in xs)
|
||||||
|
base=med(lambda: one([sys.executable,"-c","import json,re,os,time"]))
|
||||||
|
print("baseline python start (json,re,os,time imported): wall %.1f ms, cpu %.1f ms load %.1f"%(base[0],base[1],os.getloadavg()[0]))
|
||||||
|
cases={"before Read":("PreToolUse","Read",{"file_path":"/x"},None),
|
||||||
|
"after Read (500 chars)":("PostToolUse","Read",{"file_path":"/x"},{"tool_response":"x"*500}),
|
||||||
|
"before Bash ls":("PreToolUse","Bash",{"command":"ls"},None),
|
||||||
|
"after Bash ls":("PostToolUse","Bash",{"command":"ls"},{"tool_response":{"stdout":"a","exit_code":0}}),
|
||||||
|
"before Edit":("PreToolUse","Edit",{"file_path":"/x"},None),
|
||||||
|
"after Edit":("PostToolUse","Edit",{"file_path":"/x"},{"tool_response":"ok"})}
|
||||||
|
for name,(ev,tool,inp,ex) in cases.items():
|
||||||
|
m=med(lambda: one([sys.executable,B,"watch","--tool","claude-code"],payload(ev,tool,inp,ex)))
|
||||||
|
print("%-26s median wall %6.1f ms cpu %5.1f ms (cpu over a bare python start: %.1f ms)"%(name,m[0],m[1],m[1]-base[1]))
|
||||||
Reference in new issue
Block a user