Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

Cursor follow-up: docs, side-call command names in notices, capped tool input

Aaron31ddbd1d4964
diff --git a/README.md b/README.md
index d6169bc..d06f2e9 100644
--- a/README.md
+++ b/README.md
@@ -63,14 +63,13 @@ mechanisms:
turn is still stuck after that, TokenEconomizer tells you how to stop it; it never stops a turn
itself.
-TokenEconomizer is a plugin for **Claude Code**, **Codex**, the **GitHub Copilot CLI**, **Pi**, and
-**Cursor Agent**, with experimental support for **opencode**. Cursor support uses Cursor's command
-hooks and is experimental in this fork. Each italic letter above is a setting, shown with its
-default ([Settings](#settings)), and each mechanism can be turned on or off. The plugin announces
-each action in one line, and if any part of it fails, your session carries on as if it were not
-installed. Its model calls (the fact proposer, and the judge with the redirect it writes) run
-through your own agent, on the same plan or login, and their cost is included in its reports.
-What it learns stays on your machine, in `~/.tokeneconomizer`.
+TokenEconomizer is a plugin for **Claude Code**, **Codex**, the **GitHub Copilot CLI** and **Pi**,
+with experimental support for **opencode** and **Cursor Agent**. Each italic letter above is a
+setting, shown with its default ([Settings](#settings)), and each mechanism can be turned on or
+off. The plugin announces each action in one line, and if any part of it fails, your session
+carries on as if it were not installed. Its model calls (the fact proposer, and the judge with the
+redirect it writes) run through your own agent, on the same plan or login, and their cost is
+included in its reports. What it learns stays on your machine, in `~/.tokeneconomizer`.
## Results
@@ -212,7 +211,7 @@ uninstalling, using Copilot with your own model key, and troubleshooting.
| Codex | 0.153.1 to 0.164.0 | not supported |
| 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 |
+| Cursor Agent (experimental) | 3.24.9, macOS and Linux (below) | not tested |
| opencode (experimental) | 1.19.5 and 2.2.0 | not tested |
The commands above were tested on the oldest and newest version in each range; newer versions
diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md
index 147be94..5bb0e63 100644
--- a/docs/PLUGIN.md
+++ b/docs/PLUGIN.md
@@ -1,9 +1,9 @@
# The plugin: design and verified agent behaviour
-How the plugin runs the three mechanisms inside your own Claude Code, Codex, Copilot CLI, Pi, Cursor and OpenCode
-sessions, through the hooks (on Pi, the extension events) each agent exposes: what it does at
-each hook, what differs from the experiments and why, the agent behaviour each choice rests on,
-where its state lives, and its known limitations. The code is `tokeneconomizer/plugin/` (what
+How the plugin runs the three mechanisms inside your own Claude Code, Codex, Copilot CLI, Pi,
+opencode and Cursor sessions, through the hooks (on Pi, the extension events) each agent
+exposes: what it does at each hook, what differs from the experiments and why, the agent
+behaviour each choice rests on, where its state lives, and its known limitations. The code is `tokeneconomizer/plugin/` (what
the hooks run) and `plugin/` (the packaging for each agent). To install and use it, see
[`plugin/README.md`](../plugin/README.md).
diff --git a/plugin/README.md b/plugin/README.md
index e634ee4..a0863d0 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -556,6 +556,7 @@ of the preset. A value you set with `loopguard.<name>` wins over both. Defaults
| Key | Default | Values |
|---|---|---|
+| `enabled` | `true` | `false`: the whole plugin is off; its hooks return at once and record nothing |
| `paid_model` | `""` | model for the plugin's own calls; empty: `haiku` on Claude Code, the agent's own default model on Codex and Pi, on Copilot `COPILOT_PROVIDER_MODEL_ID` or `COPILOT_MODEL` (unless it is `auto`), else a BYOK provider's Haiku, else Copilot's own default |
| `pi_extensions` | `""` | Pi only: extension files (comma-separated paths) the plugin's own calls load, for a model whose provider an extension registers |
| `pi_cli` | `""` | Pi only: the `pi` the plugin's own calls run; empty: the first on PATH |
@@ -570,6 +571,14 @@ settings win over the global ones, and those over the defaults; `unset` goes bac
change applies from the agent's next hook call: the guard at the next tool call, facts and the
deny list at the next session start. A new fact-size cap shows once the next session has ended.
+**Only in some repositories.** Turn the plugin off everywhere, then back on in each repository
+you choose; in a repository left off, the plugin records nothing:
+
+```text
+~/.tokeneconomizer/bin/te config set enabled=false --global
+~/.tokeneconomizer/bin/te config set enabled=true # in each chosen repository
+```
+
**Earlier names.** Before the mechanisms were renamed they were `inject`, `untool` and `spiral`,
with settings such as `inject_max_facts`, `untool_evidence`, `spiral_nudges`, `spiral.<name>` and
variables `TE_INJECT`, `TE_UNTOOL`, `TE_SPIRAL`, ...; all of them are still read (`spiral=guard`
diff --git a/tests/test_cursor.py b/tests/test_cursor.py
index f4f0fc6..6e0828d 100644
--- a/tests/test_cursor.py
+++ b/tests/test_cursor.py
@@ -153,3 +153,10 @@ def test_cursor_native_shell_json_output_positive_and_negative(tmp_path, cursor_
("Bash", {"command": "make build"}, "ok\n", True),
("Bash", {"command": "pytest -q"}, "failed\n", False),
]
+
+
+def test_notices_name_each_agents_side_call_command():
+ from tokeneconomizer.plugin import sidecall
+ hosts = ("claude", "codex", "copilot", "pi", "opencode", "cursor")
+ assert [sidecall.call_name(h) for h in hosts] == [
+ "claude -p", "codex exec", "copilot -p", "pi -p", "opencode run", "cursor-agent -p"]
diff --git a/tests/test_cursor_recording.py b/tests/test_cursor_recording.py
index 9c0d182..250c67f 100644
--- a/tests/test_cursor_recording.py
+++ b/tests/test_cursor_recording.py
@@ -159,6 +159,16 @@ def test_recording_caps_tool_output(recording_env):
assert "user_email" not in row
+def test_recording_caps_tool_input_and_keeps_its_short_fields(recording_env):
+ repo, state, env = recording_env
+ payload = _make_tool_payload(repo, "conv-input")
+ payload.update(tool_name="Write",
+ tool_input={"file_path": "src/big.py", "contents": "y" * (RESULT_CAP + 40)})
+ assert _call_hook(payload, env) == (0, {})
+ row = json.loads((state / "cursor-sessions" / "conv-input.jsonl").read_text().splitlines()[0])
+ assert row["tool_input"] == {"file_path": "src/big.py", "contents": "y" * RESULT_CAP}
+
+
def test_settle_deletes_processed_session_file(tmp_path):
spool = tmp_path / "cursor-sessions" / "conv.jsonl"
spool.parent.mkdir()
diff --git a/tests/test_live_config.py b/tests/test_live_config.py
index bfb9cd8..9c8195e 100644
--- a/tests/test_live_config.py
+++ b/tests/test_live_config.py
@@ -213,3 +213,22 @@ def test_the_quiet_window_before_a_deny_list_is_written_may_be_zero():
assert not cfg.set("toolprune_evidence", "0") # other numbers still start at 1
assert load_config("/nonexistent", env={"TE_TOOLPRUNE_QUIET_MINUTES": "15"}
).toolprune_quiet_minutes == 15
+
+
+def test_off_everywhere_and_on_in_one_repository_runs_only_there(env, repo, tmp_path):
+ """`enabled=false --global`, then `enabled=true` in a repository: the plugin runs there, and
+ a repository left off gets no state at all."""
+ other = tmp_path / "other"
+ (other / ".git" / "info").mkdir(parents=True)
+ (other / ".git" / "HEAD").write_text("ref: refs/heads/main\n")
+ (other / ".git" / "config").write_text(
+ '[remote "origin"]\n\turl = https://github.com/acme/other.git\n')
+ home = env["TOKENECONOMIZER_HOME"]
+ on = repo_identity(repo, env).key
+ os.makedirs(os.path.join(home, "repos", on))
+ write_config(os.path.join(home, "config.json"), {"enabled": False})
+ write_config(os.path.join(home, "repos", on, "config.json"), {"enabled": True})
+ for checkout, sid in ((repo, "s-on"), (str(other), "s-off")):
+ run_session(env, checkout, sid, str(tmp_path / f"{sid}.jsonl"))
+ assert os.listdir(os.path.join(home, "repos")) == [on]
+ assert os.listdir(os.path.join(home, "repos", on)) != ["config.json"] # it ran there
diff --git a/tokeneconomizer/plugin/README.md b/tokeneconomizer/plugin/README.md
index f140a2d..2a7de99 100644
--- a/tokeneconomizer/plugin/README.md
+++ b/tokeneconomizer/plugin/README.md
@@ -11,7 +11,7 @@ What happens at each hook, and how each agent was verified to behave, is in
|---|---|
| `hook.py`, `cli.py` | entry points: the hook dispatcher and `te` |
| `controller.py` | what happens at each hook |
-| `hosts.py` | per-agent hook payloads and outputs (Claude Code, Codex, Copilot CLI, Pi, Cursor, OpenCode) |
+| `hosts.py` | per-agent hook payloads and outputs (Claude Code, Codex, Copilot CLI, Pi, opencode, Cursor) |
| `fold.py` | a finished session through `PrefixStage` and `ToolingStage` |
| `denylist.py` | writing the deny list into each agent's settings (by itself under `auto`, on `toolprune apply` under `propose`), and taking it back |
| `toolcheck.py` | asking the agent CLIs what a session loads, and what a deny list removed |
diff --git a/tokeneconomizer/plugin/cli.py b/tokeneconomizer/plugin/cli.py
index 30b9c74..5b48acb 100644
--- a/tokeneconomizer/plugin/cli.py
+++ b/tokeneconomizer/plugin/cli.py
@@ -494,7 +494,8 @@ def cmd_config(args):
"has been folded")
if {canonical(k) for k in updates} & {"microskills", "loopguard"} and sidecall.resume(
ctx.host.name, ctx.root):
- print(f"the plugin's model calls through `{ctx.host.name} -p` will be tried again")
+ print(f"the plugin's model calls through `{sidecall.call_name(ctx.host.name)}` will be "
+ f"tried again")
if "distiller" in str(cur.get("microskills", "")):
every = cur.get("microskills_propose_every") or ctx.config.microskills_propose_every
print(f"note: micro-skills calls a model through this agent every {every} sessions to "
@@ -638,9 +639,9 @@ def cmd_doctor(args):
pause = sidecall.paused(h, root)
if pause:
print(f"{h:11s} model calls paused since "
- f"{time.strftime('%Y-%m-%d %H:%M', time.localtime(pause['at']))}: `{h} -p` said "
- f"it is not signed in; `config set microskills=on` (or `loopguard=on`) "
- f"tries again")
+ f"{time.strftime('%Y-%m-%d %H:%M', time.localtime(pause['at']))}: "
+ f"`{sidecall.call_name(h)}` said it is not signed in; "
+ f"`config set microskills=on` (or `loopguard=on`) tries again")
if "claude" in agents:
cat = os.path.join(root, "hosts", "claude", "catalog.json")
print(f"claude catalog {'present' if os.path.exists(cat) else 'not probed'}")
diff --git a/tokeneconomizer/plugin/controller.py b/tokeneconomizer/plugin/controller.py
index 5a94fd6..2c19726 100644
--- a/tokeneconomizer/plugin/controller.py
+++ b/tokeneconomizer/plugin/controller.py
@@ -143,7 +143,8 @@ class LiveController:
byok = (" (with your own model key, Copilot does not pass it to the plugin's hooks)"
if self.host.name == "copilot" else "")
outputs.append(self.host.notice(
- f"TokenEconomizer: the plugin's own model calls go through `{self.host.name} -p`, "
+ f"TokenEconomizer: the plugin's own model calls go through "
+ f"`{sidecall.call_name(self.host.name)}`, "
f"which answered that it is not signed in{byok}, so they are paused; facts that "
f"need no model call are still learned, and the loop guard redirects only at its "
f"backstop. `{self._cmd('config')} set microskills=on` (or `loopguard=on`) tries "
diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.py
index dc9f65c..d55385a 100644
--- a/tokeneconomizer/plugin/hosts.py
+++ b/tokeneconomizer/plugin/hosts.py
@@ -496,6 +496,12 @@ class Cursor(Host):
value = payload.get(key)
if value not in (None, ""):
row[key] = value
+ # A file write's input holds the whole file, which no mechanism reads.
+ if isinstance(row.get("tool_input"), dict):
+ row["tool_input"] = {k: v[:RESULT_CAP] if isinstance(v, str) else v
+ for k, v in row["tool_input"].items()}
+ if isinstance(row.get("error"), str):
+ row["error"] = row["error"][:RESULT_CAP]
response = payload.get("tool_response")
if isinstance(response, dict):
response = dict(response)
diff --git a/tokeneconomizer/plugin/sidecall.py b/tokeneconomizer/plugin/sidecall.py
index 98e9774..510e68b 100644
--- a/tokeneconomizer/plugin/sidecall.py
+++ b/tokeneconomizer/plugin/sidecall.py
@@ -405,6 +405,15 @@ def copilot_call(prompt, model="", cli="copilot", timeout=TIMEOUT_S):
return text, eff
+# The command each agent's side calls run, as the notices name it; the rest run `<agent> -p`.
+_CALLS = {"codex": "codex exec", "opencode": "opencode run", "cursor": "cursor-agent -p"}
+
+
+def call_name(host_name):
+ """How a notice names this agent's side-call command: `claude -p`, `codex exec`, ..."""
+ return _CALLS.get(host_name, f"{host_name} -p")
+
+
def runner_for(host_name, config):
"""The optimizer callable for this host. Each host's calls go through that host's own CLI,
never another agent's. The caller decides whether a call is allowed: micro-skills' proposer