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
docs updated
Aaron0ce0e067b42b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9ee3ede..00cc98d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -39,9 +39,9 @@ agent behavior, and `docs/ARCHITECTURE.md` for how the package fits together.- No run outputs in the repository: transcripts, rows, streams, figures rendered from runs andtables derived from them stay out of git (`.gitignore`). The one exception is the paper'sheadline results in `README.md` (the line under the badges, the Results section and- `docs/assets/results_overview.*`): quoted from the paper's Table 1 and attributed to it, with- the plugin's differences from the experimental setting linked. Change them only with the- paper, and redraw the figure with `python docs/assets/results_overview.py`.+ `docs/assets/results_overview.*`): quoted from the paper's Table 1 and attributed to it.+ Change them only with the paper, and redraw the figure with+ `python docs/assets/results_overview.py`.- The plugin's own text (`plugin/`, its manifests, slash commands and skills, and what thehooks print) makes no claims of effect.- Tests: `python -m pytest tests experiments/tests`. A change to what the plugin learns ordiff --git a/README.md b/README.mdindex c989fec..6a3e028 100644--- a/README.md+++ b/README.md@@ -66,27 +66,6 @@ security-auditing benchmarks where every task is a new repository (6–20% lowernumbers, and nine annotated runs; [`experiments/`](experiments/README.md) reruns the SWE-Bench andWeb-Bench experiments.-<details>-<summary>The numbers in the figure</summary>--| Agent · model | Cost vs default | Pass@1, default | Pass@1, TokenEconomizer |-|---|---|---|---|-| Claude Code · Sonnet 5 | −23.6% ± 1.8 | 74.7 ± 1.3 | 76.0 ± 1.2 |-| Claude Code · Opus 4.8 | −30.9% ± 2.1 | 74.0 ± 0.6 | 73.0 ± 0.6 |-| Codex · GPT-5.6 Terra | −24.7% ± 1.2 | 73.8 ± 1.0 | 74.7 ± 1.0 |-| Codex · GPT-5.6 Sol | −26.1% ± 2.1 | 80.1 ± 0.8 | 81.7 ± 0.7 |-| Copilot CLI · Sonnet 5 | −18.4% ± 1.5 | 75.0 ± 1.5 | 77.6 ± 1.3 |--Mean ± standard deviation, from the paper's Table 1;-[`docs/assets/results_overview.py`](docs/assets/results_overview.py) draws the figure from them.--</details>--These are the paper's runs, in its experimental setting. The plugin keeps the mechanisms but-acts where a person is in the loop: by default it makes no model calls of its own, it redirects-a stuck turn instead of restarting the agent, and it never stops a turn. See-[what changes, and why](docs/PLUGIN.md#2-what-changes-relative-to-the-experimental-setting).-## How it worksCoding agents are built for task success, not for what a task costs, and every turn re-bills@@ -180,15 +159,20 @@ Uninstalling, Copilot with your own model key, and troubleshooting are in### Supported versions-| Agent | Checked on | Older versions |+| Agent | Supported | Older versions ||---|---|---|-| Claude Code | 2.1.306, 2.1.300 | not supported |-| Codex | 0.163.0, 0.153.1 | not supported |-| Copilot CLI | 1.0.101, 1.0.83 | not supported |-| Pi | 1.3.0, 1.2.0 | 0.99.x, with one change |+| Claude Code | 2.1.300 to 2.1.307 | not supported |+| Codex | 0.153.1 to 0.163.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) |++The commands above were checked on both ends of each range; later versions have not been+checked.-Before 0.141.0, Codex does not run plugin hooks at all. On Pi 0.99.x, skip `pi install` and-start each session with `pi --extension /path/to/TokenEconomizer/plugin/pi/tokeneconomizer.ts`.+- **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's+ full path; `git pull` in the clone updates it.### Everyday commands@@ -221,7 +205,10 @@ The three mechanisms are `microskills`, `toolprune` and `loopguard`; each takesand each has numbers you can tune with the same `config set` command (in Claude Code's form here).Tool pruning is `auto` by default: once a tool has gone unused for `toolprune_evidence` sessionsin a row (five), the plugin adds it to the deny list without asking, and it is left out from the-next session on. With `toolprune=propose` the plugin only proposes the list, and nothing changes+next session on. It writes the list once your sessions in the repository have been idle for an+hour (`toolprune_quiet_minutes`): a conversation resumed after its tools change writes its whole+history to the prompt cache again instead of reading it, and after an idle hour that cache has+expired anyway. With `toolprune=propose` the plugin only proposes the list, and nothing changesuntil you run `toolprune apply`.```textdiff --git a/docs/PLUGIN.md b/docs/PLUGIN.mdindex 902cb52..64e3059 100644--- a/docs/PLUGIN.md+++ b/docs/PLUGIN.md@@ -13,7 +13,7 @@ the hooks run) and `plugin/` (the packaging for each agent). To install and use| Hook | What the plugin does | Mechanism it drives ||---|---|---|-| `SessionStart` | Injects the repository's micro-skills (a cached render) as `additionalContext`; announces changed facts, tools the deny list newly left out, or a proposal still waiting, each in one `systemMessage` line; folds any earlier session whose end was never seen | microskills |+| `SessionStart` | Injects the repository's micro-skills (a cached render) as `additionalContext`, at a new start, and on a Copilot resume the text that session started with (§3); announces changed facts, tools the deny list newly left out, or a proposal still waiting, each in one `systemMessage` line; folds any earlier session whose end was never seen | microskills || `UserPromptSubmit` | Opens a prompt-turn for the loop guard | loopguard || `PostToolUse` | Folds the call into the turn's guard; delivers a redirect as `additionalContext`, then, if the turn is still stuck, a one-line notice to the person (on Claude Code, also as context asking the model to repeat it); never stops the turn | loopguard || `PostToolUseFailure` | The same, for a call that failed (Claude Code and Copilot report a failed call only here); the answer names this event, as Claude Code requires | loopguard |@@ -53,7 +53,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 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. Tools are fixed at session start, and changing them mid-session would re-write the cached prompt prefix. 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** (loaded but unused for N sessions) 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 || Nudge | kill the agent, resume it with a continuation prompt | a mid-turn reminder attached to the tool result | Different intervention, so its effect is not inherited from the experiments |@@ -376,6 +376,48 @@ thresholds), in its terminal UI and headless.same command, and the guard counted none of its twelve edits, so it never fired; and`copilot -p` was told the interactive way to stop.+**Prompt caching, 2026-10-21.** A prompt cache matches a request's prefix: the tools, the+system prompt, then the conversation in order. What the plugin changes must leave a cached+prefix alone. Checked on Claude Code 2.1.307 against a local fake Messages API (no model calls),+and on Codex 0.163.0, Copilot CLI 1.0.102 and Pi 1.3.0 through a logging proxy in front of+OpenRouter (cache breakpoints, which move every turn, left out of the comparison).++* A deny list present at session start takes its tools out of the request: Claude Code 12 tools+ to 11, Codex 9 to 4 (goals, multi-agent, view_image), Copilot 21 to 19 (an MCP server's two).+* A running session keeps its tools, on all three. A deny list written mid-turn (while the+ model's `sleep` ran) or between interactive turns by another process, as another session's+ fold would, left every later request's tools byte-identical and its history extending the+ last. Claude Code even reloaded the rule (`/permissions` listed it) and kept the tool; nor+ does a rule a `SessionStart` hook writes reach that session's first request.+* A resumed conversation does not keep them, on all three: `claude --continue`, `codex exec+ resume --last` and `copilot --continue` sent the old history with exactly the new tool list,+ so a conversation resumed while its cache is warm writes its whole history to the cache again+ instead of reading it. The fold runs just after a session ends, when its cache is warmest and+ resuming it likeliest, so `auto` now holds a new list as pending, and a detached+ `te toolprune apply-pending` writes it once every session of the repository has been idle for+ `toolprune_quiet_minutes` (60; a hook call or a write to the session's own log counts as+ activity), or once it has waited a day. End to end on Claude Code, the window set to one+ minute: the list waited through a second session, was written one idle minute after it, and+ the next session sent 8 tools instead of 12.+* Within a session the facts and the guard keep the prefix on every agent: the facts block is+ rendered at fold time and given once (on Pi, the same system-prompt section on every prompt),+ and a redirect or notice comes after a tool result. Facts changed on disk mid-session leave a+ running session alone.+* A resumed conversation must carry the facts it started with, byte for byte. Claude Code and+ Codex replay them from their own logs (Claude Code changes the message from a block list to a+ string of the same text). Two did not, and both are fixed:+ * Copilot rebuilds a resumed conversation's first message without what `SessionStart` added:+ the facts were gone and that message missed the cache. The plugin now records the text a+ session started with and gives it again on a Copilot resume, which rebuilds the message+ exactly; a session that started without facts gets none.+ * Pi rebuilds its system message from the conversation's own entries, and the extension left+ its section out on a resume, which Pi recorded as removed. Pi also reports `pi -c` and+ `--session` as `startup`, not `resume`, and stores a section wrapped in `<name>` tags. The+ extension now decides by whether the branch already holds messages, and gives such a+ conversation back the section it carries, unwrapped (`carriedSection`): two resumes after a+ fact was retired on disk kept the original system message, and a new session took the+ current facts.+## 4. State and privacyAll state is local, under `$TOKENECONOMIZER_HOME` (default `~/.tokeneconomizer`), one directorydiff --git a/plugin/README.md b/plugin/README.mdindex f4db744..a42ce23 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -14,7 +14,7 @@ behaviour of each agent are in [`docs/PLUGIN.md`](../docs/PLUGIN.md).## Before you start- [ ] Your agent installed and signed in, any way it supports (a subscription or an API key), at a- version the commands were checked on ([Supported versions](../README.md#supported-versions))+ supported version ([Supported versions](../README.md#supported-versions))- [ ] Python 3.10 or newer on `PATH` (or set `TE_PYTHON=/path/to/python3.10+`)- [ ] Access to this repository on GitHub- [ ] Copilot CLI only: the repository's folder trusted by Copilot (it asks the first time you@@ -60,8 +60,9 @@ machine, and again after Claude Code updates. **Don't skip it:** without it theonly the few tools Claude Code defers, not the ones every session loads.**4. Work normally.** See [What to expect](#what-to-expect). Once tools have gone unused for-about five sessions, the plugin leaves them out of the next sessions without asking you, and the-session start says so once:+about five sessions, the plugin leaves them out of the next sessions without asking you (it+writes the list once your sessions here have been idle for an hour), and the session start says+so once:```text/tokeneconomizer:toolprune # the tools it left out, and the evidence@@ -72,7 +73,7 @@ The rules go into this repository's `.claude/settings.local.json`, which the plugit, and it never touches deny rules you wrote. To approve each deny list yourself instead:`/tokeneconomizer:config set toolprune=propose`, then `/tokeneconomizer:toolprune apply`.-**Where its messages appear.** Claude Code 2.1.306 shows the plugin's one-line messages (facts+**Where its messages appear.** Claude Code shows the plugin's one-line messages (factsadded, tools left out) only in its detailed transcript: press **Ctrl+O**, where they read`<event> says: TokenEconomizer: …`. A turn that still looks stuck is the exception:the plugin also asks Claude to repeat that line word for word, so it shows in Claude's reply,@@ -262,7 +263,9 @@ pi install git:github.com/microsoft/TokenEconomizer```(Over SSH: `pi install git:[email protected]:microsoft/TokenEconomizer`. From a clone:-`pi install /path/to/TokenEconomizer`.)+`pi install /path/to/TokenEconomizer`.) On Pi 0.99.x, install nothing: clone the repository and+start each session with `pi --extension /path/to/TokenEconomizer/plugin/pi/tokeneconomizer.ts`,+using your clone's full path; `git pull` in the clone updates it.**2. Check it.** Start a new Pi session and type `/te status`. The commands are `/te status`,`/te microskills`, `/te config …` and `/te repos`; from a terminal, inside the repository,@@ -283,13 +286,18 @@ from); `pi config` turns it off without removing it. Optional: `rm -rf ~/.tokene- **Facts.** A fact forms once the same environment failure has come up in a few sessions (threeconfirming ones, among at least four where it applied), and is injected at every session startafter that while the failure keeps occurring or keeps being prevented. A session start that- adds facts says so once, in one line. `microskills` shows the facts injected and those forming.+ adds facts says so once, in one line. A resumed session keeps the facts it started with, word+ for word, so its cached prompt still matches. `microskills` shows the facts injected and those+ forming.- **Deny list.** Applied without asking you, after about five sessions in which a tool, package- or server went unused, from the next session on; that session's start says so once. `toolprune restore` gives- back what the plugin removed, and only that, and what you give back is never removed again- (`toolprune apply NAME` removes one again). With `toolprune=propose`, it is only proposed, the- session start says so, and nothing changes until you run `toolprune apply`. A file the plugin- creates is added to `.git/info/exclude`.+ or server went unused, from the next session on; that session's start says so once. It is+ written once the repository's sessions have been idle for an hour: a conversation resumed+ after its tools change writes its whole history to the prompt cache again instead of reading+ it, and after an idle hour that cache has expired anyway. `toolprune` shows a list still+ waiting. `toolprune restore` gives back what the plugin removed, and only that, and what you+ give back is never removed again (`toolprune apply NAME` removes one again). With+ `toolprune=propose`, it is only proposed, the session start says so, and nothing changes+ until you run `toolprune apply`. A file the plugin creates is added to `.git/info/exclude`.- **Loop guard.** Quiet on normal turns. On a turn that keeps failing the same way well past thisrepository's usual length, one redirect is attached to a tool result; if the turn is still stuckafter it, a one-line notice tells you how to stop it. The plugin never stops a turn itself.@@ -363,8 +371,8 @@ and are shared by every agent working in it. The examples use Claude Code's form| Mechanism | Key | `on` means | Other values ||---|---|---|---|| Micro-skills | `microskills` | `envfacts`: facts found without model calls | `off`; `envfacts+distiller`, `distiller` add a paid fact proposer (need `paid=true`) |-| Tool pruning | `toolprune` | `auto`: applied as soon as it forms, from the next session, and announced | `off`; `propose`: only proposed, applied when you run `toolprune apply` |-| Loop guard | `loopguard` | `nudge`: one mid-turn redirect, then a notice to you if the turn is still stuck | `off`; `stop` (which once stopped a headless turn on Claude Code and Pi) is read as `nudge`, with a warning |+| Tool pruning | `toolprune` | `auto`: applied once it forms and your sessions have been idle an hour, from the next session, and announced | `off`; `propose`: only proposed, applied when you run `toolprune apply` |+| Loop guard | `loopguard` | `nudge`: one mid-turn redirect, then a notice to you if the turn is still stuck | `off`; `stop` is read as `nudge`, with a warning |**Tune a mechanism:**@@ -381,6 +389,7 @@ and are shared by every agent working in it. The examples use Claude Code's form| `microskills_max_tokens` | `150` | the size of the injected block, in tokens (about 4 characters each) || `microskills_propose_every` | `5` | sessions between runs of the paid fact proposer || `toolprune_evidence` | `5` | sessions a tool must go unused before it is left out (three times as long for a few higher-risk tools; the web is never proposed) |+| `toolprune_quiet_minutes` | `60` | how long the repository's sessions must have been idle before `auto` writes a deny list, so that no conversation resumed while its prompt cache is warm loses it; `0` writes at once || `loopguard_aggr` | `default` | the guard's threshold preset: `conservative`, `default` or `aggressive` || `loopguard_nudges` | `1` | redirects per prompt-turn before the guard only notifies you || `loopguard.<name>` | from the preset | one guard threshold, set by hand (below) |@@ -434,8 +443,8 @@ deny list at the next session start. A new fact-size cap shows once the next ses**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` as-`loopguard=stop`, which now works as `nudge`), and a new name set alongside its old one wins.+variables `TE_INJECT`, `TE_UNTOOL`, `TE_SPIRAL`, ...; all of them are still read (`spiral=guard`+as `loopguard=stop`, which works as `nudge`), and a new name set alongside its old one wins.`config set` writes the new name. The earlier commands `te facts` and `te untool`, and`/tokeneconomizer:facts` and `/tokeneconomizer:untool`, still work.diff --git a/plugin/pi/tokeneconomizer.ts b/plugin/pi/tokeneconomizer.tsindex a30dec0..26b18b7 100644--- a/plugin/pi/tokeneconomizer.ts+++ b/plugin/pi/tokeneconomizer.ts@@ -7,7 +7,8 @@* JSON out), and the answer is applied with Pi's own levers. All of the mechanism logic lives* in the dispatcher; this file only translates.*- * session_start -> SessionStart the learned manual, kept for the session+ * session_start -> SessionStart the learned manual, kept for the session (a+ * resumed one keeps the manual it carries)* before_agent_start -> UserPromptSubmit opens a prompt-turn; the manual is set as the* `tokeneconomizer` system-prompt section, on every* prompt, because Pi diffs sections between runs and@@ -97,8 +98,8 @@ function notify(ctx: ExtensionContext, text: unknown) {}const SOURCE: Record<string, string> = {- // A new conversation starts empty; a resumed, forked or reloaded one already carries the- // section it was given, in its own system-message history.+ // For a conversation that starts empty. One that already holds messages is a resumption,+ // whatever the reason says (`carriedSection`).startup: "startup",new: "clear",resume: "resume",@@ -106,6 +107,31 @@ const SOURCE: Record<string, string> = {reload: "resume",};+/** The section a conversation that already holds messages carries. Pi replays its system+ * entries -- each patches `sections` by name, `null` removing one, and a compaction restates+ * them all -- into the leading system message of every request, so such a conversation must+ * be given the same text again: leaving it out records it as removed, and the facts are gone;+ * new facts would change the system message. Either way the whole conversation would be+ * re-read at the uncached price. Pi says "startup", not "resume", for a conversation opened+ * with `pi -c` or `--session`, so the messages decide (both verified on Pi 1.3.0). */+export function carriedSection(entries: any[]): string {+ let text = "";+ for (const entry of entries) {+ if (entry?.type === "compaction" && entry.systemMessage?.sections) {+ text = entry.systemMessage.sections[SECTION] ?? "";+ } else if (entry?.type === "message" && entry.message?.role === "system"+ && entry.message.sections && SECTION in entry.message.sections) {+ text = entry.message.sections[SECTION] ?? "";+ }+ }+ // Pi stores a section as it renders it, `<name>\n...\n</name>`, and wraps what it is given.+ const open = `<${SECTION}>\n`;+ const close = `\n</${SECTION}>`;+ return text.startsWith(open) && text.endsWith(close)+ ? text.slice(open.length, text.length - close.length)+ : text;+}+export default function tokeneconomizer(pi: ExtensionAPI) {let manual = "";let prompts = 0;@@ -119,11 +145,11 @@ export default function tokeneconomizer(pi: ExtensionAPI) {pi.on("session_start", async (event, ctx) => {prompts = 0;- const out = await hook(- { ...base(ctx), hook_event_name: "SessionStart", source: SOURCE[event.reason] ?? "startup" },- ctx.mode,- );- manual = out?.hookSpecificOutput?.additionalContext ?? "";+ const entries = (ctx.sessionManager.getBranch?.() ?? []) as any[];+ const carried = entries.some((e) => e?.type === "message");+ const source = carried ? "resume" : SOURCE[event.reason] ?? "startup";+ const out = await hook({ ...base(ctx), hook_event_name: "SessionStart", source }, ctx.mode);+ manual = carried ? carriedSection(entries) : out?.hookSpecificOutput?.additionalContext ?? "";notify(ctx, out?.systemMessage);});diff --git a/tests/test_live_config.py b/tests/test_live_config.pyindex fc37425..9d37f2f 100644--- a/tests/test_live_config.py+++ b/tests/test_live_config.py@@ -203,3 +203,13 @@ def test_loopguard_stop_is_still_read_and_acts_as_nudge_with_a_warning(tmp_path)assert cfg.loopguard == "stop"assert any("loopguard=stop acts as nudge" in w for w in cfg.warnings)assert not load_config(str(tmp_path), env={"TE_LOOPGUARD": "nudge"}).warnings+++def test_the_quiet_window_before_a_deny_list_is_written_may_be_zero():+ cfg = LiveConfig()+ assert cfg.toolprune_quiet_minutes == 60+ assert cfg.set("toolprune_quiet_minutes", "0") and cfg.toolprune_quiet_minutes == 0+ assert not cfg.set("toolprune_quiet_minutes", "-5")+ 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 == 15diff --git a/tests/test_live_hooks.py b/tests/test_live_hooks.pyindex a584ade..33ef8cb 100644--- a/tests/test_live_hooks.py+++ b/tests/test_live_hooks.py@@ -2,10 +2,10 @@Each test drives a whole stretch of a repository's life -- sessions starting, prompt-turns, toolcalls, sessions ending and being folded -- and pins one property the live layer must have:-learned facts reach the next session's context, the spiral guard is silent until it has learned-the repository and then nudges before it stops, an untool proposal changes nothing until it is-applied and touches only its own deny rules, every session is folded exactly once, and nothing-here can break the agent's session.+learned facts reach the next session's context, the loop guard is silent until it has learned+the repository and then redirects before it tells the person, a deny list is written only once+the repository's sessions are idle and touches only its own deny rules, every session is folded+exactly once, and nothing here can break the agent's session.Folds run inline (`TE_FOLD_SYNC=1`); in the plugin they are detached processes."""@@ -13,10 +13,12 @@ import globimport ioimport jsonimport os+import timeimport pytest-from tokeneconomizer.plugin import denylist, hook, hosts, toolcheck+from tokeneconomizer.plugin import denylist, fold, hook, hosts, toolcheck+from tokeneconomizer.plugin.context import LiveContextfrom tokeneconomizer.plugin.controller import LiveControllerfrom tokeneconomizer.plugin.paths import repo_identity, repo_state_dirfrom tokeneconomizer.plugin.store import Store@@ -25,6 +27,8 @@ from tokeneconomizer.plugin.store import Store@pytest.fixturedef env(tmp_path):return {"TOKENECONOMIZER_HOME": str(tmp_path / "home"), "TE_FOLD_SYNC": "1",+ # A deny list is written at the fold here; the wait before it has its own tests.+ "TE_TOOLPRUNE_QUIET_MINUTES": "0","GIT_CEILING_DIRECTORIES": str(tmp_path), "PATH": os.environ.get("PATH", "")}@@ -149,6 +153,29 @@ def test_resume_does_not_inject_again_and_shadow_never_injects(env, repo, tmp_paassert any(e["kind"] == "inject" and e["shadow"] for e in events)+def test_a_resumed_copilot_session_gets_back_the_facts_it_started_with(env, repo, tmp_path,+ monkeypatch):+ """Copilot 1.0.102 rebuilds a resumed conversation's first message without what SessionStart+ added: the facts are gone, and that message no longer matches the prompt cache. The text the+ session started with, given again, rebuilds it as it was; a session that started without+ facts gets none, and a new session gets the facts as they are now."""+ monkeypatch.setenv("COPILOT_HOME", str(tmp_path / "copilot-home"))+ st = store_for(env, repo, host="copilot")+ st.write("injection.json", {"rendered": "Facts:\n- one\n- two", "rendered_ids": ["a", "b"]})++ def start(sid, source):+ return json.dumps(call(env, {"hook_event_name": "SessionStart", "session_id": sid,+ "source": source, "cwd": repo}, "copilot"))+ assert "- two" in start("c1", "new")+ st.write("injection.json", {"rendered": "Facts:\n- one", "rendered_ids": ["a"]})+ assert "- two" in start("c1", "resume") # as it started, not as now+ assert "- two" not in start("c2", "new") and "- one" in start("c3", "new")+ st.write("injection.json", {"rendered": "", "rendered_ids": []})+ start("c4", "new")+ st.write("injection.json", {"rendered": "Facts:\n- one", "rendered_ids": ["a"]})+ assert "- one" not in start("c4", "resume") # started without facts++# ---- the spiral guard --------------------------------------------------------------------def _turn(env, repo, sid, key, calls, host=None):"""One prompt-turn through UserPromptSubmit -> PostToolUse* -> Stop; outputs per call."""@@ -422,6 +449,117 @@ def test_tools_given_back_stay_back_until_named_again(env, repo, tmp_path, monkeassert denylist.kept_for(store_for(env, repo), repo) == ["CronCreate"]+def _pending_repo(env, repo, tmp_path, quiet="60"):+ """Five sessions that leave three tools unused, under the default wait before writing."""+ env = dict(env, TE_TOOLPRUNE_QUIET_MINUTES=quiet)+ _catalog(env, ["Bash", "Read", "Edit", "Write", "AskUserQuestion", "Workflow",+ "CronCreate", "ShareOnboardingGuide", "WebFetch"])+ for i in range(5):+ t = write_session(str(tmp_path / f"u{i}.jsonl"), [("look", [+ ("Read", {"file_path": f"{repo}/a.py"}, "x", False),+ ("Bash", {"command": "ls"}, "a.py", False)])])+ run_session(env, repo, f"u{i}", t)+ return env, LiveContext.build(hosts.ClaudeCode(), repo, env)+++def _deny(repo):+ path = denylist.settings_path(repo)+ return sorted(json.load(open(path))["permissions"]["deny"]) if os.path.exists(path) else []+++def test_by_default_a_deny_list_waits_until_the_repositorys_sessions_have_been_idle(+ env, repo, tmp_path, monkeypatch, capsys):+ """A conversation resumed after its tools changed re-writes its whole history to the prompt+ cache (Claude Code 2.1.307), so `auto` writes a new list only once every session has been+ idle longer than a cache lives -- silently until then, and announced once written."""+ from tokeneconomizer.plugin import cli+ env, ctx = _pending_repo(env, repo, tmp_path)+ assert _deny(repo) == []+ pend = ctx.store.read("untool.json")["auto_pending"]+ assert sorted(pend["items"]) == ["CronCreate", "ShareOnboardingGuide", "Workflow"]+ t = str(tmp_path / "next.jsonl")+ open(t, "w").close()++ def start(sid):+ return call(env, {"hook_event_name": "SessionStart", "session_id": sid,+ "source": "startup", "transcript_path": t, "cwd": repo})+ assert "went unused" not in start("n1").get("systemMessage", "")+ for k, v in env.items():+ monkeypatch.setenv(k, v)+ assert cli.main(["--host", "claude", "--cwd", repo, "toolprune", "show"]) == 0+ assert "pending: written once this repository's sessions have been idle 60 minutes" in (+ capsys.readouterr().out)+ now = time.time()+ wait = fold.apply_pending(ctx, now=now + 600) # ten idle minutes: not yet+ assert 2900 < wait <= 3000 and _deny(repo) == []+ assert fold.apply_pending(ctx, now=now + 3700) is None # an idle hour: written+ assert _deny(repo) == ["CronCreate", "ShareOnboardingGuide", "Workflow"]+ assert "auto_pending" not in ctx.store.read("untool.json")+ assert "removed 3 tool(s)" in start("n2")["systemMessage"]+++def test_a_session_still_writing_its_log_keeps_the_deny_list_waiting(env, repo, tmp_path):+ """Activity is a hook call or a line in the session's own log: a session can go an hour+ without a hook (one long answer, or the loop guard off) and still have a warm cache."""+ env, ctx = _pending_repo(env, repo, tmp_path)+ old = time.time() - 7200+ logs = glob.glob(str(tmp_path / "u*.jsonl"))+ for f in glob.glob(ctx.store.path("sessions", "*.json")) + logs:+ os.utime(f, (old, old))+ os.utime(str(tmp_path / "u4.jsonl")) # no hook for two hours, but its log moved now+ assert fold.apply_pending(ctx) > 3500 and _deny(repo) == []+ os.utime(str(tmp_path / "u4.jsonl"), (old, old))+ assert fold.apply_pending(ctx) is None and len(_deny(repo)) == 3+++def test_a_deny_list_that_waited_a_day_is_written_even_if_sessions_never_pause(+ env, repo, tmp_path):+ env, ctx = _pending_repo(env, repo, tmp_path)+ st = ctx.store.read("untool.json")+ st["auto_pending"]["since"] = time.time() - fold.PENDING_MAX_S - 1+ ctx.store.write("untool.json", st)+ assert fold.apply_pending(ctx) is None and len(_deny(repo)) == 3+++def test_a_pending_deny_list_leaves_out_what_was_given_back_meanwhile(env, repo, tmp_path):+ env, ctx = _pending_repo(env, repo, tmp_path)+ denylist.set_kept(ctx.store, repo, "claude", add=["Workflow"]) # `restore`d earlier+ assert fold.apply_pending(ctx, now=time.time() + 3700) is None+ assert _deny(repo) == ["CronCreate", "ShareOnboardingGuide"]+++def test_a_pending_deny_list_is_dropped_once_toolprune_is_no_longer_auto(env, repo, tmp_path):+ env, ctx = _pending_repo(env, repo, tmp_path)+ ctx = LiveContext.build(hosts.ClaudeCode(), repo, dict(env, TE_TOOLPRUNE="propose"))+ assert fold.apply_pending(ctx, now=time.time() + 3700) is None+ unt = ctx.store.read("untool.json")+ assert _deny(repo) == [] and "auto_pending" not in unt and len(unt["proposal"]) == 3+++def test_the_fold_leaves_one_detached_waiter_and_a_second_one_leaves(+ env, repo, tmp_path, monkeypatch):+ from tokeneconomizer.plugin import cli+ env, ctx = _pending_repo(env, repo, tmp_path)+ spawned = []+ monkeypatch.setattr(LiveContext, "spawn", lambda self, argv, log: spawned.append(argv))+ detached = LiveContext.build(hosts.ClaudeCode(), repo,+ {k: v for k, v in env.items() if k != "TE_FOLD_SYNC"})+ assert fold.schedule_pending(detached) > 0+ assert spawned == [["toolprune", "apply-pending"]]++ for k, v in env.items():+ monkeypatch.setenv(k, v)+ monkeypatch.setattr(time, "sleep", lambda s: (_ for _ in ()).throw(AssertionError(s)))+ beat = ctx.store.path("toolprune-waiter")+ open(beat, "w").close() # another waiter is alive+ assert cli.main(["--host", "claude", "--cwd", repo, "toolprune", "apply-pending"]) == 0+ assert _deny(repo) == [] and os.path.exists(beat)+ os.remove(beat)+ monkeypatch.setenv("TE_TOOLPRUNE_QUIET_MINUTES", "0") # quiet enough at once+ assert cli.main(["--host", "claude", "--cwd", repo, "toolprune", "apply-pending"]) == 0+ assert len(_deny(repo)) == 3 and not os.path.exists(beat)++def test_the_web_is_never_proposed_and_an_old_deny_rule_for_it_is_given_back(env, repo, tmp_path):_catalog(env, ["Bash", "Read", "CronCreate", "WebFetch", "WebSearch"])diff --git a/tests/test_live_repos.py b/tests/test_live_repos.pyindex 8cac917..33cad9d 100644--- a/tests/test_live_repos.py+++ b/tests/test_live_repos.py@@ -45,6 +45,8 @@ def env(tmp_path):home = tmp_path / "home"home.mkdir()return {"TOKENECONOMIZER_HOME": str(tmp_path / "te"), "TE_FOLD_SYNC": "1",+ # A deny list is written at the fold here; the wait before it has its own tests.+ "TE_TOOLPRUNE_QUIET_MINUTES": "0","GIT_CEILING_DIRECTORIES": str(tmp_path), "HOME": str(home),"PATH": os.environ.get("PATH", "")}diff --git a/tests/test_plugin_package.py b/tests/test_plugin_package.pyindex ba8345c..3073c0d 100644--- a/tests/test_plugin_package.py+++ b/tests/test_plugin_package.py@@ -9,6 +9,7 @@ it -- which is what a marketplace install, copying only the plugin directory, acimport jsonimport osimport re+import shutilimport subprocessimport sys@@ -250,6 +251,40 @@ def test_the_package_is_stdlib_only_and_never_touches_the_benchmark_harness():"tokeneconomizer", "tomllib"), f"{path} imports non-stdlib {mod}"+def test_a_resumed_pi_conversation_keeps_the_section_it_carries():+ """Pi rebuilds a conversation's system message from its system entries, so a resumed one is+ given back the facts section it carries, byte for byte: unwrapped from the `<name>` tags Pi+ stores it in (Pi wraps it again), gone once a patch removed it, and as a compaction restated+ it. Run through Node, which loads the extension's TypeScript directly."""+ node = shutil.which("node")+ if not node:+ pytest.skip("node is not installed")+ ext = os.path.join(PLUGIN, "pi", "tokeneconomizer.ts")+ script = """+const { carriedSection } = await import(process.argv[1]);+const sys = (sections) => ({ type: "message", message: { role: "system", sections } });+const compact = (sections) => ({ type: "compaction", systemMessage: { sections } });+const user = { type: "message", message: { role: "user" } };+const facts = sys({ tokeneconomizer: "<tokeneconomizer>\\nFacts:\\n- one\\n</tokeneconomizer>" });+console.log(JSON.stringify([+ carriedSection([]),+ carriedSection([facts, user]),+ carriedSection([facts, sys({ cwd: "<cwd>\\n/x\\n</cwd>" })]),+ carriedSection([facts, sys({ tokeneconomizer: null })]),+ carriedSection([facts, compact({ cwd: "c" })]),+ carriedSection([compact(facts.message.sections)]),+]));+"""+ run = subprocess.run([node, "--experimental-strip-types", "--no-warnings",+ "--input-type=module", "-e", script, ext],+ capture_output=True, text=True, timeout=60)+ if run.returncode and "strip-types" in run.stderr:+ pytest.skip("this node cannot load TypeScript")+ assert run.returncode == 0, run.stderr+ facts = "Facts:\n- one"+ assert json.loads(run.stdout) == ["", facts, facts, "", "", facts]++def test_the_plugin_directory_is_also_a_pi_package():"""One directory, three agents: Pi loads the extension its `pi` manifest names, and thatextension drives the same launchers the Claude Code and Codex hooks run."""diff --git a/tokeneconomizer/plugin/cli.py b/tokeneconomizer/plugin/cli.pyindex c7d76c7..1e45efe 100644--- a/tokeneconomizer/plugin/cli.py+++ b/tokeneconomizer/plugin/cli.py@@ -9,6 +9,8 @@te toolprune restore [ITEM ...] remove entries this plugin addedte toolprune refresh-catalog record the tool list a fresh session loads (Claude, Copilot)te toolprune measure measure the request with and without the proposal+ te toolprune apply-pending write a pending `auto` deny list once the repository has+ been idle long enough (the fold starts it, detached)te config show each mechanism on or off, its settings, the guard's thresholdste config set KEY=VALUE ... e.g. `loopguard=off`, `microskills=on`,`loopguard.min_turns=12` (this repository; `--global` for@@ -194,6 +196,12 @@ def _toolprune_show(ctx, unt):f"{denylist.settings_path(ctx.repo.root, host)}): "f"{', '.join(denylist.applied_for(ctx.store, ctx.repo.root, host)) or '-'}")print(f"proposed: {', '.join(_proposal(ctx, unt)) or '-'}")+ pending = [t for t in (unt.get("auto_pending") or {}).get("items") or []+ if t in _proposal(ctx, unt)]+ if pending and ctx.config.toolprune == "auto":+ print(f"pending: written once this repository's sessions have been idle "+ f"{ctx.config.toolprune_quiet_minutes} minutes, so that no conversation you "+ f"resume re-reads its cached prompt (`toolprune apply` writes it now)")kept = denylist.kept_for(ctx.store, ctx.repo.root, host)if kept:print(f"kept, as you gave them back (`toolprune apply NAME` removes one again): "@@ -236,6 +244,36 @@ def _toolprune_show(ctx, unt):return 0+def _wait_and_apply(args):+ """`toolprune apply-pending`, which the fold leaves running, detached: wait until the pending+ `auto` deny list can be written without costing a warm prompt cache (`fold.apply_pending`),+ looking again as sessions come and go, then write it. One waiter per repository and agent:+ a second finds the first one's heartbeat fresh and leaves."""+ ctx = _ctx(args)+ beat = ctx.store.path("toolprune-waiter")+ try:+ if time.time() - os.path.getmtime(beat) < 2 * fold.WAITER_POLL_S:+ return 0+ except OSError:+ pass+ ctx.store.ensure()+ with open(beat, "w") as fh:+ fh.write(str(os.getpid()))+ try:+ while True:+ wait = fold.apply_pending(ctx)+ if wait is None:+ return 0+ time.sleep(min(max(wait, 1.0), fold.WAITER_POLL_S))+ os.utime(beat)+ ctx = _ctx(args) # the settings may have changed meanwhile+ finally:+ try:+ os.remove(beat)+ except OSError:+ pass++def _proposal(ctx, unt):"""The proposal, less what this checkout already applied or gave back: the clones of onerepository share its evidence, and one of them may have applied the list before another."""@@ -312,6 +350,8 @@ def cmd_toolprune(args):+ (f"; kept from now on (`toolprune apply {removed[0]}` removes one again)"if removed else ""))return 0+ if action == "apply-pending":+ return _wait_and_apply(args)if action == "refresh-catalog":if host == "codex":print("Codex needs no catalog: its removable capabilities are a fixed set "@@ -383,7 +423,8 @@ def _config_view(cfg):"microskills_propose_every": d.pop("microskills_propose_every")},"toolprune": {"state": "off" if cfg.toolprune == "off" else "on","toolprune": d.pop("toolprune"),- "toolprune_evidence": d.pop("toolprune_evidence")},+ "toolprune_evidence": d.pop("toolprune_evidence"),+ "toolprune_quiet_minutes": d.pop("toolprune_quiet_minutes")},"loopguard": {"state": "off" if cfg.loopguard == "off" else "on","loopguard": d.pop("loopguard"), "loopguard_aggr": d.pop("loopguard_aggr"),@@ -647,7 +688,8 @@ def build_parser():add("microskills", "facts").set_defaults(fn=cmd_microskills)p = add("toolprune", "untool")p.add_argument("action", nargs="?", default="show",- choices=("show", "apply", "restore", "refresh-catalog", "measure"))+ choices=("show", "apply", "restore", "refresh-catalog", "measure",+ "apply-pending"))p.add_argument("tools", nargs="*")p.set_defaults(fn=cmd_toolprune)p = add("config")diff --git a/tokeneconomizer/plugin/config.py b/tokeneconomizer/plugin/config.pyindex 5a7f7f2..d734ad5 100644--- a/tokeneconomizer/plugin/config.py+++ b/tokeneconomizer/plugin/config.py@@ -4,8 +4,9 @@ The defaults:* microskills = "envfacts" -- the LLM-free facts only. The paid proposer (`envfacts+distiller`,`distiller`) is opt-in, and refused unless `paid` is also true;- * toolprune = "auto" -- a deny list is applied as soon as the evidence forms it, from- the next session, and announced once at that session's start;+ * 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 personruns `toolprune apply`;@@ -26,6 +27,9 @@ person can tune by hand:* microskills_max_facts, microskills_max_tokens -- caps on the injected block;* microskills_propose_every -- sessions between paid proposer runs;* toolprune_evidence -- unused sessions before a tool is proposed;+ * toolprune_quiet_minutes -- how long every session of the repository must have been idle+ before `auto` writes a deny list (0: at once), so that no+ conversation resumed with a warm prompt cache loses it;* loopguard_aggr -- the guard's threshold preset;* loopguard_nudges -- redirects per prompt-turn before the guard only notifies;* loopguard.<name> -- one guard threshold, pinned over the preset and over what the@@ -124,6 +128,7 @@ class LiveConfig:microskills_propose_every: int = 5toolprune: str = "auto"toolprune_evidence: int = 5+ toolprune_quiet_minutes: int = 60loopguard: str = "nudge"loopguard_aggr: str = "default"loopguard_nudges: int = 1@@ -141,6 +146,8 @@ class LiveConfig:_CHOICES = {"mode": MODES, "microskills": MICROSKILLS, "toolprune": TOOLPRUNE,"loopguard": LOOPGUARD, "repomap": REPOMAP, "loopguard_aggr": AGGR,"vocabulary": ("auto", "python-git", "node-web")}+ # The smallest value a number setting takes, where it is not 1.+ _MIN = {"toolprune_quiet_minutes": 0}def as_dict(self):d = asdict(self)@@ -177,8 +184,9 @@ class LiveConfig:"1", "true", "yes", "on")elif isinstance(cur, int):v = int(value)- if v < 1:- raise ValueError("must be >= 1")+ lo = self._MIN.get(key, 1)+ if v < lo:+ raise ValueError(f"must be >= {lo}")else:v = str(value).strip()except (TypeError, ValueError) as e:@@ -234,6 +242,7 @@ _ENV = {"TE_MODE": "mode", "TE_PAID": "paid", "TE_SHADOW": "shadow","TE_MICROSKILLS_MAX_TOKENS": "microskills_max_tokens","TE_MICROSKILLS_PROPOSE_EVERY": "microskills_propose_every","TE_TOOLPRUNE": "toolprune", "TE_TOOLPRUNE_EVIDENCE": "toolprune_evidence",+ "TE_TOOLPRUNE_QUIET_MINUTES": "toolprune_quiet_minutes","TE_LOOPGUARD": "loopguard", "TE_LOOPGUARD_AGGR": "loopguard_aggr","TE_LOOPGUARD_NUDGES": "loopguard_nudges","TE_REPOMAP": "repomap", "TE_REPOMAP_TOKENS": "repomap_tokens",diff --git a/tokeneconomizer/plugin/controller.py b/tokeneconomizer/plugin/controller.pyindex acf716c..3d4f54f 100644--- a/tokeneconomizer/plugin/controller.py+++ b/tokeneconomizer/plugin/controller.py@@ -104,14 +104,22 @@ class LiveController:if self.cfg.microskills != "off":inj = self.store.read("injection.json") or {}text = inj.get("rendered") or ""- # A resumed or forked conversation already carries what the first start injected;- # a cleared or compacted one has lost it. ("new" is Copilot's word for "startup".)- if text and source in ("startup", "new", "clear", "compact"):+ # A resumed or forked conversation already carries what the first start injected,+ # where the agent replays it; a cleared or compacted one has lost it. ("new" is+ # Copilot's word for "startup".)+ fresh = source in ("startup", "new", "clear", "compact")+ if not fresh and not self.host.keeps_start_context:+ # The agent rebuilt the conversation without what its first start added: the+ # same text again puts it back as it was (and as its prompt cache has it), so a+ # session that started without facts gets none either.+ text = s.get("injected_text", text if s.get("injected_chars") else "")+ if text and (fresh or not self.host.keeps_start_context):n_facts = sum(1 for ln in text.splitlines() if ln.startswith("- "))self._log("inject", chars=len(text), facts=n_facts, source=source)if not self.cfg.shadow:outputs.append(self.host.context("SessionStart", text))s["injected_chars"] = len(text)+ s["injected_text"] = textif "rendered_ids" in inj: # which facts, for this session's folds["injected_ids"] = list(inj["rendered_ids"])digest = hashlib.sha1(text.encode("utf-8")).hexdigest()@@ -176,8 +184,12 @@ class LiveController:# not have).kept = set(denylist.kept_for(self.store, root, self.host.name))prop = [t for t in unt.get("proposal") or [] if t not in mine and t not in kept]+ refused = unt.get("auto_apply_refused") if self.cfg.toolprune == "auto" else None+ # Under `auto`, a list waiting for the repository to go quiet is no news yet: the+ # session start after it is written says so (above). Only a refusal is.+ if self.cfg.toolprune == "auto" and not refused:+ prop = []if prop and seen.get("untool") != ",".join(prop):- refused = unt.get("auto_apply_refused") if self.cfg.toolprune == "auto" else Noneout.append(self.host.notice(f"TokenEconomizer: {len(prop)} {unit}(s) went unused in this repository's recent "f"sessions ({few(prop)}). Review with `{cmd}`; "diff --git a/tokeneconomizer/plugin/denylist.py b/tokeneconomizer/plugin/denylist.pyindex ad2ffa5..67799bc 100644--- a/tokeneconomizer/plugin/denylist.py+++ b/tokeneconomizer/plugin/denylist.py@@ -23,10 +23,13 @@ session start, and the unit of removal is whatever that file can express:Rules common to all three:- * `toolprune: auto` (the default) writes the file as soon as a proposal forms, and the next+ * `toolprune: auto` (the default) writes the file once a proposal forms and the repository's+ sessions have been idle for `toolprune_quiet_minutes` (`fold.apply_pending`), and the nextsession start says so; with `toolprune: propose` only the person's approval (`te toolprune- apply`) does. Either way it applies from the NEXT session: tools are fixed at session- start, and changing them mid-session would rewrite the cached prompt prefix.+ apply`) does. Either way it applies from the NEXT session. Verified on Claude Code 2.1.307,+ Codex 0.163.0 and Copilot 1.0.102 (docs/PLUGIN.md §3): a running session keeps the tools+ it started with; a conversation resumed after the change sends the new tools, which+ re-writes its whole history to the prompt cache -- hence the wait.* The writer adds and removes exactly the entries it recorded adding (`untool_applied.json`,per settings file, since the clones of one repository share its state but not theirsettings); an entry the person wrote is never touched.diff --git a/tokeneconomizer/plugin/fold.py b/tokeneconomizer/plugin/fold.pyindex 9ab88d1..d1e7768 100644--- a/tokeneconomizer/plugin/fold.py+++ b/tokeneconomizer/plugin/fold.py@@ -39,6 +39,18 @@ STALE_S = 600 # an unfolded session whose transcript is quiet this lon# session, or, if it died, the session stays pending and the next SessionStart folds it.FOLD_LOCK_WAIT_S = sidecall.TIMEOUT_S + 60+# A deny list changes the tools a session sends, and the tools open the cached prompt prefix.+# A running session keeps the tools it started with, but a conversation resumed after the change+# sends the new ones, so its whole history is written to the prompt cache again instead of read+# from it (both verified on Claude Code 2.1.307, Codex 0.163.0 and Copilot 1.0.102). The fold+# runs just after a session ends, when that session's cache is warmest and resuming it is+# likeliest, so `auto` holds a new list as pending and writes it only once every session of the+# repository has been idle longer than a prompt cache lives (`toolprune_quiet_minutes`): then a+# resumed or new session finds the cache cold anyway. A list that has waited a day is written+# regardless, so a repository whose sessions never pause still gets it.+PENDING_MAX_S = 24 * 3600+WAITER_POLL_S = 600 # how often the waiter looks again, and so how fresh its heartbeat is+def _run_dir(workdir, trace_path):run = os.path.join(workdir, "run")@@ -138,17 +150,13 @@ def _fold_toolprune(ctx, adapter, run_dir, session_id, transcript=None, workdir=if t not in applied and t not in kept]doc["proposal"] = proposaldoc["new_in_proposal"] = sorted(set(proposal) - set(st.get("proposal", [])))- added = []if ctx.config.toolprune == "auto" and proposal and not ctx.config.shadow:- try:- added = denylist.apply(ctx.repo.root, proposal, ctx.store, host=host)- doc["proposal"], doc["auto_applied"] = [], added- except RuntimeError as e: # an unreadable or redirected file: keep proposing- doc["auto_apply_refused"] = str(e)+ _hold(doc, st, proposal, ctx.repo.root)if restored:doc["restored_protected"] = restoredctx.store.write("untool.json", doc)- return {"proposal": doc["proposal"], "applied_now": added, "restored": restored}+ return {"proposal": doc["proposal"], "pending": bool(doc.get("auto_pending")),+ "restored": restored}def _server_summary(stage, servers):@@ -213,15 +221,84 @@ def _fold_toolprune_codex(ctx, adapter, session_id, transcript, workdir):for c in denylist.CODEX_LIVE_CAPABILITIES},"proposal": proposal, "updated": time.time(),"new_in_proposal": sorted(set(proposal) - set(prior.get("proposal", [])))}- added = []if ctx.config.toolprune == "auto" and proposal and not ctx.config.shadow:- try:- added = denylist.apply(ctx.repo.root, proposal, ctx.store, host="codex")- doc["proposal"], doc["auto_applied"] = [], added- except RuntimeError as e: # a committed or unparseable file: keep proposing- doc["auto_apply_refused"] = str(e)+ _hold(doc, prior, proposal, ctx.repo.root)ctx.store.write("untool.json", doc)- return {"proposal": doc["proposal"], "applied_now": added, "restored": []}+ return {"proposal": doc["proposal"], "pending": bool(doc.get("auto_pending")),+ "restored": []}+++def _hold(doc, prior, proposal, root):+ """`auto`: keep the proposal as pending for `apply_pending`, from when it first waited. A+ refusal to write the file (a committed or unparseable one) stands until a write succeeds."""+ pend = prior.get("auto_pending") or {}+ doc["auto_pending"] = {"items": list(proposal), "root": root,+ "since": pend.get("since") or time.time()}+ if prior.get("auto_apply_refused"):+ doc["auto_apply_refused"] = prior["auto_apply_refused"]+++def last_activity(ctx):+ """When a session of this repository on this agent last did anything: a hook call (its+ record's write) or a line in its own session log, whichever is later; 0 when none did."""+ latest = 0.0+ sess_dir = ctx.store.path("sessions")+ try:+ names = [n for n in os.listdir(sess_dir) if n.endswith(".json")]+ except OSError:+ return latest+ for name in names:+ try:+ latest = max(latest, os.path.getmtime(os.path.join(sess_dir, name)))+ except OSError:+ continue+ tp = (ctx.store.read(os.path.join("sessions", name)) or {}).get("transcript")+ try:+ latest = max(latest, os.path.getmtime(tp)) if tp else latest+ except OSError:+ pass+ return latest+++def apply_pending(ctx, now=None):+ """Write the pending `auto` deny list once the repository has been quiet long enough (see+ PENDING_MAX_S). Returns the seconds to wait before looking again, or None when there is+ nothing left to wait for: written, refused, given back or applied by hand meanwhile, or+ `toolprune` is no longer `auto`."""+ now = now or time.time()+ with ctx.store.locked("mechanisms"):+ unt = ctx.store.read("untool.json") or {}+ pend = unt.get("auto_pending")+ if not pend:+ return None+ root = pend.get("root") or ctx.repo.root+ done = set(denylist.applied_for(ctx.store, root, ctx.host.name))+ done |= set(denylist.kept_for(ctx.store, root, ctx.host.name))+ items = [t for t in pend.get("items") or [] if t not in done]+ if items and ctx.config.toolprune == "auto" and not ctx.config.shadow:+ idle = now - last_activity(ctx)+ quiet_s = ctx.config.toolprune_quiet_minutes * 60+ waited = now - float(pend.get("since") or now)+ if idle < quiet_s and waited < PENDING_MAX_S:+ return min(quiet_s - idle, PENDING_MAX_S - waited)+ try:+ unt["auto_applied"] = denylist.apply(root, items, ctx.store, host=ctx.host.name)+ unt["proposal"] = [t for t in unt.get("proposal") or [] if t not in items]+ unt.pop("auto_apply_refused", None)+ except RuntimeError as e: # an unreadable, committed or redirected file+ unt["auto_apply_refused"] = str(e)+ unt.pop("auto_pending", None)+ ctx.store.write("untool.json", unt)+ return None+++def schedule_pending(ctx):+ """Look at the pending deny list now and, if it has to wait, leave a detached+ `te toolprune apply-pending` to write it later (only the look, when TE_FOLD_SYNC=1)."""+ wait = apply_pending(ctx)+ if wait is not None and ctx.env.get("TE_FOLD_SYNC") != "1":+ ctx.spawn(["toolprune", "apply-pending"], "fold.log")+ return wait# Rarely used, but expensive to lose when a session needs it -- the Codex counterpart of@@ -260,6 +337,8 @@ def fold_session(ctx, session_id, transcript_path=None):transcript=transcript, workdir=workdir)record["injection"] = injrecord["untool"] = unt+ if unt and unt.get("pending"):+ schedule_pending(ctx)ctx.host.settle(transcript)usage = ctx.host.session_usage(transcript)eff, priced_by = accounting.effective(usage)diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.pyindex 2073c4f..df7aa32 100644--- a/tokeneconomizer/plugin/hosts.py+++ b/tokeneconomizer/plugin/hosts.py@@ -148,6 +148,10 @@ class Host:# agent does not put hook messages where the person looks.relays_notices = False+ # Whether a resumed conversation still carries the context its first SessionStart added, so+ # the plugin need not add it again (Claude Code 2.1.307 and Codex 0.163.0 replay it).+ keeps_start_context = True+def relay(self, text):"""What the model is asked, so that it passes `text` on to the person, word for word.The notice is the person's to act on: it does not change the model's task."""@@ -341,6 +345,9 @@ class Copilot(Host):name = "copilot"interrupt = "Press Esc twice to interrupt it." # 1.0.101: "esc esc interrupt"prompt_context = True # verified: top-level additionalContext+ # 1.0.102 rebuilds a resumed conversation's first message without it, dropping the facts+ # and missing the prompt cache; the same text given again rebuilds it as it was.+ keeps_start_context = Falsedef transcript(self, p):# Only Stop carries `transcript_path`; the log's location is fixed by the session id.