Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/upstream-state/tokeneconomizer/tokeneconomizer
Original file line number Diff line number Diff line change
@@ -1 +1 @@
81e32e56bb3c4c1b4c9756b429be91e3960116ca
583fff78bf504b59d542f953c31e87d01d02ab42
1 change: 1 addition & 0 deletions plugins/tokeneconomizer/.gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
plugin/scripts/te text eol=lf
plugin/scripts/te-hook text eol=lf
*.sh text eol=lf
*.cmd text eol=crlf
12 changes: 12 additions & 0 deletions plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "tokeneconomizer",
"description": "Experience-driven cost control for Factory Droid: short repository facts learned from earlier sessions are injected at session start, each session is priced from Droid's own usage, and a guard redirects a turn stuck in a failing loop. Tool pruning is off on Droid (its TUI has no persistent tool list to change).",
"version": "0.2.0",
"author": {
"name": "TokenEconomizer authors"
},
"homepage": "https://github.com/microsoft/TokenEconomizer",
"repository": "https://github.com/microsoft/TokenEconomizer",
"license": "Apache-2.0",
"keywords": ["cost", "tokens", "context", "hooks", "micro-skills", "failure-loops", "droid"]
}
120 changes: 108 additions & 12 deletions plugins/tokeneconomizer/plugin/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# TokenEconomizer plugin

How to install and use TokenEconomizer in Claude Code, Codex, the GitHub Copilot CLI, Pi, Cursor
(experimental), Grok Build (experimental), opencode (experimental), Hermes Agent (experimental)
and the Antigravity CLI (experimental). What the plugin does and why is in the [main README](../README.md); its
design and the verified behaviour of each agent are in [`docs/PLUGIN.md`](../docs/PLUGIN.md).
(experimental), Grok Build (experimental), opencode (experimental), Hermes Agent (experimental),
the Antigravity CLI (experimental) and Factory Droid (experimental). What the plugin does and
why is in the [main README](../README.md); its design 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) · [Cursor](#cursor) · [Grok Build](#grok-build) · [opencode](#opencode) ·
[Hermes Agent](#hermes-agent) · [Antigravity CLI](#antigravity-cli)
[Hermes Agent](#hermes-agent) · [Antigravity CLI](#antigravity-cli) · [Factory Droid](#factory-droid)
- [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)
Expand Down Expand Up @@ -190,6 +191,17 @@ copilot plugin list # tokeneconomizer@tokeneconomizer ... (enabled)

Copilot loads the plugin from the clone directly, without copying it.

On Windows, its hooks and slash commands invoke Python directly from PowerShell commands;
Git Bash is not required. They work under `Restricted` without changing execution policy or
using `-ExecutionPolicy Bypass`. Copilot's normal command approval still applies;
application-control policies that block Python still apply too.
From a PowerShell terminal in the clone, use a Python >= 3.10 executable, for example:
`python -X utf8 .\plugin\scripts\te_bootstrap.py cli --host copilot status`.
The hooks run `TE_PYTHON` as named when set. Otherwise they try `python3`, `python`, and `py`,
selecting Python >= 3.10 and preferring
interpreters outside WindowsApps. If only an older Python exists, the bootstrap still handles
the refusal. The slash commands reuse the interpreter selected by the hook.

**2. Check it.** In Copilot's interactive mode, type `/tokeneconomizer:status`. Each slash command
is a model turn, and Copilot asks before running the plugin's script; choose **Yes**. Slash
commands work only in interactive mode; the plugin's notices also appear under `copilot -p`.
Expand All @@ -211,7 +223,19 @@ start says so. `/tokeneconomizer:toolprune restore` turns the server back on, an
`toolprune measure` shows the difference with no model call.

From a terminal, inside the repository: `~/.tokeneconomizer/bin/te --host copilot <command>` (the
launcher appears after the first session). A turn that is still stuck after the loop guard's
launcher appears after the first session). In PowerShell, read the launch paths as data and
invoke Python directly, replacing `status` with the command you want:

```powershell
$root = if ($env:TOKENECONOMIZER_HOME) { $env:TOKENECONOMIZER_HOME } else { Join-Path $HOME '.tokeneconomizer' }
$launcher = Get-Content -LiteralPath (Join-Path $root 'bin\te.json') -Raw -ErrorAction Stop | ConvertFrom-Json
$OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding
& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path status
```

Session-start and prompt hooks create or repair the launchers and `te.json`, so an open session
picks up the native launch paths on its next prompt after updating.
A turn that is still stuck after the loop guard's
redirect shows "● TokenEconomizer: …" in the conversation (and on stdout under `copilot -p`); press
**Esc** twice to interrupt it, or Ctrl+C to end a `copilot -p` run.

Expand Down Expand Up @@ -546,8 +570,7 @@ log a warning for the empty section of a session with no facts.

## Antigravity CLI

Experimental: **micro-skills' LLM-free facts**, written against `agy` 1.5.1 on macOS and Linux
(agy runs hook commands through `cmd /c` on Windows, and the launcher is a POSIX shell script).
Experimental: **micro-skills' LLM-free facts**, tested against `agy` 1.5.1 and 1.5.2 on Windows 11, macOS and Linux.

**1. Install.** Build the self-contained plugin, which copies the package into it, and install the
directory:
Expand All @@ -562,8 +585,10 @@ from `hooks.json` at the plugin root; the `hooks/hooks.json` beside it is Claude
validator says it is never loaded.

**2. Check it.** Run a session, then `~/.tokeneconomizer/bin/te --host antigravity status` in the
repository. agy plugins load no slash commands, so every command runs from a terminal. Micro-skills
is off by default: `te --host antigravity config set microskills=envfacts`.
repository (on Windows, `<plugin>\scripts\te.cmd --host antigravity status` in the repository;
`<plugin>` is the folder above `scripts\te_bootstrap.py` in `%USERPROFILE%\.tokeneconomizer\bin\te.json`, which the first session writes).
agy plugins load no slash commands, so every command runs from a terminal. Micro-skills
is off by default: `te --host antigravity config set microskills=envfacts` (on Windows: `<plugin>\scripts\te.cmd --host antigravity config set microskills=envfacts`).

**How it works, and what it does not do.**

Expand All @@ -584,6 +609,48 @@ is off by default: `te --host antigravity config set microskills=envfacts`.
proposer never runs, and the loop guard, which needs a judge's verdict to act, never redirects
a turn.

## Factory Droid

Experimental. Full notes are in [`docs/DROID.md`](../docs/DROID.md).

**1. Install.** Droid needs a native plugin layout, so build the Droid bundle (it copies the
Python package into `lib/`, since Droid copies the plugin directory into its cache):

```sh
python scripts/build_plugin.py --droid
droid plugin marketplace add "$PWD/dist/tokeneconomizer-droid"
droid plugin install tokeneconomizer@tokeneconomizer-droid --scope user
```

Start a new Droid session: hooks are snapshotted at startup.

**2. Check it.** Run `/tokeneconomizer-status`, or from a terminal in the repository
`~/.tokeneconomizer/bin/te --host droid status`.

**3. Import earlier sessions.** Droid's own logs are read by the same history import as the
other hosts:

```sh
~/.tokeneconomizer/bin/te --host droid history import
```

It runs only into a repository with nothing folded yet and makes no model call. Start sessions
in the project's own folder: a directory that holds several repositories is learned as one.

**What works.** Micro-skills, the loop guard and session cost. Droid writes each session's
`tokenUsage` to `<session id>.settings.json` beside its log, and the plugin prices the session
from it (an unknown model is labelled `fallback`). **What does not:** tool pruning, because the
TUI has no persistent per-tool setting (Factory issue #65). **Model calls** run through
`droid exec` and are off until `config set droid_sidecall=on` (or `TE_DROID_SIDECALL=1` in a
terminal session): that command writes a session log of its own, so enabling it is a deliberate
choice. When on, they run with `--only-tools Read`, so `Read` is the only tool they may use;
Droid has no setting for none at all. With it off, `microskills=envfacts` still learns.

**Verified live on 2026-11-05:** a fact reaching a live Droid model. A new session
(`bb18c4fc`) received the 793-character block as `hookSpecificOutput.additionalContext`, and the
model repeated it verbatim. The hook output is covered by tests; Droid appending it to the
model's context has now been observed.

## What to expect

The plugin works session by session: what it learns from a repository's earlier sessions is
Expand Down Expand Up @@ -642,6 +709,8 @@ repository is not used by Codex there), while settings are shared by every agent
|---|---|
| `status` | what it has learned in this repository, what it did, and what your sessions cost |
| `microskills` | the facts it injects at session start, and those still forming |
| `microskills forget ID …` | stop injecting the facts with these ids (as `microskills` lists them), and never learn them again under that id or from the same evidence; an unknown id changes nothing |
| `microskills unforget ID …` | bring forgotten facts back, with the evidence they had |
| `toolprune` | the deny list: what it left out, what it would leave out next, and the evidence |
| `toolprune apply [ITEM …]` | apply a waiting proposal (with `toolprune=propose`), or the named items; from the next session |
| `toolprune restore [ITEM …]` | give back the plugin's entries (all, or the named ones); they are not removed again |
Expand All @@ -668,10 +737,12 @@ How to run them:
| opencode | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host opencode <command>` |
| Grok Build | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host grok <command>` |
| Hermes Agent | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host hermes <command>` |
| Antigravity CLI | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host antigravity <command>` |
| Antigravity CLI | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host antigravity <command>` (on Windows: `<plugin>\scripts\te.cmd --host antigravity <command>`, in the repository) |
| Factory Droid | `/tokeneconomizer-<command>` | `~/.tokeneconomizer/bin/te --host droid <command>` |

`doctor`, `history` and `repomap` run from a terminal (or as `/te …` on Pi); there is no slash command or
Codex skill for them.
`doctor`, `history`, `repomap` and `microskills forget`/`unforget` run from a terminal (or as `/te …` on
Pi); there is no slash command or Codex skill for them. Quote a fact id that holds spaces or shell
characters: `te microskills forget 'form_repair:run_tests:pytest -q'`.

Inside an agent, each command is one model turn; from a terminal it costs nothing. Codex asks
before a command that changes something (`config set`, `toolprune restore`, ...), since it
Expand Down Expand Up @@ -798,6 +869,9 @@ first session there ends.
| `paid_model` | `""` | model for the plugin's own calls on every agent; 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 |
| `<agent>_paid_model` | `""` | the same for one agent (`claude`, `codex`, `copilot`, `pi`, `opencode`, `cursor`, `grok`, `hermes`), over `paid_model` |
| `claude_paid_effort`, `codex_paid_effort` | `""` | the reasoning effort of those calls: Claude Code `low` to `max`, Codex `none` to `max`; which values a model takes is the CLI's to say; empty: the CLI's default |
| `local_model` | `off` | `fm`: run the side calls `local_roles` names on Apple's on-device Foundation Models CLI (`/usr/bin/fm`, macOS 27 with Apple Intelligence) instead of the agent's CLI; see [On-device side calls](#on-device-side-calls-macos) |
| `local_roles` | `judge` | which side calls `local_model` takes: `judge`, `nudge` (the redirect writer), `proposer`, separated by commas |
| `local_judge_confidence` | `0.9` | how sure a stuck verdict from the on-device judge must be to count; below it the turn is spared |
| `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 |
| `shadow` | `false` | decide and log everything, act on nothing |
Expand Down Expand Up @@ -905,6 +979,28 @@ at its backstop), the next session start says so once, and `config set microskil
`loopguard=on`) tries again. `toolprune measure` on Claude Code makes its two calls the same way,
and only when you run it.

## On-device side calls (macOS)

With `local_model=fm`, the side calls `local_roles` names (by default the loop guard's judge) run
on the Foundation Models CLI that macOS 27 ships at `/usr/bin/fm` when Apple Intelligence is on:
a model on the Mac itself, with no login, key or network. The plugin sends it the same prompt it
would send the agent's CLI, on stdin, with greedy decoding; the judge's call also passes a JSON
schema for its verdict (`fm respond --schema`), which constrains what the model can return. Its
window is 4,096 tokens, enough for the judge's and the redirect writer's prompts.

The ledger charges an on-device call 0 tokens. Without `/usr/bin/fm`, or with its model not ready,
the call goes to the agent's CLI as before; a call `fm` cannot answer (a prompt over its window, no
reply) leaves a line in `errors.log` and goes there too, so turning this on never leaves the guard
without its judge. While that CLI is paused (signed out), the on-device judge still answers. On any
system but macOS the setting does nothing. A stuck verdict from the on-device judge counts only at
`local_judge_confidence` (0.9) or above: its confidences come in a few coarse steps, most of them
above the guard's own `judge_confidence` (0.7).

```text
~/.tokeneconomizer/bin/te config set local_model=fm
~/.tokeneconomizer/bin/te config set local_roles=judge,nudge # also the redirect writer
```

## Troubleshooting

| Symptom | Fix |
Expand Down
6 changes: 3 additions & 3 deletions plugins/tokeneconomizer/plugin/hooks.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"tokeneconomizer": {
"SessionStart": [
{ "type": "command", "command": "./scripts/te-hook --host antigravity --event SessionStart", "timeout": 15 }
{ "type": "command", "command": "./scripts/te-hook --host antigravity --event SessionStart || scripts\\te-hook.cmd --host antigravity --event SessionStart", "timeout": 15 }
],
"PreInvocation": [
{ "type": "command", "command": "./scripts/te-hook --host antigravity --event PreInvocation", "timeout": 10 }
{ "type": "command", "command": "./scripts/te-hook --host antigravity --event PreInvocation || scripts\\te-hook.cmd --host antigravity --event PreInvocation", "timeout": 10 }
],
"Stop": [
{ "type": "command", "command": "./scripts/te-hook --host antigravity --event Stop", "timeout": 10 }
{ "type": "command", "command": "./scripts/te-hook --host antigravity --event Stop || scripts\\te-hook.cmd --host antigravity --event Stop", "timeout": 10 }
]
}
}
Loading