Experience-Driven Black-Box Cost Control for Coding Agents
Python agentic-aiagentic-codingai-codingai-coding-assistantanthropicartificial-intelligenceclaude-codecodexcoding-agentcoding-agentscost-optimizationcost-reductiondeveloper-toolsgithub-copilotllmopen-sourceopenaiproductivitytoken-optimization
Address the Cursor review so the upstream PR can merge.
Shadowfb2b62a500a5
diff --git a/README.md b/README.mdindex e86c6a1..d6169bc 100644--- a/README.md+++ b/README.md@@ -172,7 +172,9 @@ Reload Cursor, confirm `tokeneconomizer` appears in Customize, then send a prompCheck its state from a terminal with `~/.tokeneconomizer/bin/te --host cursor status`. Cursor'spublished hooks provide session, prompt, tool-result and completion events. Its transcript formatand per-session token usage are not a supported public interface, so the adapter records needed-hook events locally and reports session cost as unavailable.+hook events locally and reports session cost as unavailable. Cursor support is macOS and Linux+only: on Windows, Cursor runs hook commands through PowerShell, and this plugin's launcher is a+POSIX shell script.**opencode** (experimental)@@ -211,16 +213,16 @@ uninstalling, using Copilot with your own model key, and troubleshooting.| Copilot CLI | 1.0.83 to 1.0.102 | not supported || Pi | 1.2.0 to 1.3.0 | 0.99.x: load the extension by path (below) || Cursor Agent (experimental) | current command-hook schema | no version range verified |-| opencode (experimental) | 1.19.5, 2.1.4, and 2.2.0 | not tested |+| opencode (experimental) | 1.19.5 and 2.2.0 | not tested |-The listed version ranges were tested at their oldest and newest releases; newer releases have not-been tested. OpenCode versions tested are listed individually.+The commands above were tested on the oldest and newest version in each range; newer versions+have not been tested yet.- **Codex before 0.141.0** does not run plugin hooks at all.- **Pi 0.99.x**: instead of `pi install`, clone the repository and start each session with`pi --extension /path/to/TokenEconomizer/plugin/pi/tokeneconomizer.ts`, using your clone'sfull path; `git pull` in the clone updates it.-- **opencode** support is experimental: it was tested on 1.19.5, 2.1.4, and 2.2.0, and not in the+- **opencode** support is experimental: it was tested on 1.19.5 and 2.2.0 only, and not in the2.x terminal UI.- **Cursor Agent** support is experimental. Cursor 3.24.9 loaded the local plugin, but hook deliveryfrom a live Agent session has not yet been verified.diff --git a/docs/PLUGIN.md b/docs/PLUGIN.mdindex 30f9a09..147be94 100644--- a/docs/PLUGIN.md+++ b/docs/PLUGIN.md@@ -54,7 +54,7 @@ Every hook fails open: any error becomes an empty output (no change) and a trace| Unit of work | one benchmark task | a **session** for micro-skills and tool pruning; a **prompt-turn** for the loop guard | In interactive use a person already splits work into short turns. A whole session folded as one trajectory would look stuck merely by being long || Learning signal | the official grader's `resolved` | the envelope learns from turns that **ended green**: the agent stopped on its own, was not stopped by the guard, and no verification after its last edit failed | There is no grader. Micro-skills and evidence pruning never needed one || Injection channel | a prefix on the task prompt | `SessionStart` `additionalContext` | Verified to reach the model (§3) |-| Tool removal | `--disallowed-tools` / Codex config at launch | a **deny list** is applied by default after evidence forms and repository sessions have been idle longer than a prompt cache lives (§3), and announced at the next session start (`toolprune=propose` waits for approval instead), written to the repository's own settings file — tools in `.claude/settings.local.json`, Codex capability packages in `.codex/config.toml`, Copilot MCP servers in `.github/copilot/settings.local.json` — effective from the **next** session | The plugin launches nothing. A session keeps the tools it started with, but a conversation resumed after a change sends the new ones, re-writing its cached prefix, hence the idle wait. Each agent's file can express a different unit (§3) |+| Tool removal | `--disallowed-tools` / Codex config at launch | a **deny list**, applied by default once the evidence forms it and the repository's sessions have been idle longer than a prompt cache lives (§3), and announced at the next session start (`toolprune=propose` waits for approval instead), written to the repository's own settings file — tools in `.claude/settings.local.json`, Codex capability packages in `.codex/config.toml`, Copilot MCP servers in `.github/copilot/settings.local.json` — effective from the **next** session | The plugin launches nothing. A session keeps the tools it started with, but a conversation resumed after a change sends the new ones, re-writing its cached prefix, hence the idle wait. Each agent's file can express a different unit (§3) || Pruning candidates | `toolprune.tools.INAPPLICABLE_TOOLS` — orchestration, Q&A, plan mode, web — "inapplicable by construction" for a sealed headless task | nothing is inapplicable by construction; only **evidence** (never used, and unused over `toolprune_evidence` prompts (10) across at least `toolprune_min_sessions` sessions (2), or over `toolprune_sessions` sessions (5)) proposes a tool, and a person's tools — AskUserQuestion, plan mode, sub-agents, the web — are protected | A person asks questions, plans and browses in a real session. A deny rule the plugin wrote for a tool that has since become protected is given back at the next fold || Network | every arm, baseline included, carries an answer-key guard — a `PreToolUse` hook and an `/etc/hosts` block refuse the benchmarks' upstream sources — and drops the web tools | **no guard**: no `PreToolUse` hook (on Pi, no `tool_call` handler), no blocked command or host; the web tools stay | A benchmark's answer is a fetch away. A real session has no answer key, and the web is part of the work || Who decides a turn is stuck | in the guard's arms, the trace judge, woken by the rule gate or by a turn past the envelope (the agents ran under a turn cap); without a judge, the strict rule | **always the judge** when the guard is on, woken only by a sign of trouble (a repeated failure, or dense errors) after `min_turns` calls, and never before the repository has an envelope; a `productive` or ambiguous verdict spares the turn (at the `aggressive` preset an ambiguous one past the envelope gets the redirect). The hard backstop (far past the envelope AND the strict stall rule) still acts without it. While the agent's model calls are paused, the judge gives no verdict and only the backstop acts | The rule alone redirected turns that had found their cause and were working around it (§5); interactive turns outrun a small envelope all the time, so the envelope alone wakes nothing |@@ -580,7 +580,8 @@ open-vocabulary. On a repository you do not trust, leave micro-skills off (the dverified. Cursor's transcript format is undocumented, and its hook payloads do not exposesession token usage. The adapter records prompt and tool events for learning and loop detection;session and side-call costs are reported as unavailable. Tool pruning is not implemented for- Cursor.+ Cursor. macOS and Linux only: Windows Cursor runs hooks through PowerShell, and the launcher+ is a POSIX shell script.* **Known gaps:*** `codex exec` prints no hook messages, so a headless Codex run shows no notice; `te status`counts it afterwards. On Claude Code the notice reaches the conversation and `claude -p`'sdiff --git a/plugin/README.md b/plugin/README.mdindex 3af995f..e634ee4 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -322,7 +322,9 @@ events used by the adapter. The transcript format is private and its hooks do notoken usage. TokenEconomizer records only the relevant hook events under its private state folder,uses them to learn repository facts and watch for loops, and reports Cursor session cost asunavailable. The loop guard's model calls use `cursor-agent` in read-only Ask mode; their token-usage is also unavailable in the current CLI output.+usage is also unavailable in the current CLI output. Cursor support is macOS and Linux only.+On Windows, Cursor runs these hook commands through PowerShell, which cannot run the POSIX+`te-hook` launcher.Tool pruning follows the global setting and is not applied to Cursor. Cursor commands run from a terminal:`~/.tokeneconomizer/bin/te --host cursor <command>`.@@ -494,7 +496,7 @@ and are shared by every agent working in it. The examples use Claude Code's form| Mechanism | Key | `on` means | Other values ||---|---|---|---|| Micro-skills (off by default) | `microskills` | `envfacts+distiller`: facts found without model calls, plus a model proposing facts every `microskills_propose_every` sessions | `off`; `envfacts`: only the facts found without model calls; `distiller`: only the proposer |-| Tool pruning (on by default) | `toolprune` | `auto`: applied without asking once your sessions have been idle for `toolprune_quiet_minutes` (or a day after it formed), from the next session, which announces it | `off`: never remove tools or MCP servers; `propose`: only proposed, applied when you run `toolprune apply` |+| Tool pruning | `toolprune` | `auto`: applied without asking once your sessions have been idle for `toolprune_quiet_minutes` (or a day after it formed), from the next session, which announces it | `off`; `propose`: only proposed, applied when you run `toolprune apply` || Loop guard | `loopguard` | `nudge`: a judge model decides whether a looping turn is stuck; if so, up to `loopguard_nudges` mid-turn redirects, then a notice to you if the turn is still stuck | `off` (no judge either); `stop` is read as `nudge`, with a warning |**Tune a mechanism:**diff --git a/tests/test_cursor.py b/tests/test_cursor.pyindex 93da637..f4f0fc6 100644--- a/tests/test_cursor.py+++ b/tests/test_cursor.py@@ -3,17 +3,15 @@ import jsonimport osfrom pathlib import Path+import pytest+from tokeneconomizer import trace-from tokeneconomizer.plugin.config import LiveConfig-from tokeneconomizer.plugin.hosts import Cursor+from tokeneconomizer.plugin.hosts import (+ ClaudeCode, Codex, Copilot, Cursor, OpenCode, Pi,+)from tokeneconomizer.plugin.hook import run-from tokeneconomizer.plugin.paths import state_root---def test_tool_pruning_can_be_disabled_by_a_user_config():- config = LiveConfig()- assert config.toolprune == "auto"- assert config.set("toolprune", "off") and config.toolprune == "off"+from tokeneconomizer.plugin.paths import repo_identity, repo_state_dir+from tokeneconomizer.plugin.store import Storedef test_cursor_translates_prompt_and_tool_hook_schemas(tmp_path):@@ -68,36 +66,6 @@ def test_cursor_plugin_declares_all_supported_hook_events():for entries in hooks.values() for hook in entries)-def test_cursor_records_only_allowlisted_repository_events(tmp_path):- allowed = tmp_path / "allowed"- (allowed / ".git" / "info").mkdir(parents=True)- (allowed / ".git" / "HEAD").write_text("ref: refs/heads/main\n")- (allowed / ".git" / "config").write_text(- '[remote "origin"]\n\turl = https://github.com/acme/widget.git\n')- excluded = tmp_path / "excluded"- (excluded / ".git" / "info").mkdir(parents=True)- (excluded / ".git" / "HEAD").write_text("ref: refs/heads/main\n")- (excluded / ".git" / "config").write_text(- '[remote "origin"]\n\turl = https://github.com/acme/other.git\n')- state = tmp_path / "state"- os.makedirs(state)- (state / "config.json").write_text(json.dumps({"repositories": [str(allowed)]}))- env = {"TOKENECONOMIZER_HOME": str(state), "TE_LOOPGUARD": "off",- "GIT_CEILING_DIRECTORIES": str(tmp_path), "PATH": os.environ.get("PATH", "")}-- event = {"hook_event_name": "beforeSubmitPrompt", "conversation_id": "conversation-a",- "generation_id": "generation-a", "prompt": "Fix the issue",- "workspace_roots": [str(excluded)]}- assert run(event, env, host_hint="cursor") == {}- assert not os.path.exists(state_root(env) + "/cursor-sessions")-- event["workspace_roots"] = [str(allowed)]- assert run(event, env, host_hint="cursor") == {}- spool = state / "cursor-sessions" / "conversation-a.jsonl"- rows = [json.loads(line) for line in spool.read_text().splitlines()]- assert len(rows) == 1 and rows[0]["prompt"] == "Fix the issue"--def test_cursor_events_reconstruct_tool_results_and_count_prompts(tmp_path):source, target = tmp_path / "events.jsonl", tmp_path / "trace.jsonl"events = [@@ -118,3 +86,70 @@ def test_cursor_events_reconstruct_tool_results_and_count_prompts(tmp_path):("Bash", {"command": "pytest"}, True),("Read", {"file_path": "missing"}, False),]+++def cursor_env(tmp_path):+ repo = tmp_path / "repo"+ (repo / ".git" / "info").mkdir(parents=True)+ (repo / ".git" / "HEAD").write_text("ref: refs/heads/main\n")+ (repo / ".git" / "config").write_text(+ '[remote "origin"]\n\turl = https://github.com/acme/widget.git\n')+ state = tmp_path / "state"+ state.mkdir(parents=True, exist_ok=True)+ env = {+ "TOKENECONOMIZER_HOME": str(state),+ "CURSOR_PROJECT_DIR": str(repo),+ "TE_LOOPGUARD": "off",+ "PATH": os.environ.get("PATH", ""),+ "GIT_CEILING_DIRECTORIES": str(tmp_path),+ }+ store = Store(repo_state_dir(repo_identity(str(repo), env), "cursor", env))+ return str(repo), env, store++[email protected]("host_cls", [ClaudeCode, Codex, Copilot, OpenCode, Pi])+def test_host_stopped_normally_default(host_cls):+ assert host_cls().stopped_normally({}) is True++[email protected]("status,expected_normal", [+ ("completed", True), ("aborted", False), ("error", False), (None, False), ("unknown", False),+])+def test_cursor_stop_lifecycle_status_handling(cursor_env, status, expected_normal):+ repo, env, store = cursor_env+ env = dict(env, TE_LOOPGUARD="on")+ base = {"conversation_id": "c1", "generation_id": "g1", "workspace_roots": [repo]}+ run(dict(base, hook_event_name="beforeSubmitPrompt", prompt="check"), env, host_hint="cursor")+ run(dict(base, hook_event_name="postToolUse", tool_name="Shell", tool_use_id="t1",+ tool_input={"command": "pytest"},+ tool_output=json.dumps({"output": "1 passed", "exitCode": 0})), env, host_hint="cursor")+ stop = dict(base, hook_event_name="stop")+ if status is not None:+ stop["status"] = status+ assert run(stop, env, host_hint="cursor") == {}++ sess = store.read("sessions/c1.json")+ assert sess and sess.get("turn") is None and len(sess.get("turns", [])) == 1+ assert sess["turns"][0]["resolved_proxy"] is expected_normal+ envelope = store.read("envelope.json") or {}+ assert envelope.get("resolved_turns", []) == ([1] if expected_normal else [])+++def test_cursor_native_shell_json_output_positive_and_negative(tmp_path, cursor_env):+ repo, env, _ = cursor_env+ base = {"conversation_id": "c-shell", "generation_id": "g-shell", "workspace_roots": [repo]}+ run(dict(base, hook_event_name="beforeSubmitPrompt", prompt="build & test"), env, host_hint="cursor")+ calls = [("t1", "make build", {"output": "ok\n", "exitCode": 0}),+ ("t2", "pytest -q", {"output": "failed\n", "exitCode": 1})]+ for tid, cmd, out in calls:+ run(dict(base, hook_event_name="postToolUse", tool_name="Shell", tool_use_id=tid,+ tool_input={"command": cmd}, tool_output=json.dumps(out)), env, host_hint="cursor")++ host = Cursor()+ tp = host.transcript(host.prepare(dict(base, session_id="c-shell"), env))+ trace_path = host.mechanism_trace(tp, str(tmp_path))+ assert trace.load_trajectory(trace_path) == [+ ("Bash", {"command": "make build"}, "ok\n", True),+ ("Bash", {"command": "pytest -q"}, "failed\n", False),+ ]diff --git a/tests/test_cursor_recording.py b/tests/test_cursor_recording.pynew file mode 100644index 0000000..9c0d182--- /dev/null+++ b/tests/test_cursor_recording.py@@ -0,0 +1,173 @@+"""Regression tests for Cursor hook recording lifecycle: enabled vs disabled."""+import io+import json+import os++import pytest++from tokeneconomizer.plugin import hook+from tokeneconomizer.plugin.hosts import RESULT_CAP, Cursor+from tokeneconomizer.plugin.paths import repo_identity+++def _call_hook(payload, env, host="cursor"):+ out = io.StringIO()+ ret = hook.main(["--host", host] if host else [], io.StringIO(json.dumps(payload)), out, env)+ return ret, json.loads(out.getvalue())+++def recording_env(tmp_path):+ repo = tmp_path / "repo"+ (repo / ".git" / "info").mkdir(parents=True)+ (repo / ".git" / "HEAD").write_text("ref: refs/heads/main\n")+ (repo / ".git" / "config").write_text(+ '[remote "origin"]\n\turl = https://github.com/acme/project.git\n'+ )+ state = tmp_path / "state"+ state.mkdir(parents=True)+ env = {+ "TOKENECONOMIZER_HOME": str(state),+ "GIT_CEILING_DIRECTORIES": str(tmp_path),+ "PATH": os.environ.get("PATH", ""),+ "TE_LOOPGUARD": "off",+ "TE_MICROSKILLS": "off",+ "TE_REPOMAP": "off",+ }+ return repo, state, env+++def _make_prompt_payload(repo, conversation_id="conv-rec-1"):+ return {+ "hook_event_name": "beforeSubmitPrompt",+ "conversation_id": conversation_id,+ "generation_id": "gen-p-1",+ "prompt": "Fix bug in payment handler",+ "workspace_roots": [str(repo)],+ "cwd": str(repo),+ }+++def _make_tool_payload(repo, conversation_id="conv-rec-1"):+ return {+ "hook_event_name": "postToolUse",+ "conversation_id": conversation_id,+ "generation_id": "gen-p-1",+ "tool_use_id": "tool-rec-1",+ "tool_name": "Shell",+ "tool_input": {"command": "npm test"},+ "tool_output": '{"exitCode":0,"output":"PASS test/pay.test.js"}',+ "workspace_roots": [str(repo)],+ "cwd": str(repo),+ }+++def test_cursor_records_prompt_and_tool_when_enabled(recording_env):+ repo, state, env = recording_env+ ret1, res1 = _call_hook(_make_prompt_payload(repo), env)+ assert ret1 == 0 and res1 == {}++ ret2, res2 = _call_hook(_make_tool_payload(repo), env)+ assert ret2 == 0 and res2 == {}++ spool = state / "cursor-sessions" / "conv-rec-1.jsonl"+ assert spool.exists()+ rows = [json.loads(line) for line in spool.read_text().splitlines() if line.strip()]+ assert len(rows) == 2+ assert rows[0]["hook_event_name"] == "UserPromptSubmit"+ assert rows[0]["prompt"] == "Fix bug in payment handler"+ assert rows[1]["hook_event_name"] == "PostToolUse"+ assert rows[1]["tool_response"] == {+ "content": "PASS test/pay.test.js",+ "exit_code": 0,+ "isError": False,+ }+++def test_global_config_disabled_creates_no_new_spool_and_does_not_append(recording_env):+ repo, state, env = recording_env+ (state / "config.json").write_text(json.dumps({"enabled": False}))++ ret1, res1 = _call_hook(_make_prompt_payload(repo, "conv-disabled-global"), env)+ assert ret1 == 0 and res1 == {}+ spool = state / "cursor-sessions" / "conv-disabled-global.jsonl"+ assert not spool.exists()++ spool.parent.mkdir(parents=True, exist_ok=True)+ spool.write_text('{"seed":true}\n')+ ret2, res2 = _call_hook(_make_tool_payload(repo, "conv-disabled-global"), env)+ assert ret2 == 0 and res2 == {}+ assert spool.read_text() == '{"seed":true}\n'+++def test_repo_config_disabled_creates_no_new_spool_and_does_not_append(recording_env):+ repo, state, env = recording_env+ repo_id = repo_identity(str(repo), env)+ repo_cfg_dir = state / "repos" / repo_id.key+ repo_cfg_dir.mkdir(parents=True, exist_ok=True)+ (repo_cfg_dir / "config.json").write_text(json.dumps({"enabled": False}))++ ret1, res1 = _call_hook(_make_prompt_payload(repo, "conv-disabled-repo"), env)+ assert ret1 == 0 and res1 == {}+ spool = state / "cursor-sessions" / "conv-disabled-repo.jsonl"+ assert not spool.exists()++ spool.parent.mkdir(parents=True, exist_ok=True)+ spool.write_text('{"seed":true}\n')+ ret2, res2 = _call_hook(_make_tool_payload(repo, "conv-disabled-repo"), env)+ assert ret2 == 0 and res2 == {}+ assert spool.read_text() == '{"seed":true}\n'+++def test_env_disable_and_sidecall_skip_recording(recording_env):+ repo, state, env = recording_env++ env_disable = dict(env, TE_DISABLE="1")+ ret1, res1 = _call_hook(_make_prompt_payload(repo, "conv-env-skip"), env_disable)+ assert ret1 == 0 and res1 == {}+ spool = state / "cursor-sessions" / "conv-env-skip.jsonl"+ assert not spool.exists()++ env_sidecall = dict(env, TE_SIDECALL="1")+ ret2, res2 = _call_hook(_make_tool_payload(repo, "conv-env-skip"), env_sidecall)+ assert ret2 == 0 and res2 == {}+ assert not spool.exists()+++def test_recording_keeps_adapter_fields_and_drops_user_email(recording_env):+ repo, state, env = recording_env+ payload = _make_prompt_payload(repo, "conv-fields")+ payload["user_email"] = "[email protected]"+ payload["CURSOR_USER_EMAIL"] = "[email protected]"+ assert _call_hook(payload, env) == (0, {})+ spool = state / "cursor-sessions" / "conv-fields.jsonl"+ row = json.loads(spool.read_text().splitlines()[0])+ assert row["hook_event_name"] == "UserPromptSubmit"+ assert row["prompt"] == "Fix bug in payment handler"+ assert "user_email" not in row+ assert "CURSOR_USER_EMAIL" not in row+ assert "user_email" not in json.dumps(row)+++def test_recording_caps_tool_output(recording_env):+ repo, state, env = recording_env+ payload = _make_tool_payload(repo, "conv-cap")+ payload["tool_output"] = json.dumps({"exitCode": 0, "output": "x" * (RESULT_CAP + 40)})+ assert _call_hook(payload, env) == (0, {})+ row = json.loads((state / "cursor-sessions" / "conv-cap.jsonl").read_text().splitlines()[0])+ assert row["tool_response"]["content"] == "x" * RESULT_CAP+ assert "user_email" not in row+++def test_settle_deletes_processed_session_file(tmp_path):+ spool = tmp_path / "cursor-sessions" / "conv.jsonl"+ spool.parent.mkdir()+ spool.write_text("{}\n")+ other = tmp_path / "elsewhere" / "conv.jsonl"+ other.parent.mkdir()+ other.write_text("{}\n")+ host = Cursor()+ host.settle(str(spool))+ host.settle(str(other))+ assert not spool.exists()+ assert other.exists()diff --git a/tokeneconomizer/plugin/config.py b/tokeneconomizer/plugin/config.pyindex 315aa4b..c31b3cc 100644--- a/tokeneconomizer/plugin/config.py+++ b/tokeneconomizer/plugin/config.py@@ -38,8 +38,6 @@ person can tune by hand:* toolprune_protect -- tools never proposed, by name or pattern (`mcp__headroom__*`),comma-separated; a deny rule the plugin added for one isremoved at the next fold;- * repositories -- optional absolute checkout paths where hooks are active;- empty means all repositories;* toolprune_quiet_minutes -- how long every session of the repository must have been idlebefore `auto` writes a deny list (0: at once), so that noconversation resumed with a warm prompt cache loses it;@@ -157,7 +155,6 @@ class LiveConfig:toolprune_sessions: int = 5toolprune_quiet_minutes: int = 60toolprune_protect: list = field(default_factory=list)- repositories: list = field(default_factory=list)loopguard: str = "nudge"loopguard_aggr: str = "default"loopguard_nudges: int = 1diff --git a/tokeneconomizer/plugin/controller.py b/tokeneconomizer/plugin/controller.pyindex d697314..5a94fd6 100644--- a/tokeneconomizer/plugin/controller.py+++ b/tokeneconomizer/plugin/controller.py@@ -80,10 +80,6 @@ class LiveController:# leave an "unknown" session behind.if not self.cfg.enabled or not self.host.session_id(self.p):return {}- if self.cfg.repositories:- allowed = {os.path.realpath(path) for path in self.cfg.repositories}- if os.path.realpath(self.ctx.repo.root) not in allowed:- return {}self.ctx.settle()self.cfg = self.ctx.configevent = self.p.get("hook_event_name") or ""@@ -274,7 +270,7 @@ class LiveController:if self.cfg.loopguard == "off" or self.p.get("stop_hook_active"):return {}s = self._session()- summary = self._close_turn(s, stopped_normally=True)+ summary = self._close_turn(s, stopped_normally=self.host.stopped_normally(self.p))if summary:self._log("turn", **summary)self._save(s)diff --git a/tokeneconomizer/plugin/hook.py b/tokeneconomizer/plugin/hook.pyindex 8f665d0..e5d4cae 100644--- a/tokeneconomizer/plugin/hook.py+++ b/tokeneconomizer/plugin/hook.py@@ -30,8 +30,7 @@ def run(payload, env, host_hint=None):payload = host.prepare(payload, env)ctx = LiveContext.build(host, host.cwd(payload, env), env,session_id=host.session_id(payload) or None, settle=False)- if ctx.config.repositories and os.path.realpath(ctx.repo.root) not in {- os.path.realpath(path) for path in ctx.config.repositories}:+ if not ctx.config.enabled:return {}if hasattr(host, "record_event"):host.record_event(payload)diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.pyindex f9a1716..dc9f65c 100644--- a/tokeneconomizer/plugin/hosts.py+++ b/tokeneconomizer/plugin/hosts.py@@ -146,6 +146,9 @@ class Host:def stop_hint(self, headless):return self.end_run if headless else self.interrupt+ def stopped_normally(self, p):+ return True+# Whether the loop guard's still-stuck notice must also go through the model, because the# agent does not put hook messages where the person looks.relays_notices = False@@ -485,9 +488,24 @@ class Cursor(Host):path = self.transcript(payload)if not path:return+ # The adapter reads these fields only. Cursor also sends user_email and the raw+ # tool_output; neither is stored. Tool text is capped where the guard folds it.+ row = {}+ for key in ("hook_event_name", "prompt", "cwd", "tool_use_id", "generation_id",+ "tool_name", "tool_input", "error"):+ value = payload.get(key)+ if value not in (None, ""):+ row[key] = value+ response = payload.get("tool_response")+ if isinstance(response, dict):+ response = dict(response)+ content = response.get("content")+ if isinstance(content, str):+ response["content"] = content[:RESULT_CAP]+ row["tool_response"] = responseos.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)with open(path, "a", encoding="utf-8") as fh:- fh.write(json.dumps(payload, ensure_ascii=False, sort_keys=True) + "\n")+ fh.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")try:os.chmod(path, 0o600)except OSError:@@ -504,12 +522,26 @@ class Cursor(Host):def session_usage(self, transcript_path):return {}+ def settle(self, transcript_path):+ # The fold has already read this private spool. It is not the agent's transcript.+ if not transcript_path:+ return+ if os.path.basename(os.path.dirname(os.path.realpath(transcript_path))) != "cursor-sessions":+ return+ try:+ os.remove(transcript_path)+ except OSError:+ pass+def tool_call(self, p):name, args, text, code = super().tool_call(p)if name.lower() == "shell":return "Bash", args, text, codereturn name, args, text, code+ def stopped_normally(self, p):+ return (p or {}).get("status") == "completed"+def copilot_home(env=None):env = os.environ if env is None else env