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
Add Cursor support and safe defaults
Shadow296e04a7753d
diff --git a/README.md b/README.mdindex 44d9b77..a5d8865 100644--- a/README.md+++ b/README.md@@ -63,8 +63,9 @@ mechanisms:turn is still stuck after that, TokenEconomizer tells you how to stop it; it never stops a turnitself.-TokenEconomizer is a plugin for **Claude Code**, **Codex**, the **GitHub Copilot CLI** and **Pi**,-with experimental support for **opencode**. Each italic letter above is a setting, shown with its+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 itsdefault ([Settings](#settings)), and each mechanism can be turned on or off. The plugin announceseach action in one line, and if any part of it fails, your session carries on as if it were notinstalled. Its model calls (the fact proposer, and the judge with the redirect it writes) run@@ -161,6 +162,18 @@ pi install git:github.com/microsoft/TokenEconomizerStart `pi` and run `/te status`.+**Cursor Agent** (experimental)++```sh+python scripts/build_plugin.py --out ~/.cursor/plugins/local/+```++Reload Cursor, confirm `tokeneconomizer` appears in Customize, then send a prompt in a repository.+Check its state from a terminal with `~/.tokeneconomizer/bin/te --host cursor status`. Cursor's+published hooks provide session, prompt, tool-result and completion events. Its transcript format+and per-session token usage are not a supported public interface, so the adapter records needed+hook events locally and reports session cost as unavailable.+**opencode** (experimental)```sh@@ -197,6 +210,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 || 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@@ -208,6 +222,8 @@ have not been tested yet.full path; `git pull` in the clone updates it.- **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; the hook event mapping has not yet been verified in+ the live Cursor app.### Everyday commands@@ -220,6 +236,7 @@ commands. They have the same names on every agent; only the way you type them di| Codex | `$tokeneconomizer:<command>` || Pi | `/te <command>` || opencode | from a terminal: `~/.tokeneconomizer/bin/te --host opencode <command>` |+| Cursor Agent | from a terminal: `~/.tokeneconomizer/bin/te --host cursor <command>` || a terminal, in the repository | `~/.tokeneconomizer/bin/te <command>` || Command | What it does |@@ -237,10 +254,11 @@ Inside an agent, a command costs one model turn; from a terminal it is free. The## Settings-Tool pruning and the loop guard are on by default; with these defaults, the plugin calls a model-only when a turn shows signs of looping: the judge, and the redirect it writes if it finds the-turn stuck. Micro-skills is off by default, because its proposer adds model calls and how much it-saves depends on the repository and the work you do there. Each mechanism has its own switch+The loop guard is on by default. Tool pruning is off by default and never removes tools or MCP+servers unless you explicitly enable it. With these defaults, the plugin calls a model only when a+turn shows signs of looping: the judge, and the redirect it writes if it finds the turn stuck.+Micro-skills is off by default, because its proposer adds model calls and how much it saves depends+on the repository and the work you do there. Each mechanism has its own switch(`microskills`, `toolprune`, `loopguard`) that takes `on` or `off`, and the italic letters aboveare these settings:@@ -295,6 +313,7 @@ what it can leave out differs:| Codex | capability packages | `.codex/config.toml` || Copilot CLI | whole MCP servers | `.github/copilot/settings.local.json` || Pi | nothing (Pi loads only four tools) | — |+| Cursor Agent | nothing yet | — || opencode | nothing yet | — |Tool pruning adds only its own entries and never touches deny rules you wrote; a settings file itdiff --git a/docs/PLUGIN.md b/docs/PLUGIN.mdindex 3cc809d..033831c 100644--- a/docs/PLUGIN.md+++ b/docs/PLUGIN.md@@ -1,6 +1,6 @@# The plugin: design and verified agent behaviour-How the plugin runs the three mechanisms inside your own Claude Code, Codex, Copilot CLI and Pi+How the plugin runs the three mechanisms inside your own Claude Code, Codex, Copilot CLI, Pi, Cursor and OpenCodesessions, through the hooks (on Pi, the extension events) each agent exposes: what it does ateach 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@@ -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**, 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) |+| Tool removal | `--disallowed-tools` / Codex config at launch | off by default; when explicitly enabled, a **deny list** is applied 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) || 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 |@@ -525,7 +525,7 @@ Which repository a session belongs to (`plugin/paths.py`, `plugin/repos.py`):agent files its own session log. `te status` run inside a session says so when the two differ.* **Deny lists stay per checkout.** The clones of a repository share its evidence and proposal,but each has its own settings file, so `untool_applied.json` records per file what was added,- and what the person gave back with `restore`: `toolprune: auto`, the default, never applies that+ and what the person gave back with `restore`: `toolprune: off`, the default, never applies thatagain (an explicit `toolprune apply NAME` does), as the evidence would keep proposing it.* **State from earlier keys is carried over.** Up to 0.1.0 a checkout's folder name was part ofthe key, any `.git` entry made a checkout, and a session was recorded wherever the agent was.@@ -575,6 +575,11 @@ open-vocabulary. On a repository you do not trust, leave micro-skills off (the dalready found its cause and was working around it; since 2026-10-25 the judge decides everyredirect but the backstop's, which still counts.* **Pi** — tool pruning is not planned there, since Pi declares only four tools by default.+* **Cursor Agent (experimental)** — hook event mapping is based on Cursor's published hook+ schemas but has not been exercised in the live app. Cursor's transcript format is undocumented+ and hook payloads do not expose session token usage, so the adapter records only prompt and tool+ events needed for learning and loop detection; session and side-call costs are reported as+ unavailable. Tool pruning is not implemented for Cursor.* **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/.cursor-plugin/plugin.json b/plugin/.cursor-plugin/plugin.jsonnew file mode 100644index 0000000..ca0c9a4--- /dev/null+++ b/plugin/.cursor-plugin/plugin.json@@ -0,0 +1,9 @@+{+ "name": "tokeneconomizer",+ "version": "0.1.0",+ "description": "Learn repository facts and redirect coding-agent turns that appear stuck.",+ "author": {+ "name": "TokenEconomizer authors"+ },+ "hooks": "./hooks/cursor-hooks.json"+}diff --git a/plugin/README.md b/plugin/README.mdindex 6e1729d..fcbb429 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,12 +1,12 @@# TokenEconomizer plugin-How to install and use TokenEconomizer in Claude Code, Codex, the GitHub Copilot CLI, Pi and-(experimental) opencode. What the plugin does and why is in the [main README](../README.md); its+How to install and use TokenEconomizer in Claude Code, Codex, the GitHub Copilot CLI, Pi, Cursor+(experimental), and opencode (experimental). What the plugin does and why is in the [main README](../README.md); itsdesign and the verified behaviour of each agent are in [`docs/PLUGIN.md`](../docs/PLUGIN.md).- [Before you start](#before-you-start)- Install and use it on [Claude Code](#claude-code) · [Codex](#codex) ·- [Copilot CLI](#copilot-cli) · [Pi](#pi)+ [Copilot CLI](#copilot-cli) · [Pi](#pi) · [Cursor](#cursor)- [What to expect](#what-to-expect) · [Commands](#commands) · [Settings](#settings)- [Repository map](#repository-map) · [Using with rtk](#using-with-rtk) ·[Model calls and API keys](#model-calls-and-api-keys) · [Troubleshooting](#troubleshooting)@@ -300,6 +300,33 @@ is a wrapper the calls should not run, set `pi_cli` to the real one.**Uninstall.** `pi remove git:github.com/microsoft/TokenEconomizer` (the source you installedfrom); `pi config` turns it off without removing it. Optional: `rm -rf ~/.tokeneconomizer`.+## Cursor++**1. Install.** From the TokenEconomizer checkout, build a local Cursor plugin:++```sh+python scripts/build_plugin.py --out ~/.cursor/plugins/local/+```++Reload Cursor. In **Customize**, confirm `tokeneconomizer` is installed, then open a repository and+send a prompt.++**2. Check it.** From a terminal in that repository:++```sh+~/.tokeneconomizer/bin/te --host cursor status+```++Cursor's command hooks provide the session, prompt, successful and failed tool, and completion+events used by the adapter. The transcript format is private and its hooks do not report per-session+token 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 as+unavailable. 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.++Tool pruning is off by default and is not applied to Cursor. Cursor commands run from a terminal:+`~/.tokeneconomizer/bin/te --host cursor <command>`.+## opencode**1. Install.** One plugin file serves opencode 1.x (the `server` entry) and 2.x (the `setup`@@ -467,7 +494,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 | `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` |+| Tool pruning (off 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` || 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/plugin/hooks/cursor-hooks.json b/plugin/hooks/cursor-hooks.jsonnew file mode 100644index 0000000..f20ea4e--- /dev/null+++ b/plugin/hooks/cursor-hooks.json@@ -0,0 +1,23 @@+{+ "version": 1,+ "hooks": {+ "sessionStart": [+ { "command": "\"${CURSOR_PLUGIN_ROOT}/scripts/te-hook\" --host cursor" }+ ],+ "beforeSubmitPrompt": [+ { "command": "\"${CURSOR_PLUGIN_ROOT}/scripts/te-hook\" --host cursor" }+ ],+ "postToolUse": [+ { "command": "\"${CURSOR_PLUGIN_ROOT}/scripts/te-hook\" --host cursor" }+ ],+ "postToolUseFailure": [+ { "command": "\"${CURSOR_PLUGIN_ROOT}/scripts/te-hook\" --host cursor" }+ ],+ "stop": [+ { "command": "\"${CURSOR_PLUGIN_ROOT}/scripts/te-hook\" --host cursor" }+ ],+ "sessionEnd": [+ { "command": "\"${CURSOR_PLUGIN_ROOT}/scripts/te-hook\" --host cursor" }+ ]+ }+}diff --git a/tokeneconomizer/plugin/README.md b/tokeneconomizer/plugin/README.mdindex 1adc4f3..f140a2d 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) |+| `hosts.py` | per-agent hook payloads and outputs (Claude Code, Codex, Copilot CLI, Pi, Cursor, OpenCode) || `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/config.py b/tokeneconomizer/plugin/config.pyindex c31b3cc..ee22c97 100644--- a/tokeneconomizer/plugin/config.py+++ b/tokeneconomizer/plugin/config.py@@ -8,12 +8,10 @@ The defaults:calls a model through the agent's own CLI (charged to theledger) to write facts beyond them, as in the experiments."envfacts" alone makes no model call;- * toolprune = "auto" -- a deny list is applied once the evidence forms it and the- repository's sessions have been idle (toolprune_quiet_minutes),- from the next session, and announced once at that session's start;- `toolprune restore` gives it back. "propose" only proposes it,- and writes nothing to the agent's settings until the person- runs `toolprune apply`;+ * toolprune = "off" -- no tools or MCP servers are removed by default. Set it to `auto`+ to apply a deny list after the evidence forms and the repository's+ sessions have been idle, or to `propose` to wait for `toolprune+ apply`;* loopguard = "nudge" -- a turn that shows signs of looping is put to a judge, a modelcalled through the agent's own CLI, and redirected mid-turn onlywhen the judge finds it stuck (the redirect written by that@@ -38,6 +36,8 @@ 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;@@ -149,12 +149,13 @@ class LiveConfig:microskills_max_facts: int = 4microskills_max_tokens: int = 150microskills_propose_every: int = 3- toolprune: str = "auto"+ toolprune: str = "off"toolprune_evidence: int = 10toolprune_min_sessions: int = 2toolprune_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 bedeb9a..d697314 100644--- a/tokeneconomizer/plugin/controller.py+++ b/tokeneconomizer/plugin/controller.py@@ -80,6 +80,10 @@ 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 ""diff --git a/tokeneconomizer/plugin/hook.py b/tokeneconomizer/plugin/hook.pyindex 9fc873c..8f665d0 100644--- a/tokeneconomizer/plugin/hook.py+++ b/tokeneconomizer/plugin/hook.py@@ -26,8 +26,15 @@ def run(payload, env, host_hint=None):from .context import LiveContextfrom .controller import LiveControllerhost = hosts.detect(payload, env, hint=host_hint)+ if hasattr(host, "prepare"):+ 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}:+ return {}+ if hasattr(host, "record_event"):+ host.record_event(payload)return LiveController(ctx, payload).handle()diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.pyindex 94e2ef0..043e59a 100644--- a/tokeneconomizer/plugin/hosts.py+++ b/tokeneconomizer/plugin/hosts.py@@ -7,7 +7,7 @@ tool call; JSON on stdout with `hookSpecificOutput.additionalContext`, `systemMean adapter rather than a branch in a mechanism:* Turn identity. Claude Code stamps every event of a prompt-turn with `prompt_id`; Codex- stamps `turn_id`.+ stamps `turn_id`; Cursor gives one `generation_id` per prompt.* Stopping. The plugin never stops a turn: the guard's last rung, on every agent and in everymode, is a notice telling the person how to (`stop_hint`). Claude Code's `{"continue":false}` from PostToolUse would halt its loop (verified on 2.1.286), but Codex's replaces the@@ -92,6 +92,8 @@ def merge_outputs(*outputs):out[k] = out[k] + "\n" + velif k == "additionalContext" and out.get(k):out[k] = out[k] + "\n\n" + v+ elif k == "additional_context" and out.get(k):+ out[k] = out[k] + "\n\n" + velif k == PROGRESS:out[k] = list(out.get(k) or []) + list(v)elif k == "hookSpecificOutput" and out.get(k):@@ -389,6 +391,122 @@ class OpenCode(Host):return trace.opencode_session_usage(transcript_path)+class Cursor(Host):+ """Cursor Agent hooks, translated to the shared live-controller contract.++ Cursor's JSONL transcript records prompts and tool requests, but not tool results or token+ usage. The adapter therefore keeps only the hook events TokenEconomizer needs in its private+ state directory and reconstructs a Claude-shaped trace from those events. Session economics+ remain unpriced until Cursor exposes per-session usage in a supported interface.+ """+ name = "cursor"+ prompt_context = False+ relays_notices = True+ interrupt = "Press Esc to stop the Cursor agent."+ end_run = "Press Ctrl+C to end the Cursor Agent CLI run."++ _EVENTS = {+ "sessionStart": "SessionStart",+ "beforeSubmitPrompt": "UserPromptSubmit",+ "postToolUse": "PostToolUse",+ "postToolUseFailure": "PostToolUseFailure",+ "stop": "Stop",+ "sessionEnd": "SessionEnd",+ }++ def prepare(self, payload, env):+ p = dict(payload or {})+ p["session_id"] = p.get("conversation_id") or p.get("session_id") or ""+ roots = p.get("workspace_roots")+ root = roots[0] if isinstance(roots, list) and roots else ""+ p["cwd"] = p.get("cwd") or env.get("CURSOR_PROJECT_DIR") or root or os.getcwd()+ p["hook_event_name"] = self._EVENTS.get(p.get("hook_event_name"), "")+ p["transcript_path"] = self.transcript(p)+ if p["hook_event_name"] == "SessionStart":+ p["source"] = "startup"+ if p["hook_event_name"] == "UserPromptSubmit":+ p["prompt_id"] = p.get("generation_id") or ""+ if p["hook_event_name"] in ("PostToolUse", "PostToolUseFailure"):+ p["tool_use_id"] = p.get("tool_use_id") or p.get("generation_id") or ""+ if p["hook_event_name"] == "PostToolUse":+ raw = p.get("tool_output")+ try:+ output = json.loads(raw) if isinstance(raw, str) else raw+ except ValueError:+ output = raw+ if isinstance(output, dict):+ p["tool_response"] = {+ "content": "\n".join(str(output[k]) for k in ("stdout", "stderr", "output")+ if output.get(k) is not None),+ "exit_code": _exit_code(output),+ "isError": bool(output.get("isError") or output.get("is_error")),+ }+ else:+ p["tool_response"] = {"content": str(output or "")}+ else:+ p["error"] = p.get("error_message") or p.get("error") or "tool failed"+ if p.get("failure_type") == "permission_denied":+ p["error"] = "Permission denied: " + str(p["error"])+ return p++ def session_id(self, p):+ return str(p.get("session_id") or p.get("conversation_id") or "")++ def cwd(self, p, env):+ roots = p.get("workspace_roots")+ root = roots[0] if isinstance(roots, list) and roots else ""+ return p.get("cwd") or env.get("CURSOR_PROJECT_DIR") or root or os.getcwd()++ def turn_key(self, p):+ return str(p.get("generation_id") or p.get("prompt_id") or "")++ def context(self, event, text):+ return {"additional_context": text}++ def notice(self, text):+ return {"additional_context": self.relay(text)}++ def transcript(self, p):+ sid = self.session_id(p)+ if not sid:+ return ""+ from .paths import state_root+ safe_id = os.path.basename(sid)+ return os.path.join(state_root(), "cursor-sessions", safe_id + ".jsonl")++ def record_event(self, payload):+ event = payload.get("hook_event_name")+ if event not in ("UserPromptSubmit", "PostToolUse", "PostToolUseFailure"):+ return+ path = self.transcript(payload)+ if not path:+ return+ os.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")+ try:+ os.chmod(path, 0o600)+ except OSError:+ pass++ def mechanism_trace(self, transcript_path, workdir):+ out = os.path.join(workdir, "cursor_trace.jsonl")+ n = trace.cursor_events_to_claude(transcript_path, out)+ return out if n is not None else None++ def prompt_count(self, transcript_path):+ return trace.cursor_prompt_count(transcript_path)++ def session_usage(self, transcript_path):+ return {}++ def tool_call(self, p):+ name, args, text, code = super().tool_call(p)+ if name.lower() == "shell":+ return "Bash", args, text, code+ return name, args, text, code++def copilot_home(env=None):env = os.environ if env is None else envreturn env.get("COPILOT_HOME") or os.path.join(os.path.expanduser("~"), ".copilot")@@ -481,7 +599,7 @@ def _ancestor_args(limit=4):HOSTS = {"claude": ClaudeCode, "codex": Codex, "copilot": Copilot, "opencode": OpenCode,- "pi": Pi}+ "pi": Pi, "cursor": Cursor}def default_host(env=None, recent=None):@@ -496,6 +614,8 @@ def default_host(env=None, recent=None):return "claude"if env.get("COPILOT_CLI") == "1":return "copilot"+ if env.get("CURSOR_AGENT") or env.get("CURSOR_PROJECT_DIR"):+ return "cursor"return recent if recent in HOSTS else "claude"diff --git a/tokeneconomizer/plugin/sidecall.py b/tokeneconomizer/plugin/sidecall.pyindex d13cd9d..98e9774 100644--- a/tokeneconomizer/plugin/sidecall.py+++ b/tokeneconomizer/plugin/sidecall.py@@ -313,6 +313,29 @@ def opencode_call(prompt, model="", cli="opencode", timeout=TIMEOUT_S):return text, eff+def cursor_call(prompt, model="", cli="cursor-agent", timeout=TIMEOUT_S):+ """Use Cursor Agent's read-only Ask mode for optimizer calls in an empty directory.++ Cursor's current CLI JSON result does not expose token usage, so the call is useful for the+ judge/proposer but its cost remains unpriced in TokenEconomizer's ledger.+ """+ with tempfile.TemporaryDirectory(prefix="te-side-") as cwd:+ cmd = [cli, "--print", "--output-format", "json", "--mode", "ask", "--trust"]+ if model:+ cmd += ["--model", model]+ cmd.append(prompt)+ out = subprocess.run(cmd, capture_output=True, encoding="utf-8", errors="replace",+ timeout=timeout, env=_env(), cwd=cwd, stdin=subprocess.DEVNULL)+ try:+ data = json.loads(out.stdout or "{}")+ except ValueError:+ data = {}+ text = data.get("result") if isinstance(data, dict) else ""+ if not text:+ _no_reply("cursor", out)+ return text or "", None++# Everything the Copilot CLI offers (1.0.83 names), so the completion is offered nothing; a name# the installed CLI does not know is ignored.COPILOT_TOOLS = ("bash", "read_bash", "write_bash", "stop_bash", "list_bash", "view", "grep",@@ -394,6 +417,8 @@ def runner_for(host_name, config):extensions=extensions)if host_name == "opencode":return lambda prompt, _m="agent": opencode_call(prompt, model=model)+ if host_name == "cursor":+ return lambda prompt, _m="agent": cursor_call(prompt, model=model)if host_name == "codex":return lambda prompt, _m="agent": codex_call(prompt, model=model)if host_name == "copilot":diff --git a/tokeneconomizer/trace/README.md b/tokeneconomizer/trace/README.mdindex 43a9278..0b1e200 100644--- a/tokeneconomizer/trace/README.md+++ b/tokeneconomizer/trace/README.md@@ -11,6 +11,7 @@ session as an ordered list of `(tool_name, args, result_text, success)` calls th| `claude.py` | Claude Code transcripts: calls with the shell's directory, usage by message id, subagents, deferred tools || `codex.py` | `codex exec --json` streams; a session's rollout file, converted to that stream; usage || `copilot.py` | Copilot CLI event logs: calls, usage, prompt-turns, MCP servers |+| `cursor.py` | Cursor Agent hook events, normalized to a Claude-shaped trajectory; usage is unavailable || `pi.py` | Pi's session tree: the active branch, written as a Claude transcript; usage || `jsonl.py` | line and record readers shared by the above |diff --git a/tokeneconomizer/trace/__init__.py b/tokeneconomizer/trace/__init__.pyindex b8993c5..c78e533 100644--- a/tokeneconomizer/trace/__init__.py+++ b/tokeneconomizer/trace/__init__.py@@ -24,6 +24,7 @@ from .codex import (codex_capability_trace, codex_exec_calls, codex_prompt_countfrom .copilot import (copilot_event_calls, copilot_mcp_servers, copilot_prompt_count,copilot_session_meta, copilot_session_usage, copilot_turns,mcp_server_of)+from .cursor import cursor_events_to_claude, cursor_prompt_countfrom .opencode import (opencode_prompt_count, opencode_run_reply, opencode_session_info,opencode_session_to_claude, opencode_session_usage)from .pi import (pi_active_branch, pi_json_reply, pi_prompt_count, pi_session_header,@@ -40,6 +41,7 @@ __all__ = ["codex_session_meta", "codex_session_usage", "rollout_item_to_exec","copilot_event_calls", "copilot_mcp_servers", "copilot_prompt_count", "copilot_session_meta","copilot_session_usage", "copilot_turns", "mcp_server_of",+ "cursor_events_to_claude", "cursor_prompt_count","opencode_prompt_count", "opencode_run_reply", "opencode_session_info","opencode_session_to_claude", "opencode_session_usage","pi_active_branch", "pi_json_reply", "pi_prompt_count", "pi_session_header",diff --git a/tokeneconomizer/trace/cursor.py b/tokeneconomizer/trace/cursor.pynew file mode 100644index 0000000..1e512c3--- /dev/null+++ b/tokeneconomizer/trace/cursor.py@@ -0,0 +1,90 @@+"""Cursor Agent hook events, normalized to the Claude-shaped trace the mechanisms read.++Cursor's JSONL transcript format is private and omits tool results. Its documented hooks provide+the information needed for micro-skills and loop detection, so the host adapter records those+events locally and this reader pairs each tool request with its observed result.+"""+import json++from .jsonl import lines as _lines+++def _response_text(response):+ if isinstance(response, str):+ return response+ if isinstance(response, dict):+ return "\n".join(str(response[k]) for k in+ ("content", "stdout", "stderr", "output", "error")+ if response.get(k) is not None)+ return str(response or "")+++def _exit_code(response):+ if not isinstance(response, dict):+ return None+ for key in ("exit_code", "exitCode", "returncode", "status_code"):+ code = response.get(key)+ if isinstance(code, int) and not isinstance(code, bool):+ return code+ return None+++def cursor_events_to_claude(path, out_path):+ """Write the normalized trajectory. Return the number of records, or None if unreadable."""+ try:+ lines = _lines(path)+ except OSError:+ return None+ if not lines:+ return None+ out = []+ for line in lines:+ try:+ event = json.loads(line)+ except ValueError:+ continue+ name = event.get("hook_event_name")+ if name == "UserPromptSubmit":+ prompt = event.get("prompt")+ if isinstance(prompt, str) and prompt.strip():+ out.append({"type": "user", "message": {"content": [+ {"type": "text", "text": prompt}]}})+ elif name in ("PostToolUse", "PostToolUseFailure"):+ tool_id = str(event.get("tool_use_id") or event.get("generation_id") or len(out))+ tool_name = str(event.get("tool_name") or "unknown")+ tool_input = event.get("tool_input")+ if not isinstance(tool_input, dict):+ tool_input = {}+ if tool_name.lower() == "shell":+ tool_name = "Bash"+ out.append({"type": "assistant", "cwd": event.get("cwd"), "message": {+ "content": [{"type": "tool_use", "id": tool_id, "name": tool_name,+ "input": tool_input}]}})+ response = event.get("tool_response")+ if name == "PostToolUseFailure":+ response = {"content": event.get("error") or "tool failed", "isError": True}+ result = _response_text(response)+ code = _exit_code(response)+ failed = name == "PostToolUseFailure" or (code is not None and code != 0)+ out.append({"type": "user", "message": {"content": [+ {"type": "tool_result", "tool_use_id": tool_id, "content": result,+ "is_error": failed}]}})+ try:+ with open(out_path, "w", encoding="utf-8") as fh:+ for item in out:+ fh.write(json.dumps(item, ensure_ascii=False) + "\n")+ except OSError:+ return None+ return len(out)+++def cursor_prompt_count(path):+ """Count actual prompt-submission events recorded by the adapter."""+ count = 0+ for line in _lines(path):+ try:+ event = json.loads(line)+ except ValueError:+ continue+ count += event.get("hook_event_name") == "UserPromptSubmit"+ return count