diff --git a/.github/upstream-state/tokeneconomizer/tokeneconomizer b/.github/upstream-state/tokeneconomizer/tokeneconomizer index 12b3719..2d522d5 100644 --- a/.github/upstream-state/tokeneconomizer/tokeneconomizer +++ b/.github/upstream-state/tokeneconomizer/tokeneconomizer @@ -1 +1 @@ -81e32e56bb3c4c1b4c9756b429be91e3960116ca +583fff78bf504b59d542f953c31e87d01d02ab42 diff --git a/plugins/tokeneconomizer/.gitattributes b/plugins/tokeneconomizer/.gitattributes index e916ab7..4ee4029 100644 --- a/plugins/tokeneconomizer/.gitattributes +++ b/plugins/tokeneconomizer/.gitattributes @@ -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 diff --git a/plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json b/plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json new file mode 100644 index 0000000..644144f --- /dev/null +++ b/plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json @@ -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"] +} diff --git a/plugins/tokeneconomizer/plugin/README.md b/plugins/tokeneconomizer/plugin/README.md index 1483d7f..0395d66 100644 --- a/plugins/tokeneconomizer/plugin/README.md +++ b/plugins/tokeneconomizer/plugin/README.md @@ -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) @@ -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`. @@ -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 ` (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. @@ -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: @@ -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, `\scripts\te.cmd --host antigravity status` in the repository; +`` 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: `\scripts\te.cmd --host antigravity config set microskills=envfacts`). **How it works, and what it does not do.** @@ -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 `.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 @@ -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 | @@ -668,10 +737,12 @@ How to run them: | opencode | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host opencode ` | | Grok Build | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host grok ` | | Hermes Agent | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host hermes ` | -| Antigravity CLI | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host antigravity ` | +| Antigravity CLI | none (run from a terminal) | `~/.tokeneconomizer/bin/te --host antigravity ` (on Windows: `\scripts\te.cmd --host antigravity `, in the repository) | +| Factory Droid | `/tokeneconomizer-` | `~/.tokeneconomizer/bin/te --host droid ` | -`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 @@ -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 | | `_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 | @@ -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 | diff --git a/plugins/tokeneconomizer/plugin/hooks.json b/plugins/tokeneconomizer/plugin/hooks.json index 9307311..cdca9c4 100644 --- a/plugins/tokeneconomizer/plugin/hooks.json +++ b/plugins/tokeneconomizer/plugin/hooks.json @@ -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 } ] } } diff --git a/plugins/tokeneconomizer/plugin/hooks/copilot-hooks.json b/plugins/tokeneconomizer/plugin/hooks/copilot-hooks.json index 15c8fd8..42bd873 100644 --- a/plugins/tokeneconomizer/plugin/hooks/copilot-hooks.json +++ b/plugins/tokeneconomizer/plugin/hooks/copilot-hooks.json @@ -7,6 +7,7 @@ { "type": "command", "command": "\"${PLUGIN_ROOT}/scripts/te-hook\" --host copilot", + "windows": "& { $env:PYTHONUTF8 = '1'; $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; $payload = if ($MyInvocation.ExpectingInput) { $input -join \"`n\" } else { [Console]::In.ReadToEnd() }; $python = $null\nif ($env:TE_PYTHON) {\n $python = Get-Command $env:TE_PYTHON -CommandType Application -All -ErrorAction SilentlyContinue |\n Select-Object -First 1\n}\nif (-not $python) {\n $candidates = @(foreach ($name in @('python3', 'python', 'py')) {\n Get-Command $name -CommandType Application -All -ErrorAction SilentlyContinue\n })\n $ordered = @($candidates | Where-Object { $_.Source -notlike '*\\WindowsApps\\*' }) +\n @($candidates | Where-Object { $_.Source -like '*\\WindowsApps\\*' })\n $old = $null\n foreach ($candidate in $ordered) {\n $probeArgs = @()\n if ($candidate.Name -eq 'py.exe' -or $candidate.Name -eq 'py') { $probeArgs += '-3' }\n if ($candidate.Source -like '*\\WindowsApps\\*') {\n & $candidate.Source @probeArgs -E -S -c pass *> $null\n if ($LASTEXITCODE -ne 0) { continue }\n }\n & $candidate.Source @probeArgs -E -S -c 'import sys; sys.exit(sys.version_info < (3, 10))' *> $null\n if ($LASTEXITCODE -eq 0) { $python = $candidate; break }\n if ($LASTEXITCODE -eq 1 -and -not $old) { $old = $candidate }\n }\n if (-not $python) { $python = $old }\n}\nif (-not $python) { $root = if ($env:TOKENECONOMIZER_HOME) { $env:TOKENECONOMIZER_HOME } else { Join-Path $HOME '.tokeneconomizer' }; try { [IO.Directory]::CreateDirectory($root) | Out-Null; [IO.File]::AppendAllText((Join-Path $root 'errors.log'), \"te: no Python on PATH (set TE_PYTHON)`n\") } catch [IO.IOException] { [Console]::Error.WriteLine($_.Exception.Message) } catch [UnauthorizedAccessException] { [Console]::Error.WriteLine($_.Exception.Message) }; '{}'; exit 0 }; $pythonArgs = @(); if ($python.Name -eq 'py.exe' -or $python.Name -eq 'py') { $pythonArgs += '-3' }; $pythonArgs += @((Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\\te_bootstrap.py'), 'hook', '--host', 'copilot'); $payload | & $python.Source @pythonArgs; exit $LASTEXITCODE }", "timeout": 15 } ] @@ -18,6 +19,7 @@ { "type": "command", "command": "\"${PLUGIN_ROOT}/scripts/te-hook\" --host copilot", + "windows": "& { $env:PYTHONUTF8 = '1'; $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; $payload = if ($MyInvocation.ExpectingInput) { $input -join \"`n\" } else { [Console]::In.ReadToEnd() }; $python = $null\nif ($env:TE_PYTHON) {\n $python = Get-Command $env:TE_PYTHON -CommandType Application -All -ErrorAction SilentlyContinue |\n Select-Object -First 1\n}\nif (-not $python) {\n $candidates = @(foreach ($name in @('python3', 'python', 'py')) {\n Get-Command $name -CommandType Application -All -ErrorAction SilentlyContinue\n })\n $ordered = @($candidates | Where-Object { $_.Source -notlike '*\\WindowsApps\\*' }) +\n @($candidates | Where-Object { $_.Source -like '*\\WindowsApps\\*' })\n $old = $null\n foreach ($candidate in $ordered) {\n $probeArgs = @()\n if ($candidate.Name -eq 'py.exe' -or $candidate.Name -eq 'py') { $probeArgs += '-3' }\n if ($candidate.Source -like '*\\WindowsApps\\*') {\n & $candidate.Source @probeArgs -E -S -c pass *> $null\n if ($LASTEXITCODE -ne 0) { continue }\n }\n & $candidate.Source @probeArgs -E -S -c 'import sys; sys.exit(sys.version_info < (3, 10))' *> $null\n if ($LASTEXITCODE -eq 0) { $python = $candidate; break }\n if ($LASTEXITCODE -eq 1 -and -not $old) { $old = $candidate }\n }\n if (-not $python) { $python = $old }\n}\nif (-not $python) { $root = if ($env:TOKENECONOMIZER_HOME) { $env:TOKENECONOMIZER_HOME } else { Join-Path $HOME '.tokeneconomizer' }; try { [IO.Directory]::CreateDirectory($root) | Out-Null; [IO.File]::AppendAllText((Join-Path $root 'errors.log'), \"te: no Python on PATH (set TE_PYTHON)`n\") } catch [IO.IOException] { [Console]::Error.WriteLine($_.Exception.Message) } catch [UnauthorizedAccessException] { [Console]::Error.WriteLine($_.Exception.Message) }; '{}'; exit 0 }; $pythonArgs = @(); if ($python.Name -eq 'py.exe' -or $python.Name -eq 'py') { $pythonArgs += '-3' }; $pythonArgs += @((Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\\te_bootstrap.py'), 'hook', '--host', 'copilot'); $payload | & $python.Source @pythonArgs; exit $LASTEXITCODE }", "timeout": 20 } ] @@ -29,6 +31,7 @@ { "type": "command", "command": "\"${PLUGIN_ROOT}/scripts/te-hook\" --host copilot", + "windows": "& { $env:PYTHONUTF8 = '1'; $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; $payload = if ($MyInvocation.ExpectingInput) { $input -join \"`n\" } else { [Console]::In.ReadToEnd() }; $python = $null\nif ($env:TE_PYTHON) {\n $python = Get-Command $env:TE_PYTHON -CommandType Application -All -ErrorAction SilentlyContinue |\n Select-Object -First 1\n}\nif (-not $python) {\n $candidates = @(foreach ($name in @('python3', 'python', 'py')) {\n Get-Command $name -CommandType Application -All -ErrorAction SilentlyContinue\n })\n $ordered = @($candidates | Where-Object { $_.Source -notlike '*\\WindowsApps\\*' }) +\n @($candidates | Where-Object { $_.Source -like '*\\WindowsApps\\*' })\n $old = $null\n foreach ($candidate in $ordered) {\n $probeArgs = @()\n if ($candidate.Name -eq 'py.exe' -or $candidate.Name -eq 'py') { $probeArgs += '-3' }\n if ($candidate.Source -like '*\\WindowsApps\\*') {\n & $candidate.Source @probeArgs -E -S -c pass *> $null\n if ($LASTEXITCODE -ne 0) { continue }\n }\n & $candidate.Source @probeArgs -E -S -c 'import sys; sys.exit(sys.version_info < (3, 10))' *> $null\n if ($LASTEXITCODE -eq 0) { $python = $candidate; break }\n if ($LASTEXITCODE -eq 1 -and -not $old) { $old = $candidate }\n }\n if (-not $python) { $python = $old }\n}\nif (-not $python) { $root = if ($env:TOKENECONOMIZER_HOME) { $env:TOKENECONOMIZER_HOME } else { Join-Path $HOME '.tokeneconomizer' }; try { [IO.Directory]::CreateDirectory($root) | Out-Null; [IO.File]::AppendAllText((Join-Path $root 'errors.log'), \"te: no Python on PATH (set TE_PYTHON)`n\") } catch [IO.IOException] { [Console]::Error.WriteLine($_.Exception.Message) } catch [UnauthorizedAccessException] { [Console]::Error.WriteLine($_.Exception.Message) }; '{}'; exit 0 }; $pythonArgs = @(); if ($python.Name -eq 'py.exe' -or $python.Name -eq 'py') { $pythonArgs += '-3' }; $pythonArgs += @((Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\\te_bootstrap.py'), 'hook', '--host', 'copilot'); $payload | & $python.Source @pythonArgs; exit $LASTEXITCODE }", "timeout": 60 } ] @@ -40,6 +43,7 @@ { "type": "command", "command": "\"${PLUGIN_ROOT}/scripts/te-hook\" --host copilot", + "windows": "& { $env:PYTHONUTF8 = '1'; $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; $payload = if ($MyInvocation.ExpectingInput) { $input -join \"`n\" } else { [Console]::In.ReadToEnd() }; $python = $null\nif ($env:TE_PYTHON) {\n $python = Get-Command $env:TE_PYTHON -CommandType Application -All -ErrorAction SilentlyContinue |\n Select-Object -First 1\n}\nif (-not $python) {\n $candidates = @(foreach ($name in @('python3', 'python', 'py')) {\n Get-Command $name -CommandType Application -All -ErrorAction SilentlyContinue\n })\n $ordered = @($candidates | Where-Object { $_.Source -notlike '*\\WindowsApps\\*' }) +\n @($candidates | Where-Object { $_.Source -like '*\\WindowsApps\\*' })\n $old = $null\n foreach ($candidate in $ordered) {\n $probeArgs = @()\n if ($candidate.Name -eq 'py.exe' -or $candidate.Name -eq 'py') { $probeArgs += '-3' }\n if ($candidate.Source -like '*\\WindowsApps\\*') {\n & $candidate.Source @probeArgs -E -S -c pass *> $null\n if ($LASTEXITCODE -ne 0) { continue }\n }\n & $candidate.Source @probeArgs -E -S -c 'import sys; sys.exit(sys.version_info < (3, 10))' *> $null\n if ($LASTEXITCODE -eq 0) { $python = $candidate; break }\n if ($LASTEXITCODE -eq 1 -and -not $old) { $old = $candidate }\n }\n if (-not $python) { $python = $old }\n}\nif (-not $python) { $root = if ($env:TOKENECONOMIZER_HOME) { $env:TOKENECONOMIZER_HOME } else { Join-Path $HOME '.tokeneconomizer' }; try { [IO.Directory]::CreateDirectory($root) | Out-Null; [IO.File]::AppendAllText((Join-Path $root 'errors.log'), \"te: no Python on PATH (set TE_PYTHON)`n\") } catch [IO.IOException] { [Console]::Error.WriteLine($_.Exception.Message) } catch [UnauthorizedAccessException] { [Console]::Error.WriteLine($_.Exception.Message) }; '{}'; exit 0 }; $pythonArgs = @(); if ($python.Name -eq 'py.exe' -or $python.Name -eq 'py') { $pythonArgs += '-3' }; $pythonArgs += @((Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\\te_bootstrap.py'), 'hook', '--host', 'copilot'); $payload | & $python.Source @pythonArgs; exit $LASTEXITCODE }", "timeout": 60 } ] @@ -51,6 +55,7 @@ { "type": "command", "command": "\"${PLUGIN_ROOT}/scripts/te-hook\" --host copilot", + "windows": "& { $env:PYTHONUTF8 = '1'; $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; $payload = if ($MyInvocation.ExpectingInput) { $input -join \"`n\" } else { [Console]::In.ReadToEnd() }; $python = $null\nif ($env:TE_PYTHON) {\n $python = Get-Command $env:TE_PYTHON -CommandType Application -All -ErrorAction SilentlyContinue |\n Select-Object -First 1\n}\nif (-not $python) {\n $candidates = @(foreach ($name in @('python3', 'python', 'py')) {\n Get-Command $name -CommandType Application -All -ErrorAction SilentlyContinue\n })\n $ordered = @($candidates | Where-Object { $_.Source -notlike '*\\WindowsApps\\*' }) +\n @($candidates | Where-Object { $_.Source -like '*\\WindowsApps\\*' })\n $old = $null\n foreach ($candidate in $ordered) {\n $probeArgs = @()\n if ($candidate.Name -eq 'py.exe' -or $candidate.Name -eq 'py') { $probeArgs += '-3' }\n if ($candidate.Source -like '*\\WindowsApps\\*') {\n & $candidate.Source @probeArgs -E -S -c pass *> $null\n if ($LASTEXITCODE -ne 0) { continue }\n }\n & $candidate.Source @probeArgs -E -S -c 'import sys; sys.exit(sys.version_info < (3, 10))' *> $null\n if ($LASTEXITCODE -eq 0) { $python = $candidate; break }\n if ($LASTEXITCODE -eq 1 -and -not $old) { $old = $candidate }\n }\n if (-not $python) { $python = $old }\n}\nif (-not $python) { $root = if ($env:TOKENECONOMIZER_HOME) { $env:TOKENECONOMIZER_HOME } else { Join-Path $HOME '.tokeneconomizer' }; try { [IO.Directory]::CreateDirectory($root) | Out-Null; [IO.File]::AppendAllText((Join-Path $root 'errors.log'), \"te: no Python on PATH (set TE_PYTHON)`n\") } catch [IO.IOException] { [Console]::Error.WriteLine($_.Exception.Message) } catch [UnauthorizedAccessException] { [Console]::Error.WriteLine($_.Exception.Message) }; '{}'; exit 0 }; $pythonArgs = @(); if ($python.Name -eq 'py.exe' -or $python.Name -eq 'py') { $pythonArgs += '-3' }; $pythonArgs += @((Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\\te_bootstrap.py'), 'hook', '--host', 'copilot'); $payload | & $python.Source @pythonArgs; exit $LASTEXITCODE }", "timeout": 10 } ] @@ -62,6 +67,7 @@ { "type": "command", "command": "\"${PLUGIN_ROOT}/scripts/te-hook\" --host copilot", + "windows": "& { $env:PYTHONUTF8 = '1'; $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; $payload = if ($MyInvocation.ExpectingInput) { $input -join \"`n\" } else { [Console]::In.ReadToEnd() }; $python = $null\nif ($env:TE_PYTHON) {\n $python = Get-Command $env:TE_PYTHON -CommandType Application -All -ErrorAction SilentlyContinue |\n Select-Object -First 1\n}\nif (-not $python) {\n $candidates = @(foreach ($name in @('python3', 'python', 'py')) {\n Get-Command $name -CommandType Application -All -ErrorAction SilentlyContinue\n })\n $ordered = @($candidates | Where-Object { $_.Source -notlike '*\\WindowsApps\\*' }) +\n @($candidates | Where-Object { $_.Source -like '*\\WindowsApps\\*' })\n $old = $null\n foreach ($candidate in $ordered) {\n $probeArgs = @()\n if ($candidate.Name -eq 'py.exe' -or $candidate.Name -eq 'py') { $probeArgs += '-3' }\n if ($candidate.Source -like '*\\WindowsApps\\*') {\n & $candidate.Source @probeArgs -E -S -c pass *> $null\n if ($LASTEXITCODE -ne 0) { continue }\n }\n & $candidate.Source @probeArgs -E -S -c 'import sys; sys.exit(sys.version_info < (3, 10))' *> $null\n if ($LASTEXITCODE -eq 0) { $python = $candidate; break }\n if ($LASTEXITCODE -eq 1 -and -not $old) { $old = $candidate }\n }\n if (-not $python) { $python = $old }\n}\nif (-not $python) { $root = if ($env:TOKENECONOMIZER_HOME) { $env:TOKENECONOMIZER_HOME } else { Join-Path $HOME '.tokeneconomizer' }; try { [IO.Directory]::CreateDirectory($root) | Out-Null; [IO.File]::AppendAllText((Join-Path $root 'errors.log'), \"te: no Python on PATH (set TE_PYTHON)`n\") } catch [IO.IOException] { [Console]::Error.WriteLine($_.Exception.Message) } catch [UnauthorizedAccessException] { [Console]::Error.WriteLine($_.Exception.Message) }; '{}'; exit 0 }; $pythonArgs = @(); if ($python.Name -eq 'py.exe' -or $python.Name -eq 'py') { $pythonArgs += '-3' }; $pythonArgs += @((Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\\te_bootstrap.py'), 'hook', '--host', 'copilot'); $payload | & $python.Source @pythonArgs; exit $LASTEXITCODE }", "timeout": 10 } ] diff --git a/plugins/tokeneconomizer/plugin/hooks/droid-hooks.json b/plugins/tokeneconomizer/plugin/hooks/droid-hooks.json new file mode 100644 index 0000000..2a54aab --- /dev/null +++ b/plugins/tokeneconomizer/plugin/hooks/droid-hooks.json @@ -0,0 +1,57 @@ +{ + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${DROID_PLUGIN_ROOT}/scripts/te-hook\" --host droid", + "timeout": 15 + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${DROID_PLUGIN_ROOT}/scripts/te-hook\" --host droid", + "timeout": 20 + } + ] + } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${DROID_PLUGIN_ROOT}/scripts/te-hook\" --host droid", + "timeout": 60 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${DROID_PLUGIN_ROOT}/scripts/te-hook\" --host droid", + "timeout": 10 + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "\"${DROID_PLUGIN_ROOT}/scripts/te-hook\" --host droid", + "timeout": 10 + } + ] + } + ] +} diff --git a/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts b/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts index 8914137..6ca2deb 100644 --- a/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts +++ b/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts @@ -225,7 +225,8 @@ export default function tokeneconomizer(pi: ExtensionAPI) { pi.registerCommand("te", { description: "TokenEconomizer: status | microskills | config | repos (what it learned here, what it did)", handler: async (args, ctx) => { - const argv = (args || "status").trim().split(/\s+/).filter(Boolean); + // `te` splits the line itself (shlex), so a quoted fact id with spaces stays one argument. + const argv = ["--argline", (args || "").trim() || "status"]; // The session id lets `te status` say when this session is recorded under the repository // it started in rather than the one `ctx.cwd` is in now. const out = await run("te", ["--host", "pi", "--cwd", ctx.cwd, ...argv], "", ctx.mode, { diff --git a/plugins/tokeneconomizer/plugin/scripts/te b/plugins/tokeneconomizer/plugin/scripts/te index 53c416a..ecc0f17 100755 --- a/plugins/tokeneconomizer/plugin/scripts/te +++ b/plugins/tokeneconomizer/plugin/scripts/te @@ -32,10 +32,27 @@ if [ "${OS:-}" = Windows_NT ]; then exec "$py" "$dir/te_bootstrap.py" cli "$@" done else - for py in "${TE_PYTHON:-}" python3 python; do - [ -n "$py" ] && command -v "$py" >/dev/null 2>&1 || continue - exec "$py" "$dir/te_bootstrap.py" cli "$@" + # TE_PYTHON is the person's own choice: it runs as named. Otherwise the first python3 on PATH + # can be older than the bootstrap's minimum (macOS /usr/bin/python3 is 3.9, and an agent's + # hook PATH is often not a login shell's), which would make the plugin a silent no-op with a + # newer Python installed: take the first one new enough. With none, run the first one too old + # (the probe exits 1), so the bootstrap still fails open / says what it needs; a name that + # runs no Python (a pyenv shim with no version set exits 127) is passed over. The probe + # skips `site` (-E -S). + if [ -n "${TE_PYTHON:-}" ] && command -v "$TE_PYTHON" >/dev/null 2>&1; then + exec "$TE_PYTHON" "$dir/te_bootstrap.py" cli "$@" + fi + probe='import sys; sys.exit(sys.version_info < (3, 10))' + old= + for py in python3 python3.15 python3.14 python3.13 python3.12 python3.11 python3.10 python; do + command -v "$py" >/dev/null 2>&1 || continue + "$py" -E -S -c "$probe" /dev/null 2>&1 + case $? in + 0) exec "$py" "$dir/te_bootstrap.py" cli "$@" ;; + 1) [ -n "$old" ] || old=$py ;; + esac done + [ -n "$old" ] && exec "$old" "$dir/te_bootstrap.py" cli "$@" fi echo "te: no python3 on PATH (set TE_PYTHON)" >&2 exit 1 diff --git a/plugins/tokeneconomizer/plugin/scripts/te-hook b/plugins/tokeneconomizer/plugin/scripts/te-hook index da387ea..94da312 100755 --- a/plugins/tokeneconomizer/plugin/scripts/te-hook +++ b/plugins/tokeneconomizer/plugin/scripts/te-hook @@ -1,5 +1,6 @@ #!/bin/sh -# TokenEconomizer hook launcher: run the hook dispatcher under the first Python 3 on PATH. +# TokenEconomizer hook launcher: run the hook dispatcher under TE_PYTHON, else the first Python +# 3.10+ on PATH. # Fails open -- with no usable Python the hook prints an empty object, which changes nothing. # On Windows (Git Bash), $0 can arrive with backslashes. The Microsoft Store alias under WindowsApps # runs nothing, and every probe of it starts AppXSvc (python/pymanager#396), so a Python outside @@ -35,10 +36,27 @@ if [ "${OS:-}" = Windows_NT ]; then exec "$py" "$dir/te_bootstrap.py" hook "$@" done else - for py in "${TE_PYTHON:-}" python3 python; do - [ -n "$py" ] && command -v "$py" >/dev/null 2>&1 || continue - exec "$py" "$dir/te_bootstrap.py" hook "$@" + # TE_PYTHON is the person's own choice: it runs as named. Otherwise the first python3 on PATH + # can be older than the bootstrap's minimum (macOS /usr/bin/python3 is 3.9, and an agent's + # hook PATH is often not a login shell's), which would make the plugin a silent no-op with a + # newer Python installed: take the first one new enough. With none, run the first one too old + # (the probe exits 1), so the bootstrap still fails open / says what it needs; a name that + # runs no Python (a pyenv shim with no version set exits 127) is passed over. The probe + # skips `site` (-E -S). + if [ -n "${TE_PYTHON:-}" ] && command -v "$TE_PYTHON" >/dev/null 2>&1; then + exec "$TE_PYTHON" "$dir/te_bootstrap.py" hook "$@" + fi + probe='import sys; sys.exit(sys.version_info < (3, 10))' + old= + for py in python3 python3.15 python3.14 python3.13 python3.12 python3.11 python3.10 python; do + command -v "$py" >/dev/null 2>&1 || continue + "$py" -E -S -c "$probe" /dev/null 2>&1 + case $? in + 0) exec "$py" "$dir/te_bootstrap.py" hook "$@" ;; + 1) [ -n "$old" ] || old=$py ;; + esac done + [ -n "$old" ] && exec "$old" "$dir/te_bootstrap.py" hook "$@" fi # Drain stdin with a builtin (no `cat` when PATH is empty), then answer "no change". while IFS= read -r _line; do :; done diff --git a/plugins/tokeneconomizer/plugin/scripts/te-hook.cmd b/plugins/tokeneconomizer/plugin/scripts/te-hook.cmd new file mode 100644 index 0000000..2a95332 --- /dev/null +++ b/plugins/tokeneconomizer/plugin/scripts/te-hook.cmd @@ -0,0 +1,82 @@ +@echo off +setlocal EnableDelayedExpansion +set "DIR=%~dp0" +set "PYTHONUTF8=1" + +:: 1. TE_PYTHON is the person's own choice: it runs as named when it is there, as a file or as +:: a command on PATH. One that is not there is passed over for the probes below, as the sh +:: launchers do, so a stale setting cannot keep the hook from answering. The name is read with +:: delayed expansion and run in quotes: a path with spaces or parentheses +:: ("C:\Program Files (x86)\...") stays one word and cannot end an `if` block early. +if not defined TE_PYTHON goto :probe +set "TE_PY=%TE_PYTHON:"=%" +if exist "!TE_PY!" ( + set "RUN_PY="!TE_PY!"" + goto :run_hook +) +where /q "!TE_PY!" >nul 2>&1 +if !ERRORLEVEL! equ 0 ( + set "RUN_PY="!TE_PY!"" + goto :run_hook +) + +:probe + +:: Probe script: exits 0 if >= 3.10, exits 1 if older +set "PROBE=import sys; sys.exit(sys.version_info < (3, 10))" +set "OLD_PY=" + +:: 2. Probe py.exe (-3 launcher) +where py.exe >nul 2>&1 +if !ERRORLEVEL! equ 0 ( + py -3 -E -S -c "%PROBE%" >nul 2>&1 + if !ERRORLEVEL! equ 0 ( + set "RUN_PY=py -3" + goto :run_hook + ) else if !ERRORLEVEL! equ 1 ( + if not defined OLD_PY set "OLD_PY=py -3" + ) +) + +:: 3. Probe python.exe on PATH, skipping WindowsApps store alias +for /f "tokens=*" %%i in ('where python.exe 2^>nul') do ( + echo %%~fi | findstr /i /c:"WindowsApps" >nul + if errorlevel 1 ( + "%%~fi" -E -S -c "%PROBE%" >nul 2>&1 + if !ERRORLEVEL! equ 0 ( + set "RUN_PY="%%~fi"" + goto :run_hook + ) else if !ERRORLEVEL! equ 1 ( + if not defined OLD_PY set "OLD_PY="%%~fi"" + ) + ) +) + +:: 4. Probe python3.exe on PATH, skipping WindowsApps store alias +for /f "tokens=*" %%i in ('where python3.exe 2^>nul') do ( + echo %%~fi | findstr /i /c:"WindowsApps" >nul + if errorlevel 1 ( + "%%~fi" -E -S -c "%PROBE%" >nul 2>&1 + if !ERRORLEVEL! equ 0 ( + set "RUN_PY="%%~fi"" + goto :run_hook + ) else if !ERRORLEVEL! equ 1 ( + if not defined OLD_PY set "OLD_PY="%%~fi"" + ) + ) +) + +:: 5. If only older Python was found, hand off to it so bootstrap fails open +if defined OLD_PY ( + set "RUN_PY=%OLD_PY%" + goto :run_hook +) + +:: 6. Fail open: drain stdin and output empty JSON +for /f "tokens=*" %%a in ('more 2^>nul') do rem +echo {} +exit /b 0 + +:run_hook +%RUN_PY% "%DIR%te_bootstrap.py" hook %* +exit /b !ERRORLEVEL! diff --git a/plugins/tokeneconomizer/plugin/scripts/te.cmd b/plugins/tokeneconomizer/plugin/scripts/te.cmd new file mode 100644 index 0000000..eb4a83a --- /dev/null +++ b/plugins/tokeneconomizer/plugin/scripts/te.cmd @@ -0,0 +1,80 @@ +@echo off +setlocal EnableDelayedExpansion +set "DIR=%~dp0" +set "PYTHONUTF8=1" + +:: 1. TE_PYTHON is the person's own choice: it runs as named when it is there, as a file or as +:: a command on PATH. One that is not there is passed over for the probes below, as the sh +:: launchers do, so a stale setting cannot keep the hook from answering. The name is read with +:: delayed expansion and run in quotes: a path with spaces or parentheses +:: ("C:\Program Files (x86)\...") stays one word and cannot end an `if` block early. +if not defined TE_PYTHON goto :probe +set "TE_PY=%TE_PYTHON:"=%" +if exist "!TE_PY!" ( + set "RUN_PY="!TE_PY!"" + goto :run_cli +) +where /q "!TE_PY!" >nul 2>&1 +if !ERRORLEVEL! equ 0 ( + set "RUN_PY="!TE_PY!"" + goto :run_cli +) + +:probe + +:: Probe script: exits 0 if >= 3.10, exits 1 if older +set "PROBE=import sys; sys.exit(sys.version_info < (3, 10))" +set "OLD_PY=" + +:: 2. Probe py.exe (-3 launcher) +where py.exe >nul 2>&1 +if !ERRORLEVEL! equ 0 ( + py -3 -E -S -c "%PROBE%" >nul 2>&1 + if !ERRORLEVEL! equ 0 ( + set "RUN_PY=py -3" + goto :run_cli + ) else if !ERRORLEVEL! equ 1 ( + if not defined OLD_PY set "OLD_PY=py -3" + ) +) + +:: 3. Probe python.exe on PATH, skipping WindowsApps store alias +for /f "tokens=*" %%i in ('where python.exe 2^>nul') do ( + echo %%~fi | findstr /i /c:"WindowsApps" >nul + if errorlevel 1 ( + "%%~fi" -E -S -c "%PROBE%" >nul 2>&1 + if !ERRORLEVEL! equ 0 ( + set "RUN_PY="%%~fi"" + goto :run_cli + ) else if !ERRORLEVEL! equ 1 ( + if not defined OLD_PY set "OLD_PY="%%~fi"" + ) + ) +) + +:: 4. Probe python3.exe on PATH, skipping WindowsApps store alias +for /f "tokens=*" %%i in ('where python3.exe 2^>nul') do ( + echo %%~fi | findstr /i /c:"WindowsApps" >nul + if errorlevel 1 ( + "%%~fi" -E -S -c "%PROBE%" >nul 2>&1 + if !ERRORLEVEL! equ 0 ( + set "RUN_PY="%%~fi"" + goto :run_cli + ) else if !ERRORLEVEL! equ 1 ( + if not defined OLD_PY set "OLD_PY="%%~fi"" + ) + ) +) + +:: 5. If only older Python was found, hand off to it so bootstrap reports requirements +if defined OLD_PY ( + set "RUN_PY=%OLD_PY%" + goto :run_cli +) + +echo te: no python3 on PATH (set TE_PYTHON) >&2 +exit /b 1 + +:run_cli +%RUN_PY% "%DIR%te_bootstrap.py" cli %* +exit /b !ERRORLEVEL! diff --git a/plugins/tokeneconomizer/plugin/slash-commands/config.md b/plugins/tokeneconomizer/plugin/slash-commands/config.md index 913ede6..f7e73dc 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/config.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/config.md @@ -3,7 +3,18 @@ description: Show or change TokenEconomizer's settings - turn each mechanism on argument-hint: "[show | set KEY=VALUE ... [--global] | unset KEY ... [--global]]" --- The arguments I typed after the command are: "$ARGUMENTS" (it shows every setting when there are none). -Run this exact command with the Bash tool, then show me its output verbatim in a code block: +Run the command for this shell, then show me its output verbatim in a code block. + +In Copilot CLI on Windows, use the PowerShell tool: + +```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 config $ARGUMENTS +``` + +Otherwise, run this command with the Bash tool: ``` te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" config $ARGUMENTS diff --git a/plugins/tokeneconomizer/plugin/slash-commands/facts.md b/plugins/tokeneconomizer/plugin/slash-commands/facts.md index 9bfc20e..86efecc 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/facts.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/facts.md @@ -1,7 +1,18 @@ --- description: Earlier name of /tokeneconomizer:microskills - show the repository facts TokenEconomizer injects --- -Run this exact command with the Bash tool, then show me its output verbatim in a code block, with no commentary: +Run the command for this shell, then show me its output verbatim in a code block, with no commentary. + +In Copilot CLI on Windows, use the PowerShell tool: + +```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 microskills +``` + +Otherwise, run this command with the Bash tool: ``` te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" microskills diff --git a/plugins/tokeneconomizer/plugin/slash-commands/microskills.md b/plugins/tokeneconomizer/plugin/slash-commands/microskills.md index 4f65110..3aa504c 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/microskills.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/microskills.md @@ -1,7 +1,18 @@ --- description: Show the repository facts (micro-skills) TokenEconomizer learned and injects at session start --- -Run this exact command with the Bash tool, then show me its output verbatim in a code block, with no commentary: +Run the command for this shell, then show me its output verbatim in a code block, with no commentary. + +In Copilot CLI on Windows, use the PowerShell tool: + +```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 microskills +``` + +Otherwise, run this command with the Bash tool: ``` te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" microskills diff --git a/plugins/tokeneconomizer/plugin/slash-commands/repos.md b/plugins/tokeneconomizer/plugin/slash-commands/repos.md index e0a4778..e780f0f 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/repos.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/repos.md @@ -3,7 +3,18 @@ description: List every repository TokenEconomizer keeps state for, or merge one argument-hint: "[list | migrate | merge KEY [INTO]]" --- The arguments I typed after the command are: "$ARGUMENTS" (it lists the repositories when there are none). -Run this exact command with the Bash tool, then show me its output verbatim in a code block: +Run the command for this shell, then show me its output verbatim in a code block. + +In Copilot CLI on Windows, use the PowerShell tool: + +```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 repos $ARGUMENTS +``` + +Otherwise, run this command with the Bash tool: ``` te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" repos $ARGUMENTS diff --git a/plugins/tokeneconomizer/plugin/slash-commands/status.md b/plugins/tokeneconomizer/plugin/slash-commands/status.md index 8f01053..3c71d19 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/status.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/status.md @@ -1,7 +1,18 @@ --- description: Show what TokenEconomizer has learned for this repository and what it has done --- -Run this exact command with the Bash tool, then show me its output verbatim in a code block. Add nothing unless the output contains a warning, in which case explain the warning in one sentence. +Run the command for this shell, then show me its output verbatim in a code block. Add nothing unless the output contains a warning, in which case explain the warning in one sentence. + +In Copilot CLI on Windows, use the PowerShell tool: + +```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 +``` + +Otherwise, run this command with the Bash tool: ``` te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" status diff --git a/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md b/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md index c757e9b..46b4f36 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md @@ -3,7 +3,18 @@ description: Review the tools TokenEconomizer left out of this repository's sess argument-hint: "[show | apply [TOOL ...] | restore [TOOL ...] | refresh-catalog | measure]" --- The arguments I typed after the command are: "$ARGUMENTS" (it shows the proposal when there are none). -Run this exact command with the Bash tool, then show me its output verbatim in a code block: +Run the command for this shell, then show me its output verbatim in a code block. + +In Copilot CLI on Windows, use the PowerShell tool: + +```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 toolprune $ARGUMENTS +``` + +Otherwise, run this command with the Bash tool: ``` te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" toolprune $ARGUMENTS diff --git a/plugins/tokeneconomizer/plugin/slash-commands/untool.md b/plugins/tokeneconomizer/plugin/slash-commands/untool.md index a5fc7b9..5ab36f6 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/untool.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/untool.md @@ -3,7 +3,18 @@ description: Earlier name of /tokeneconomizer:toolprune - review the deny list, argument-hint: "[show | apply [TOOL ...] | restore [TOOL ...] | refresh-catalog | measure]" --- The arguments I typed after the command are: "$ARGUMENTS" (it shows the proposal when there are none). -Run this exact command with the Bash tool, then show me its output verbatim in a code block: +Run the command for this shell, then show me its output verbatim in a code block. + +In Copilot CLI on Windows, use the PowerShell tool: + +```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 toolprune $ARGUMENTS +``` + +Otherwise, run this command with the Bash tool: ``` te="${CLAUDE_PLUGIN_ROOT}/scripts/te"; [ -x "$te" ] || te="${TOKENECONOMIZER_HOME:-$HOME/.tokeneconomizer}/bin/te"; "$te" --cwd "$(pwd)" toolprune $ARGUMENTS diff --git a/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py b/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py index 8c800ab..34676d9 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py +++ b/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py @@ -177,24 +177,84 @@ def _py_writes(text): return out +# git's own options that take the next word as their value (`git -C repo apply x.diff`). +_GIT_VALUE_OPTS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", + "--attr-source"} + + +def _git_args(tokens): + """The words of a git command from its subcommand on, past git's own options such as + `-C `, `-c =` or `--no-pager`; [] for any other command.""" + if tokens[0].rsplit("/", 1)[-1] != "git": + return [] + i = 1 + while i < len(tokens) and tokens[i].startswith("-"): + i += 2 if tokens[i] in _GIT_VALUE_OPTS else 1 + return tokens[i:] + + def _restored(tokens): """The paths a `git checkout -- ` or `git restore ` puts back; [] for any other command.""" - if tokens[0].rsplit("/", 1)[-1] != "git" or len(tokens) < 3 or \ - tokens[1] not in ("checkout", "restore"): + args = _git_args(tokens) + if len(args) < 2 or args[0] not in ("checkout", "restore"): return [] - rest = (tokens[tokens.index("--") + 1:] if "--" in tokens - else tokens[2:] if tokens[1] == "restore" else []) + rest = (args[args.index("--") + 1:] if "--" in args + else args[1:] if args[0] == "restore" else []) return [t for t in rest if not t.startswith("-")] +# The commands that run another one, and which of their own options take the next word as a +# value: `sudo -u bob sed -i ...`, `env -u VAR ...`, `timeout -s KILL 60 ...`, `nice -n 10 ...`. +_WRAPPERS = { + "sudo": {"-u", "-g", "-p", "-C", "-D", "-R", "-r", "-t", "-T", "-U", "--user", "--group", + "--prompt", "--close-from", "--chdir", "--chroot", "--role", "--type", + "--command-timeout", "--other-user"}, + "env": {"-u", "-C", "-S", "--unset", "--chdir", "--split-string"}, + "timeout": {"-s", "-k", "--signal", "--kill-after"}, + "nice": {"-n", "--adjustment"}, + "time": {"-f", "-o", "--format", "--output"}, + "command": set(), + "nohup": set(), +} + + +def _past_wrapper(tokens): + """The words after a wrapper such as `sudo` or `timeout`, its own options and, for + `timeout`, the duration.""" + takes_value = _WRAPPERS[tokens[0]] + i = 1 + while i < len(tokens) and tokens[i].startswith("-"): + t = tokens[i] + i += 1 + if t == "--": + break + if t.startswith("--"): + if t in takes_value: # `--user bob`, not `--user=bob` + i += 1 + continue + for n, letter in enumerate(t[1:], 2): # `-Eu bob`, `-ubob`, `-n10`, `-10` + if "-" + letter in takes_value: + if n == len(t): # the value is the next word + i += 1 + break + if tokens[0] == "timeout": + i += 1 + return tokens[i:] + + def _bare(cmds): - """Each command with the `sudo`, `env`, `VAR=1` ... before it dropped; empty ones left out.""" + """Each command with the `sudo -u bob`, `env -u VAR`, `timeout 60`, `VAR=1` ... before it + dropped; empty ones left out.""" out = [] for tokens in cmds: - while tokens and (tokens[0] in ("sudo", "command", "env", "time", "nohup") - or re.match(r"^\w+=", tokens[0])): - tokens = tokens[1:] + while tokens: + if tokens[0] in _WRAPPERS: + tokens = _past_wrapper(tokens) + elif re.match(r"^\w+=", tokens[0]): + tokens = tokens[1:] + else: + break if tokens: out.append(tokens) return out @@ -232,7 +292,7 @@ def shell_edit_targets(cmd): found += [t for t in tokens[1:] if not t.startswith("-") and _SOURCE_FILE.search(t)] elif head == "apply_patch": found += _PATCH_FILE.findall("\n".join(bodies + [" ".join(tokens[1:])])) or ["(patch)"] - elif head == "patch" or (head == "git" and len(tokens) > 1 and tokens[1] == "apply"): + elif head == "patch" or _git_args(tokens)[:1] == ["apply"]: found.append("(patch)") else: found += _restored(tokens) diff --git a/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py b/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py index 8f1bf1e..cce521f 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py +++ b/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py @@ -182,12 +182,17 @@ def update(self, tool_name, args, result_text, failed=None): tool_name = canon_tool(tool_name) # accept Copilot- or Claude-named tools action = tool_name or "?" if tool_name in _EDIT_TOOLS: - b = basename(args.get("path") or args.get("filePath") - or args.get("file_path") or "") - if b: + # A patch names every file it changes in `paths`; any other edit names one. + paths = args.get("paths") + if not isinstance(paths, (list, tuple)) or not paths: + paths = [args.get("path") or args.get("filePath") or args.get("file_path")] + names = list(dict.fromkeys(basename(p) for p in paths if isinstance(p, str))) + names = [b for b in names if b] + for b in names: self.edit_order.append(b) self.edit_counts[b] = self.edit_counts.get(b, 0) + 1 - action = f"edit {b}" + if names: + action = f"edit {', '.join(names)}" cmd = args.get("command", "") if tool_name == "bash" else "" if cmd: short = re.sub(r"\s+", " ", cmd.strip())[:90] diff --git a/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py b/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py index cf2f2e9..5495c89 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py +++ b/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py @@ -34,13 +34,25 @@ # is often named by path (`python tests/runtests.py`, `.venv/bin/pytest`, `./node_modules/.bin/ # jest`): without the optional directories those turns showed no verification at all, so a turn # whose last test run failed still counted as ended green and fed the envelope. +# `python` with the interpreter's own options before what it runs (`python -W error -m pytest`, +# `python -X dev -m pytest`, `python -u tests/runtests.py`); they are case-sensitive. +_PYTHON = (r"python\d?(?:\.\d+)?" + r"(?-i:(?:\s+(?:-[bBdEiIOPqsSuvx]+|-[WX]\s*[^\s\-]\S*))*)") VERIFY_RE = re.compile( - r"(?i)(?:^|[\s;&|(])(?:(?:~?/)?(?:[\w.\-]+/)*python\d?(?:\.\d+)?\s+)?" - r"(?:~?/)?(?:[\w.\-]+/)*(?:pytest|py\.test|tox|nox|python\d?(?:\.\d+)?\s+-m\s+(?:pytest|unittest)|" + r"(?i)(?:^|[\s;&|(])(?:(?:~?/)?(?:[\w.\-]+/)*" + _PYTHON + r"\s+)?" + r"(?:~?/)?(?:[\w.\-]+/)*(?:pytest|py\.test|tox|nox|" + _PYTHON + r"\s+-m\s+(?:pytest|unittest)|" r"manage\.py\s+test|runtests(?:\.py)?|jest|vitest|mocha|ava|playwright\s+test|" r"(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test|go\s+test|cargo\s+(?:test|nextest)|" r"(?:mvn|mvnw|\./mvnw)\s+(?:\S+\s+)*test|(?:gradle|gradlew|\./gradlew)\s+(?:\S+\s+)*test|" r"make\s+(?:test|check)|ctest|rspec|phpunit|dotnet\s+test|swift\s+test|mix\s+test|" + # Ruby: `rake test`, `bin/rails test`, and `ruby` given a test file (`ruby -Itest + # test/models/user_test.rb`), but not `ruby -e '...'`, a syntax check (`ruby -wc x.rb`) or a + # script that is not a test (`ruby repro.rb`): the options it takes are spelled out, and + # case-sensitive, so `-W` does not also take `-wc` under the pattern's `(?i)`. + r"rake(?:\s+\w+=\S*)*\s+(?:test|spec)(?::[\w:]+)?|rails\s+test(?::[\w:]+)?|" + r"ruby(?-i:\s+(?:-[Ir](?:\S+|\s+[^\s\-]\S*)|-C\s*\S+|-W[0-2]?(?::\S+)?|" + r"--[\w\-]+(?:=\S+)?|-[abdf-zABDF-Z]+))*\s+" + r"(?:[\w.\-~]*/)*(?:test_[\w.\-]*|[\w.\-]*_(?:test|spec))\.rb|" r"deno\s+test|node\s+--test|bazel\s+test|(?:\./)?bin/test)(?![\w.\-/])") # A command line's exit status is its LAST command's, so it may not be the test run's: `npm test @@ -55,9 +67,13 @@ _SEP_RE = re.compile(r"(&&|\|\||\|&|(?)\||;|\n)") # `|`, but not the `>|` redirect # A runner asked for its help, version or test list, not to run the tests. _NOT_A_RUN_RE = re.compile(r"\s(?:-h|--help|--version|--collect-only|--co|--list\S*)(?!\S)") -# What may precede the command itself: `FOO=1 timeout 60 npm test`, and a launcher that runs -# it in the project's environment, `uv run pytest`, `npx jest`, `bundle exec rspec`. -_PREFIX_RE = re.compile(r"^\s*(?:(?:\w+=\S*|time|nice|nohup|command|env|" +# What may precede the command itself: `FOO=1 timeout 60 npm test`, `env -u VAR`, `nice -n 10`, +# and a launcher that runs it in the project's environment, `uv run pytest`, `npx jest`, +# `bundle exec rspec`. +_PREFIX_RE = re.compile(r"^\s*(?:(?:\w+=\S*|time|nohup|command|" + r"nice(?:\s+(?:-n\s*|--adjustment=)?[-+]?\d+)?|" + # env's options; `-u`, `-C` and their long forms take a value + r"env(?:\s+(?:(?:-[uC]|--unset|--chdir)(?:=|\s*)[^\s-]\S*|-[-\w]*))*|" r"timeout(?:\s+(?:-\S+|[A-Z]+|\d\S*))+|" r"(?:(?:uv|poetry|pipenv|pdm|hatch|rye)\s+run|npx|bunx|" r"(?:npm|pnpm|yarn)\s+(?:exec|dlx)|bundle\s+exec|xvfb-run)" @@ -178,6 +194,9 @@ def status_of_tests(cmd): r"^(?:--- FAIL: |FAIL\t|FAIL$)", # go r"^test result: FAILED", # cargo r"\b\d+ examples?, [1-9]\d* failures?\b", # rspec + # minitest (`8 runs, 9 assertions, 1 failures, 0 errors, 0 skips`), test-unit (`tests`) + r"^\d+ (?:runs|tests), \d+ assertions, (?:[1-9]\d* failures, \d+ errors|\d+ failures, " + r"[1-9]\d* errors)\b", r"Tests run: \d+, Failures: (?:[1-9]|0, Errors: [1-9])", # JUnit (Maven, Gradle) r"BUILD FAIL(?:URE|ED)")), re.MULTILINE) _RUN_PASSED_RE = re.compile("|".join(( @@ -192,6 +211,7 @@ def status_of_tests(cmd): r"^ok\s+\S+\s+(?:\d+(?:\.\d+)?s|\(cached\))", r"^test result: ok\.", r"\b\d+ examples?, 0 failures\b", + r"^\d+ (?:runs|tests), \d+ assertions, 0 failures, 0 errors\b", # minitest, test-unit r"BUILD SUCCESS")), re.MULTILINE) diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/README.md b/plugins/tokeneconomizer/tokeneconomizer/microskills/README.md index 7c3d213..b24e60f 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/README.md +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/README.md @@ -22,6 +22,10 @@ Each finished session goes through three steps: retires on contradiction (for a command-spelling fact, two contradicting sessions in a row), and is injected only while the failure it prevents keeps occurring, or keeps being prevented, in at least 40% of the sessions that exercise it (over at least four). + A person can also retire a fact by hand (`stage.forget_facts`; the plugin's + `te microskills forget`): it leaves the block, and its id goes into its layer's + `forgotten` set, so the fact is never formed again under that id; the proposer's + admission also refuses a new id that confirms only on the forgotten fact's evidence. `stage.PrefixStage` ties these together for a caller: render the block before a session, fold the session in after it. The block is capped (`MAX_FACTS`, `MAX_TOKENS`), and a lint refuses any @@ -33,4 +37,4 @@ fact that reads as completion or verification advice. | `envfacts.py` | `EnvFactsDistiller`: the five LLM-free fact families, rendering, caps | | `distiller.py` | `Distiller`: the model-backed proposer (part of `microskills=on`) and its detector DSL | | `lifecycle.py` | `Lifecycle`: formation, retirement, the firing gate | -| `stage.py` | `PrefixStage`, `ComposedDistiller` | +| `stage.py` | `PrefixStage`, `ComposedDistiller`, `forget_facts` | diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/__init__.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/__init__.py index 70ea1db..37d98df 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/__init__.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/__init__.py @@ -13,8 +13,8 @@ from .envfacts import EnvFactsDistiller from .lifecycle import Lifecycle from .observe import GENERIC, NODE_WEB, PYTHON_GIT, Vocabulary, classify_command, observe_task -from .stage import ComposedDistiller, PrefixStage +from .stage import ComposedDistiller, PrefixStage, forget_facts, forgotten_facts __all__ = ["Distiller", "EnvFactsDistiller", "GENERIC", "Lifecycle", "NODE_WEB", "PYTHON_GIT", "Vocabulary", "classify_command", "observe_task", "ComposedDistiller", - "PrefixStage"] + "PrefixStage", "forget_facts", "forgotten_facts"] diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py index 79c78ad..2bb2629 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py @@ -23,7 +23,7 @@ from ..names import repo_filename from ..trace import call_cwds from ..trace.claude import CONVERSATION -from .lifecycle import Lifecycle, edited_files, edited_pyfiles +from .lifecycle import Forgetting, Lifecycle, edited_files, edited_pyfiles, write_json_atomic # ---- proposer cadence / caps / gates --------------------------------------- PROPOSE_EVERY = 8 # one LLM proposer call per this many tasks (PrefixStage rebinds @@ -79,6 +79,8 @@ def load_calls(fp): d = json.loads(line) except Exception: continue + if not isinstance(d, dict): + continue m = d.get("message") if not isinstance(m, dict) or d.get("type", "assistant") not in CONVERSATION: continue @@ -88,16 +90,23 @@ def load_calls(fp): for b in c: if not isinstance(b, dict): continue - if b.get("type") == "tool_use" and b.get("id") not in uses: - uses[b.get("id")] = (b.get("name", ""), b.get("input") or {}) - order.append(b.get("id")) + tid = b.get("id") if b.get("type") == "tool_use" else b.get("tool_use_id") + if not isinstance(tid, str): + continue + if b.get("type") == "tool_use" and tid not in uses: + name = b.get("name") + inp = b.get("input") + uses[tid] = (name if isinstance(name, str) else "", + inp if isinstance(inp, dict) else {}) + order.append(tid) elif b.get("type") == "tool_result": cont = b.get("content") if isinstance(cont, list): - txt = "\n".join(x.get("text", "") for x in cont if isinstance(x, dict)) + txt = "\n".join(x.get("text") for x in cont + if isinstance(x, dict) and isinstance(x.get("text"), str)) else: txt = cont if isinstance(cont, str) else json.dumps(cont) - res[b.get("tool_use_id")] = txt + res[tid] = txt return [(uses[t][0].lower(), uses[t][1], res.get(t, "")) for t in order] @@ -261,7 +270,7 @@ def proposer_view(dg): def _rx(pat): - if not pat: + if not pat or not isinstance(pat, str): return None try: return re.compile(pat) @@ -526,13 +535,23 @@ def parse_payload(raw): obj = json.loads(m.group(0)) except Exception: return [], [] - exts = [e for e in obj.get("extractors", []) - if isinstance(e, dict) and e.get("name") and e.get("pattern")] - facts = [f for f in obj.get("facts", []) - if isinstance(f, dict) and f.get("id") and f.get("detector")] + exts, facts = obj.get("extractors"), obj.get("facts") + exts = [e for e in (exts if isinstance(exts, list) else []) + if isinstance(e, dict) and isinstance(e.get("name"), str) and e.get("name") + and isinstance(e.get("pattern"), str) and e.get("pattern")] + facts = [f for f in (facts if isinstance(facts, list) else []) + if isinstance(f, dict) and isinstance(f.get("id"), str) and f.get("id") + and isinstance(f.get("detector"), dict) and f.get("detector") + and _detector_fields_ok(f["detector"]) + and (f.get("cite") is None or isinstance(f.get("cite"), list))] return exts, facts +def _detector_fields_ok(det): + return all(det.get(k) is None or isinstance(det.get(k), str) + for k in ("scope", "fired", "confirm", "contradict")) + + def _reparse_cmds(dg): """Recover [(cmd,out)] from a digest's stashed blobs (for retro-featurize). The blobs no longer say which output came from which command, so the whole output rides on the first @@ -543,7 +562,16 @@ def _reparse_cmds(dg): # ---- distiller ------------------------------------------------------------- -class Distiller: +def _forgotten_evidence(rec): + """The tasks a forgotten fact stood on when it was forgotten. An entry saved before they + were recorded falls back to the tasks the fact cited when it was admitted.""" + ev = rec.get("evidence") + if ev is None: + ev = ((rec.get("record") or {}).get("spec") or {}).get("cite") + return [i for i in (ev if isinstance(ev, list) else []) if isinstance(i, str)] + + +class Distiller(Forgetting): """Learns and injects a per-repo operating manual over the task stream. Public surface (the injection Stage calls these): @@ -553,6 +581,8 @@ class Distiller: d.update(transcript_path, iid=..., resolved=...) # fold in the finished task d.save(root) """ + FACT_CLS = Fact + def __init__(self, repo, runner=None, model="agent", external_facts=None, vocab=None): self.repo = repo # The plugin's generic reading (`Vocabulary.generic`): the generic digest and prompt. @@ -569,6 +599,7 @@ def __init__(self, repo, runner=None, model="agent", external_facts=None, vocab= self.last_propose = -1 self.extractors = {} # name -> Extractor self.raw_window = [] # bounded recent [(cmd,out)] per task + self.forgotten = {} # id -> {claim, record}: never admitted again # ---- featurization ----------------------------------------------------- def _observe_fact(self, fact, now, dg, files): @@ -641,6 +672,8 @@ def _maybe_propose(self): exts, facts = parse_payload(raw) for e in exts: self._admit_extractor(e) # append-only + # A forgotten id is refused at admission anyway: keep it from taking a candidate slot. + facts = [f for f in facts if f.get("id") not in self.forgotten] for spec in facts[:MAX_CANDS]: self._admit(spec) self.last_propose = self.now @@ -659,11 +692,44 @@ def _admit_extractor(self, spec): return True # ---- fact admission: new id = append; existing id = contradict-only revise -- + def _confirms(self, detector): + """The window's task ids on which `detector` confirms, under the CURRENT features.""" + out = set() + for dg in self.window: + det = DetectorV3Scope(detector or {}, dg.get("features", {})) + if det.verdict(dg)[0] == "confirm": + out.add(dg["iid"]) + return out + + def _evidence(self, fact): + """The window's tasks the fact's detector confirms on as it is forgotten: the evidence + a restatement under a new id would be grounded on (see _restates_forgotten).""" + return sorted(self._confirms(fact.spec.get("detector"))) + + def _restates_forgotten(self, spec): + """The forgotten fact a new-id candidate restates, if any: the candidate confirms on at + least MIN_CITE of the tasks that fact stood on when it was forgotten, and on no other + task in the window. Only that evidence counts, not what the forgotten detector would + confirm on now: it leaves the window as tasks come in, so a fact that later tasks + show (a corrected one, or another about the same commands) still gets in, where a + broad forgotten detector would otherwise keep it out for good.""" + mine = self._confirms(spec.get("detector")) + if len(mine) < MIN_CITE: + return None + for fid, rec in self.forgotten.items(): + theirs = set(_forgotten_evidence(rec)) + if len(mine & theirs) >= MIN_CITE and mine <= theirs: + return fid + return None + def _ground(self, spec): """#window cites whose confirm regex fires under the CURRENT features.""" by_iid = {d["iid"]: d for d in self.window} hits = 0 - for iid in (spec.get("cite") or []): + cites = spec.get("cite") + for iid in (cites if isinstance(cites, list) else []): + if not isinstance(iid, str): + continue dg = by_iid.get(iid) if dg is None: continue @@ -695,10 +761,14 @@ def _frozen_view(self, spec): def _admit(self, spec): fid = spec.get("id") + if fid in self.forgotten: + return False, "forgotten" if fid not in self.facts: hits = self._ground(spec) if hits < MIN_CITE: return False, f"grounding-fail({hits}/{MIN_CITE})" + if self.forgotten and self._restates_forgotten(spec): + return False, "restates-forgotten" spec.setdefault("rev", 1) self.facts[fid] = self._build_fact(spec) return True, "admitted" @@ -771,13 +841,14 @@ def save(self, root): window = [dict(dg, _cmd_blob=dg.get("_cmd_blob", "")[-BLOB_CAP:], _out_blob=dg.get("_out_blob", "")[-2 * BLOB_CAP:]) for dg in self.window[-WINDOW:]] - json.dump({"repo": self.repo, "now": self.now, "opt_tokens": self.opt_tokens, - "last_propose": self.last_propose, - "extractors": {k: e.to_dict() for k, e in self.extractors.items()}, - "facts": {k: f.to_dict() for k, f in self.facts.items()}, - "window": window, - "raw_cmds": [[c for c, _ in cmds] for cmds in self.raw_window[-WINDOW:]]}, - open(self._path(root, self.repo), "w", encoding="utf-8"), indent=2) + write_json_atomic(self._path(root, self.repo), { + "repo": self.repo, "now": self.now, "opt_tokens": self.opt_tokens, + "last_propose": self.last_propose, + "extractors": {k: e.to_dict() for k, e in self.extractors.items()}, + "facts": {k: f.to_dict() for k, f in self.facts.items()}, + "forgotten": self.forgotten, + "window": window, + "raw_cmds": [[c for c, _ in cmds] for cmds in self.raw_window[-WINDOW:]]}) @classmethod def load(cls, repo, root, runner=None, model="agent", external_facts=None, vocab=None): @@ -793,6 +864,8 @@ def load(cls, repo, root, runner=None, model="agent", external_facts=None, vocab self.facts = {k: Fact.from_dict(v) for k, v in d.get("facts", {}).items()} self.window = list(d.get("window") or [])[-WINDOW:] self.raw_window = [[(c, "") for c in cmds] for cmds in d.get("raw_cmds") or []] + self.forgotten = dict(d.get("forgotten") or {}) + self.drop_forgotten() return self def debug_row(self): diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py index 1fb079d..6026073 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py @@ -41,7 +41,7 @@ from collections import Counter from ..names import repo_filename -from .lifecycle import Lifecycle +from .lifecycle import Forgetting, Lifecycle, write_json_atomic from .observe import (DEFAULT_VOCAB, NETWORK_ERRORS, form_failed, form_worked, is_bare, label_rule, observe_task) @@ -243,7 +243,7 @@ def lint_ok(text): # -------------------------------------------------------------------------------------- # the distiller # -------------------------------------------------------------------------------------- -class EnvFactsDistiller: +class EnvFactsDistiller(Forgetting): """Learns and injects environment facts over a repository's task stream. Interface parity with `injection.Distiller`, so `PrefixStage` drives both the same way: @@ -256,6 +256,8 @@ class EnvFactsDistiller: on top is told not to restate. `max_facts` / `max_tokens` cap the rendered block (default MAX_FACTS / MAX_TOKENS). """ + FACT_CLS = EnvFact + def __init__(self, repo, runner=None, model="agent", vocab=None, max_facts=None, max_tokens=None): self.max_facts = int(max_facts or MAX_FACTS) @@ -264,6 +266,7 @@ def __init__(self, repo, runner=None, model="agent", vocab=None, max_facts=None, self.vocab = vocab or DEFAULT_VOCAB self.now = 0 self.facts = {} # id -> EnvFact + self.forgotten = {} # id -> {claim, record}: never learned again self.opt_tokens = 0.0 # invariant: LLM-free self.last_injected = set() # fact ids rendered for the task now running self.last_digest = None # the most recent per-task verdicts (telemetry) @@ -577,6 +580,7 @@ def update(self, transcript_path, iid="", resolved=None, edited=None): self.last_digest = {"iid": iid, "resolved": resolved, "injected": sorted(injected), "verdicts": verdicts, "n_calls": digest["n_calls"]} + self.drop_forgotten() self.last_injected = set() self.now += 1 @@ -588,10 +592,10 @@ def _path(root, repo): return os.path.join(d, repo_filename(repo) + ".json") def save(self, root): - with open(self._path(root, self.repo), "w", encoding="utf-8") as fh: - json.dump({"repo": self.repo, "now": self.now, "opt_tokens": 0.0, - "vocab": self.vocab.name, - "facts": {k: f.to_dict() for k, f in self.facts.items()}}, fh, indent=2) + write_json_atomic(self._path(root, self.repo), { + "repo": self.repo, "now": self.now, "opt_tokens": 0.0, "vocab": self.vocab.name, + "facts": {k: f.to_dict() for k, f in self.facts.items()}, + "forgotten": self.forgotten}) @classmethod def load(cls, repo, root, runner=None, model="agent", vocab=None, max_facts=None, @@ -604,6 +608,8 @@ def load(cls, repo, root, runner=None, model="agent", vocab=None, max_facts=None d = json.load(fh) self.now = d.get("now", 0) self.facts = {k: EnvFact.from_dict(v) for k, v in d.get("facts", {}).items()} + self.forgotten = dict(d.get("forgotten") or {}) + self.drop_forgotten() return self # ---- telemetry --------------------------------------------------------------- diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py index 63cf4a8..85465db 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py @@ -9,7 +9,9 @@ injected only while it clears the FIRING GATE: the waste it prevents occurred (or, once injected, kept being prevented) on at least FIRE_GATE of the tasks that exercised it. """ +import json import os +import time # ---- lifecycle knobs (the validated replay constants) ---------------------- K_PROMOTE = 3 # confirmations (drifted, where drift applies) to promote -> ACTIVE @@ -115,3 +117,87 @@ def update(self, now, verdict, fired, exercised, files): hard = self.high and verdict == "contradict" and HARD_KILL if hard or self.score(now) < SCORE_FLOOR: self.state, self.retired_at = "RETIRED", now + + +# ---- forgetting: a person retires a fact by hand ----------------------------- +# Seconds slept between tries of a Windows `os.replace`, which fails while another process has the +# target open; POSIX renames over an open file at once. +_REPLACE_BACKOFF = (0.01, 0.02, 0.05, 0.1, 0.2) + + +def write_json_atomic(path, obj): + """Write `obj` to `path` through a temporary file and `os.replace`: a reader, or a write cut + short, never leaves half a document behind.""" + tmp = f"{path}.{os.getpid()}.tmp" + try: + with open(tmp, "w", encoding="utf-8") as fh: + json.dump(obj, fh, indent=2) + for delay in _REPLACE_BACKOFF if os.name == "nt" else (): + try: + os.replace(tmp, path) + return + except PermissionError: + time.sleep(delay) + os.replace(tmp, path) + finally: + try: + os.unlink(tmp) + except FileNotFoundError: + pass + + +NO_RECORD = "no record" # truthy: the state changed and is saved + + +class Forgetting: + """The forgotten facts of a distiller (`self.facts`: id -> fact). A forgotten fact leaves + `facts`, so it is neither rendered nor folded; its id is kept in `forgotten`, with the claim + it made and its record, so that it is never learned again under that id and `unforget` can + put it back as it was. `FACT_CLS` reads a record back.""" + FACT_CLS = None + + @staticmethod + def _claim_of(fact): + claim = fact.claim + return claim() if callable(claim) else claim + + def known_ids(self): + return set(self.facts) | set(self.forgotten) + + def _evidence(self, fact): + """The sessions `fact` stands on as it is forgotten, for a layer that refuses a + restatement of it (the proposed facts); None for one that does not.""" + return None + + def forget(self, fid): + """True when `fid` is forgotten now, False when it already was; KeyError when no fact + has that id.""" + if fid in self.forgotten: + return False + fact = self.facts[fid] + entry = {"claim": self._claim_of(fact), "record": fact.to_dict()} + evidence = self._evidence(fact) + if evidence is not None: + entry["evidence"] = evidence + del self.facts[fid] + self.forgotten[fid] = entry + return True + + def unforget(self, fid): + """True when `fid` is back among the facts, False when it was not forgotten; KeyError + when no fact has that id. `NO_RECORD` when it was forgotten without a record (a + hand-edited state file): the id is no longer forgotten, but nothing is restored.""" + if fid not in self.forgotten: + if fid in self.facts: + return False + raise KeyError(fid) + rec = self.forgotten.pop(fid).get("record") + if not rec: + return NO_RECORD + self.facts[fid] = self.FACT_CLS.from_dict(rec) + return True + + def drop_forgotten(self): + """Take out any forgotten id the last fold learned again.""" + for fid in self.forgotten: + self.facts.pop(fid, None) diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/stage.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/stage.py index 430a4ef..1957890 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/stage.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/stage.py @@ -7,6 +7,7 @@ """ import os +from ..names import repo_filename from ..stage import Stage from . import distiller as _distiller from .distiller import Distiller @@ -130,3 +131,52 @@ def after_task(self, task, row, run_dir_path, srow): opt_tokens = self.distiller.opt_tokens - before srow["manual_facts"] = self.distiller.debug_row() return opt_tokens, self.reason + + +# ---- forgetting a fact by hand --------------------------------------------- +def _saved_layers(repo, root, vocab=None): + """The distillers with state saved under `root`, loaded: the environment layer first.""" + from . import envfacts + out = [] + for cls, sub in ((envfacts.EnvFactsDistiller, envfacts.STATE_SUBDIR), + (Distiller, _distiller.STATE_SUBDIR)): + if os.path.exists(os.path.join(root, sub, repo_filename(repo) + ".json")): + out.append(cls.load(repo, root, vocab=vocab)) + return out + + +def forget_facts(repo, root, ids, vocab=None, undo=False): + """Forget the facts `ids` (or, with `undo`, bring them back) in whichever saved layer holds + each, and save the layers that changed. A forgotten fact is no longer rendered, and is not + learned again under its id. Returns [(id, changed, claim)] in the order given. When an id + is unknown to every layer nothing is changed, and KeyError carries the unknown ids.""" + layers = _saved_layers(repo, root, vocab) + owner = {} + for layer in layers: + for fid in layer.known_ids(): + owner.setdefault(fid, layer) + unknown = [fid for fid in ids if fid not in owner] + if unknown: + raise KeyError(unknown) + out, changed = [], [] + for fid in dict.fromkeys(ids): + layer = owner[fid] + did = layer.unforget(fid) if undo else layer.forget(fid) + if did and layer not in changed: + changed.append(layer) + fact = layer.facts.get(fid) + claim = (layer._claim_of(fact) if fact is not None + else layer.forgotten.get(fid, {}).get("claim", "")) + out.append((fid, did, claim)) + for layer in changed: + layer.save(root) + return out + + +def forgotten_facts(repo, root, vocab=None): + """{id: the claim it made} for every forgotten fact saved under `root`.""" + out = {} + for layer in _saved_layers(repo, root, vocab): + for fid, rec in layer.forgotten.items(): + out.setdefault(fid, rec.get("claim", "")) + return out diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/accounting.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/accounting.py index a7ec78d..29bb259 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/accounting.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/accounting.py @@ -38,6 +38,7 @@ def summarize(records): A session imported from the agent's history (`imported: true`) ran before the plugin: it is counted on its own (`imported_sessions`) and left out of every other number.""" + records = [r for r in records if isinstance(r, dict)] imported = [r for r in records if r.get("kind") == "session" and r.get("imported")] records = [r for r in records if not r.get("imported")] sessions = [r for r in records if r.get("kind") == "session"] diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py index 5838624..f0a66f7 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py @@ -3,6 +3,10 @@ te status what it has learned for this repository, and what it did te status --explain explain the current settings and saved learning state te microskills the facts it injects, and the ones still forming + te microskills forget ID ... stop injecting the facts with these ids (as listed by + `te microskills`); they are not learned again + under that id or from the same evidence + te microskills unforget ID ... bring forgotten facts back, as they were te toolprune show the proposed deny list, and the evidence behind it te toolprune apply [ITEM ...] write the proposal (or the named items) to the repository's settings: tools (Claude Code), capabilities (Codex) or @@ -19,8 +23,8 @@ te config unset KEY ... back to the next source down (the global file, then default) te repomap [show | refresh] the repository map (`repomap=on`): what is cached, or make it now - te history import [--dry-run] Claude Code: fold this repository's sessions from before - the plugin, from Claude Code's own logs (no model calls, + te history import [--dry-run] fold this repository's sessions from before the plugin, + from the agent's own logs (no model calls, no deny list written; only before any session is folded; with `history_import=on`, the first session start runs it by itself) @@ -45,6 +49,7 @@ import glob import json import os +import shlex import sys import time @@ -264,7 +269,7 @@ def earlier(n): f"{accounting.fmt_tokens(ledger['effective_tokens'])} effective tokens, plugin " f"overhead {accounting.fmt_tokens(ledger['overhead_tokens'])} " f"({ledger['overhead_frac']:.1%})") - hist = history.describe(out["history"]) + hist = history.describe(out["history"], ctx.host.name) if hist: print(f" history {hist}") i = out["microskills"] @@ -294,6 +299,12 @@ def earlier(n): def cmd_microskills(args): + if args.action in ("forget", "unforget"): + return _microskills_forget(args) + if args.ids: + print(f"`microskills {args.action}` takes no ids; did you mean `microskills forget " + f"{' '.join(args.ids)}`?") + return 2 ctx = _ctx(args) inj = ctx.store.read("injection.json") or {} if ctx.config.microskills == "off": @@ -311,6 +322,55 @@ def cmd_microskills(args): for k, v in sorted(rows): print(f" {v.get('state', '?'):9s} fire={v.get('fire', '?'):>5s} " f"{'INJECTED' if v.get('inject') else ' '} {k}") + from tokeneconomizer.microskills import forgotten_facts + gone = forgotten_facts(ctx.repo.label, os.path.join(ctx.store.base, "mechanisms")) + if gone: + print("\nforgotten (`microskills unforget ID` brings one back):") + for k, claim in sorted(gone.items()): + print(f" {k}" + (f" ({_short(claim)})" if claim else "")) + return 0 + + +def _short(text, n=80): + text = " ".join(str(text).split()) + return text if len(text) <= n else text[:n - 1] + "\u2026" + + +def _microskills_forget(args): + from tokeneconomizer.microskills.lifecycle import NO_RECORD + undo = args.action == "unforget" + if not args.ids: + print(f"`microskills {args.action}` needs the id of at least one fact; " + f"`microskills` lists them") + return 2 + ctx = _ctx(args) + refused = _refuse_unwritable(ctx.root) + if refused: + return refused + try: + done = fold.forget_microskills(ctx, args.ids, undo=undo) + except KeyError as e: + unknown = e.args[0] if e.args and isinstance(e.args[0], list) else list(e.args) + print(f"not changed: no learned fact here has the id {', '.join(unknown)} " + f"({ctx.host.name}, {ctx.repo.label}); `microskills` lists the ids") + return 1 + except fold.Busy as e: + print(f"not changed: {e}; try again in a moment") + return 1 + for fid, changed, claim in done: + if changed == NO_RECORD: + print(f"no longer forgotten, but nothing to bring back: {fid} had no saved record; " + f"a later fold may learn it again") + continue + what = (("brought back" if changed else "not forgotten, nothing to bring back") if undo + else ("forgotten" if changed else "already forgotten")) + print(f"{what}: {fid}" + (f" ({_short(claim)})" if claim else "")) + if any(changed for _, changed, _ in done): + print("from the next session, " + ( + "these facts are kept and injected under the same rules as any other fact" if undo + else "these facts are not injected, and are not learned again under the same id " + "or from the same evidence " + "(`microskills unforget ID` undoes this)")) return 0 @@ -583,6 +643,8 @@ def _config_view(cfg): "history_max_sessions": d.pop("history_max_sessions"), "history_days": d.pop("history_days"), "history_dirs": d.pop("history_dirs")}, + "droid": {"state": "on" if cfg.droid_sidecall else "off", + "droid_sidecall": d.pop("droid_sidecall")}, "other": d, "warnings": cfg.warnings, } @@ -623,7 +685,7 @@ def cmd_config(args): print(f"{path}: {json.dumps(cur, sort_keys=True)}") print("applies from the next hook call; a new fact-size cap applies once the next session " "has been folded") - if {canonical(k) for k in updates} & {"microskills", "loopguard"} and sidecall.resume( + if {canonical(k) for k in updates} & {"microskills", "loopguard", "droid_sidecall"} and sidecall.resume( ctx.host.name, ctx.root): print(f"the plugin's model calls through `{sidecall.call_name(ctx.host.name)}` will be " f"tried again") @@ -654,7 +716,7 @@ def _print_history(ctx, doc): print(f"no import of earlier sessions recorded for {ctx.repo.label}" + ("" if ctx.config.history_import else " (history_import is off)")) return - print(f"{ctx.repo.label}: {history.describe(doc) or doc.get('state')}") + print(f"{ctx.repo.label}: {history.describe(doc, ctx.host.name) or doc.get('state')}") skipped = doc.get("skipped") if isinstance(doc.get("skipped"), dict) else {} if doc.get("over_limit"): skipped = dict(skipped, older_than_the_newest=doc["over_limit"]) @@ -663,13 +725,13 @@ def _print_history(ctx, doc): def cmd_history(args): - """`te history [import]`: a repository's sessions from before the plugin (Claude Code).""" + """`te history [import]`: a repository's sessions from before the plugin.""" ctx = _ctx(args) if args.action == "status" or args.status: _print_history(ctx, history.summary(ctx)) return 0 if not ctx.host.keeps_history: - print(f"{ctx.host.name}: no session history the plugin reads (Claude Code only)") + print(f"{ctx.host.name}: no session history the plugin reads") return 1 if args.dry_run: p = history.plan(ctx) @@ -739,6 +801,13 @@ def cmd_repos(args): if not args.keys or len(args.keys) > 2: print("usage: te repos merge KEY [INTO] (keys as `te repos` lists them)") return 2 + # A key names one directory in `repos/`: `.`, `""` or a path would name `repos/` + # itself, or somewhere else, and the merge would set all of it aside. + bad = [k for k in args.keys if k in ("", ".", "..") or os.path.basename(k) != k + or "/" in k or "\\" in k] + if bad: + print(f"not a state directory key: {bad[0]!r} (keys as `te repos` lists them)") + return 2 src = args.keys[0] if not os.path.isdir(os.path.join(repos.repos_dir(root), src)): print(f"no state directory {src!r} in {repos.repos_dir(root)}") @@ -813,13 +882,14 @@ def cmd_doctor(args): ok = False import shutil as _sh # Only the agents installed here: a Codex-only machine has no Claude Code catalog to probe. - agents = [h for h in ("antigravity", "claude", "codex", "copilot", "grok", "hermes", "opencode", - "pi") + agents = [h for h in ("antigravity", "claude", "codex", "copilot", "droid", "grok", "hermes", + "opencode", "pi") if _sh.which(sidecall.claude_cli() if h == "claude" else sidecall.hermes_cli() if h == "hermes" else "agy" if h == "antigravity" else h)] print("agents " + (', '.join(agents) or 'none of antigravity (agy), claude, codex, ' - 'copilot, grok, hermes, opencode, pi on PATH')) + 'copilot, droid, grok, hermes, opencode, pi on PATH')) + ctx = _ctx(args) # the per-agent lines below read the settings in effect for h in agents: pause = sidecall.paused(h, root) if pause: @@ -831,7 +901,7 @@ def cmd_doctor(args): cat = os.path.join(root, "hosts", "claude", "catalog.json") print(f"claude catalog {'present' if os.path.exists(cat) else 'not probed'}") if "codex" in agents: - trusted = denylist.codex_project_trusted(args.cwd) + trusted = denylist.codex_project_trusted(ctx.repo.root) if trusted is not None: print(f"codex this project is {'trusted' if trusted else 'NOT trusted'} " f"(an untrusted project's .codex/config.toml is ignored)") @@ -853,6 +923,17 @@ def cmd_doctor(args): if ctrust is not None: print(f"copilot this folder is {'trusted' if ctrust else 'NOT trusted'} (an " f"untrusted folder's .github/copilot settings are ignored)") + if "droid" in agents: + sessions = os.environ.get("DROID_SESSIONS_DIR") or os.path.join( + os.path.expanduser("~"), ".factory", "sessions") + if getattr(ctx.config, "droid_sidecall", False): + side = "on (the `droid_sidecall` setting)" + elif sidecall.droid_enabled(): + side = "on (TE_DROID_SIDECALL=1)" + else: + side = ("off (set `droid_sidecall=on` or TE_DROID_SIDECALL=1 to try them)") + print(f"droid sessions {sessions}; side calls {side}; tool pruning is not " + f"available in the TUI") if "hermes" in agents: link = os.path.join(sidecall.hermes_home(), "plugins", "tokeneconomizer") print(f"hermes plugin {'linked at ' + link if os.path.exists(link) else 'not in ' + link}" @@ -866,7 +947,6 @@ def cmd_doctor(args): pkgs = [] mine = [p for p in pkgs if "tokeneconomizer" in json.dumps(p).lower()] print(f"pi package {'installed: ' + str(mine[0]) if mine else 'not in ' + settings}") - ctx = _ctx(args) print(f"repository {ctx.repo.root}: {repos.describe(ctx.repo)}; state {ctx.repo.key}") home_git = os.path.join(paths.home_dir(), ".git") for path in repos.ignored_git_entries(args.cwd): @@ -916,7 +996,12 @@ def add(name, *aliases): p.add_argument("--explain", action="store_true", help="briefly explain current settings and saved state (no model calls)") p.set_defaults(fn=cmd_status) - add("microskills", "facts").set_defaults(fn=cmd_microskills) + p = add("microskills", "facts") + p.add_argument("action", nargs="?", default="show", choices=("show", "forget", "unforget"), + help="show the facts (default); forget: stop injecting them and never learn " + "them again; unforget: bring forgotten facts back") + p.add_argument("ids", nargs="*", metavar="ID", help="fact ids, as `te microskills` lists them") + p.set_defaults(fn=cmd_microskills) p = add("toolprune", "untool") p.add_argument("action", nargs="?", default="show", choices=("show", "apply", "restore", "refresh-catalog", "measure", @@ -978,7 +1063,35 @@ def _recent_host(cwd): return max(seen, key=seen.get) if seen else None +def _split_argline(line): + """Split on whitespace and quotes as a POSIX shell would, but keep a backslash as typed: + on Windows `C:\\Python312\\python.exe` is a path, not two escapes. An unclosed quote + raises ValueError.""" + lex = shlex.shlex(line, posix=True) + lex.whitespace_split = True + lex.escape = "" + lex.commenters = "" + return list(lex) + + +def _expand_argline(argv): + """`--argline TEXT` stands for TEXT split by `_split_argline`: a host's slash command + (Pi's `/te ...`) hands over the line as typed, and a fact id may hold spaces and quotes.""" + argv = list(sys.argv[1:] if argv is None else argv) + for i, a in enumerate(argv): + if a == "--argline" and i + 1 < len(argv): + return argv[:i] + _split_argline(argv[i + 1]) + argv[i + 2:] + if a.startswith("--argline="): + return argv[:i] + _split_argline(a.split("=", 1)[1]) + argv[i + 1:] + return argv + + def main(argv=None): + try: + argv = _expand_argline(argv) + except ValueError as e: + print(f"te: could not read the arguments: {e}") + return 2 args = build_parser().parse_args(argv) if args.host is None: args.host = hosts.default_host(recent=_recent_host(args.cwd)) diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py index c71538b..1377204 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py @@ -48,12 +48,26 @@ * repomap, repomap_tokens, repomap_python, repomap_timeout -- the opt-in repository map; * _paid_model -- the model of the plugin's own calls on that agent, over `paid_model` (claude, codex, copilot, pi, opencode, cursor, - grok, hermes); + grok, hermes, droid); * claude_paid_effort, codex_paid_effort -- their reasoning effort on those two agents; + * local_model, local_roles -- run the named side calls (`judge`, `nudge`, `proposer`; + default `judge`) on an on-device model instead of the + agent's CLI: `fm`, Apple's Foundation Models CLI on macOS 27. + Off by default. A call the local model cannot make -- no `fm`, + model unavailable, no reply -- falls back to the agent's CLI. + Local calls are charged 0 tokens; + * local_judge_confidence -- the confidence a stuck verdict from the local judge must reach + to count (default 0.9); below it the turn is spared. The local + model's confidences come in coarse steps, so the guard's own + `judge_confidence` would let nearly every local "stuck" + through; how 0.9 was chosen: microsoft/TokenEconomizer#186; * pi_extensions, pi_cli -- on Pi, the extensions the plugin's own model calls load (a custom provider's, whose model they could not reach otherwise; comma-separated paths), and the `pi` they run; * hermes_cli -- on Hermes, the `hermes` the plugin's own model calls run; + * droid_sidecall -- on Droid, allow the plugin's own model calls. They run + `droid exec`, which writes a session log of its own, so this + is off by default: `microskills=envfacts` learns without it; * history_import -- on Claude Code, fold a repository's sessions from before the plugin (Claude Code's own logs) once, at its first session start, when nothing is folded there yet. Off by default: @@ -82,6 +96,12 @@ from dataclasses import asdict, dataclass, field, fields MICROSKILLS = ("off", "envfacts", "envfacts+distiller", "distiller") +# An on-device model some side calls can run on instead of the agent's CLI (`sidecall.local_runner`): +# "fm" is Apple's Foundation Models CLI (`/usr/bin/fm`, macOS 27 with Apple Intelligence). +LOCAL_MODELS = ("off", "fm") +# The side calls `local_roles` may name. The judge is the default because it is the one the +# evaluation supports; the redirect writer and the proposer are opt-in. +LOCAL_ROLES = ("judge", "nudge", "proposer") TOOLPRUNE = ("off", "propose", "auto") LOOPGUARD = ("off", "nudge", "stop") REPOMAP = ("off", "on", "start") @@ -186,11 +206,16 @@ class LiveConfig: cursor_paid_model: str = "" grok_paid_model: str = "" hermes_paid_model: str = "" + droid_paid_model: str = "" claude_paid_effort: str = "" codex_paid_effort: str = "" + local_model: str = "off" + local_roles: list = field(default_factory=lambda: ["judge"]) + local_judge_confidence: float = 0.9 pi_extensions: list = field(default_factory=list) pi_cli: str = "" hermes_cli: str = "" + droid_sidecall: bool = False history_import: bool = False history_max_sessions: int = 200 history_days: int = 365 @@ -201,6 +226,7 @@ class LiveConfig: _CHOICES = {"mode": MODES, "microskills": MICROSKILLS, "toolprune": TOOLPRUNE, "loopguard": LOOPGUARD, "repomap": REPOMAP, "loopguard_aggr": AGGR, + "local_model": LOCAL_MODELS, "vocabulary": ("auto", "generic", "python-git", "node-web"), # Each CLI's own words (Claude Code 2.1.319, Codex 0.167.0); whether a model # takes one is the CLI's to say. @@ -245,6 +271,12 @@ def set(self, key, value, source="?"): if isinstance(cur, list): items = value if isinstance(value, list) else str(value).split(",") v = [str(x).strip() for x in items if str(x).strip()] + elif isinstance(cur, float): + if isinstance(value, bool): + raise ValueError("not a number") + v = float(value) + if not 0.0 <= v <= 1.0: + raise ValueError("must be between 0 and 1") elif isinstance(cur, bool): v = value if isinstance(value, bool) else str(value).strip().lower() in ( "1", "true", "yes", "on") @@ -262,6 +294,11 @@ def set(self, key, value, source="?"): except (TypeError, ValueError, OverflowError) as e: self.warnings.append(f"{source}: {key}={value!r} rejected ({e})") return False + if key == "local_roles": + bad = [r for r in v if r not in LOCAL_ROLES] + if bad: + self.warnings.append(f"{source}: local_roles {bad!r} not in {LOCAL_ROLES}") + return False choices = self._CHOICES.get(key) if choices and v not in choices: self.warnings.append(f"{source}: {key}={v!r} not one of {choices}") @@ -300,8 +337,10 @@ def _set_threshold(self, name, value, source): _ENV = {"TE_MODE": "mode", "TE_SHADOW": "shadow", "TE_PAID_MODEL": "paid_model", "TE_VOCABULARY": "vocabulary", **{f"TE_{a.upper()}_PAID_MODEL": f"{a}_paid_model" for a in ( - "claude", "codex", "copilot", "pi", "opencode", "cursor", "grok", "hermes")}, + "claude", "codex", "copilot", "pi", "opencode", "cursor", "grok", "hermes", "droid")}, "TE_CLAUDE_PAID_EFFORT": "claude_paid_effort", "TE_CODEX_PAID_EFFORT": "codex_paid_effort", + "TE_LOCAL_MODEL": "local_model", "TE_LOCAL_ROLES": "local_roles", + "TE_LOCAL_JUDGE_CONFIDENCE": "local_judge_confidence", "TE_INJECT": "microskills", "TE_INJECT_MAX_FACTS": "microskills_max_facts", "TE_INJECT_MAX_TOKENS": "microskills_max_tokens", "TE_PROPOSE_EVERY": "microskills_propose_every", diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py index cfef0b2..cd338f7 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py @@ -95,16 +95,17 @@ def handle(self): self.ctx.settle() self.cfg = self.ctx.config event = self.p.get("hook_event_name") or "" + if event in ("SessionStart", "UserPromptSubmit"): + try: + ensure_launcher(self.ctx.env) + except OSError: + self._record_error() handler = self.handler(event) return hookqueue.run(self, event, handler) if handler else {} # ---- SessionStart ----------------------------------------------------------------- def session_start(self): source = self.p.get("source") or "startup" - try: - ensure_launcher(self.ctx.env) - except OSError: - pass s = self._session() s["source"] = source s.setdefault("cwd", self.host.cwd(self.p, self.ctx.env)) @@ -332,8 +333,13 @@ def _judge(self, thr, envelope): from .judge import AsyncJudge, NoVerdict if envelope is None: return None - if self.host.name in sidecall.NO_SIDE_CALLS or sidecall.paused(self.host.name, - self.ctx.root): + if self.host.name in sidecall.NO_SIDE_CALLS: + return NoVerdict() + # A local judge (`local_model`) needs no login, so it still answers while the host's + # CLI is paused (signed out). Only the settings are read here, as this runs on every + # tool call; the job checks that the model answers, and with none spares the turn. + if (sidecall.paused(self.host.name, self.ctx.root) + and not sidecall.local_routes("judge", self.ctx.config)): return NoVerdict() return AsyncJudge(self.ctx, self.sid, thr.get("judge_confidence")) diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/denylist.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/denylist.py index 7f75a78..003891a 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/denylist.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/denylist.py @@ -504,13 +504,14 @@ def codex_home(env=None): def codex_project_trusted(repo_root, env=None): """True/False from the user's Codex config: is this checkout a trusted project? A project-local `.codex/config.toml` is ignored until it is. None if the config is - unreadable.""" + unreadable. Decided as Codex decides it: the checkout's own entry, else -- for a linked + worktree -- the entry of the clone it was made from.""" + from .paths import _main_checkout try: text = open(os.path.join(codex_home(env), "config.toml"), encoding="utf-8").read() except OSError: return None - want = {os.path.normcase(p) for p in (os.path.abspath(repo_root), os.path.realpath(repo_root))} - current = None + levels, current = {}, None for line in text.splitlines(): m = re.match(r'^\s*\[projects\.(?:"([^"]+)"|\'([^\']+)\')\]\s*$', line) if m: @@ -519,8 +520,14 @@ def codex_project_trusted(repo_root, env=None): if _ANY_HEADER_RE.match(line): current = None continue - if current in want and re.match(r'^\s*trust_level\s*=\s*"trusted"', line): - return True + m = re.match(r'^\s*trust_level\s*=\s*"([^"]*)"', line) + if current is not None and m: + levels[current] = m.group(1) + main = _main_checkout(repo_root) + for root in (repo_root, main) if main else (repo_root,): + for p in (os.path.abspath(root), os.path.realpath(root)): + if os.path.normcase(p) in levels: + return levels[os.path.normcase(p)] == "trusted" return False diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py index a99e0d5..efe98b7 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py @@ -64,22 +64,28 @@ def _run_dir(workdir, trace_path): return run +def _microskills_config(ctx, profile): + from tokeneconomizer.config import InjectionConfig + return InjectionConfig(enabled=True, profile=profile, + propose_every=ctx.config.microskills_propose_every, + max_facts=ctx.config.microskills_max_facts, + max_tokens=ctx.config.microskills_max_tokens) + + def _fold_microskills(ctx, adapter, run_dir, session_id, injected=None, imported=False): profile = ctx.config.microskills if profile == "off": return None - from tokeneconomizer.config import InjectionConfig from tokeneconomizer.microskills import PrefixStage - icfg = InjectionConfig(enabled=True, profile=profile, - propose_every=ctx.config.microskills_propose_every, - max_facts=ctx.config.microskills_max_facts, - max_tokens=ctx.config.microskills_max_tokens) + icfg = _microskills_config(ctx, profile) # Paused once the host's CLI said it is not signed in (`sidecall.paused`): the free layer # still learns. A session read from the agent's history never calls a model: the free # layer learns from it, and the proposer waits for sessions the plugin sees end. - runner = (sidecall.runner_for(ctx.host.name, ctx.config) - if icfg.paid and not imported and not sidecall.paused(ctx.host.name, ctx.root) - else None) + runner = None + if icfg.paid and not imported: + runner = (sidecall.runner_for(ctx.host.name, ctx.config, role="proposer") + if not sidecall.paused(ctx.host.name, ctx.root) + else sidecall.local_runner("proposer", ctx.config)) stage = PrefixStage(icfg, ctx.repo.label, ctx.mech_dir, False, runner=runner, optimizer_model="agent", adapter=adapter, agent=ctx.host.name) srow = {"resolved": None} @@ -98,6 +104,42 @@ def _fold_microskills(ctx, adapter, run_dir, session_id, injected=None, imported return {"optimizer_tokens": float(opt_tokens or 0), "rendered_chars": len(rendered)} +class Busy(RuntimeError): + """Another fold holds this repository's learning state.""" + + +def forget_microskills(ctx, ids, undo=False): + """`te microskills forget` (`unforget` with `undo`): forget the facts `ids` in this + repository's learning state, so that no later fold learns them again, and render the cached + block again without them (with them, for `unforget`). Returns [(id, changed, claim)]; + raises KeyError with the unknown ids, changing nothing, and `Busy` when a fold holds the + state longer than the lock waits.""" + from tokeneconomizer.microskills import PrefixStage, forget_facts + adapter = LiveAdapter(ctx.host, ctx.repo.root, vocabulary=ctx.config.vocabulary, + catalog={}, protect=ctx.config.toolprune_protect) + vocab = adapter.env_vocabulary() + with ctx.store.locked("mechanisms") as got: + if not got: + raise Busy("a fold of this repository's sessions holds its state") + out = forget_facts(ctx.repo.label, ctx.mech_dir, ids, vocab=vocab, undo=undo) + prior = ctx.store.read("injection.json") + profile = (ctx.config.microskills if ctx.config.microskills != "off" + else (prior or {}).get("profile")) + if not any(changed for _, changed, _ in out) or prior is None or not profile: + return out + stage = PrefixStage(_microskills_config(ctx, profile), ctx.repo.label, ctx.mech_dir, + False, adapter=adapter, agent=ctx.host.name) + rendered = stage.render() or "" + facts = dict(stage.distiller.debug_row()) if stage.distiller else {} + # What only a fold knows (the last session's verdicts) stays as the fold left it. + facts.update({k: v for k, v in (prior.get("facts") or {}).items() + if k.startswith("_") and k not in facts}) + ctx.store.write("injection.json", dict( + prior, rendered=rendered, rendered_ids=stage.injected_ids(), facts=facts, + updated=time.time())) + return out + + def enough_evidence(sessions, prompts, cfg, high_risk=False): """Has a never-used tool gone unused long enough to be left out? Over `toolprune_evidence` prompts spread across at least `toolprune_min_sessions` sessions, or over diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/history.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/history.py index 0b37827..95067b9 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/history.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/history.py @@ -155,14 +155,13 @@ def _identity(cwd, env, cache): def is_this_repository(ctx, folder, cwd, cache=None): """Is a log filed under `folder` that names `cwd` a session of this repository? Its recorded - directory decides, keyed as a live session's is; only where that directory is gone, an - exact match of the folder with the one Claude Code derives from the repository's root.""" + directory decides, keyed as a live session's is; only where that directory is gone, the + host's own folder rule decides (Claude Code's derived project folder, Droid's encoded + workspace name).""" cache = {} if cache is None else cache if cwd and os.path.isdir(cwd): return _identity(cwd, ctx.env, cache) == ctx.repo.key - root = ctx.repo.root - names = {trace.claude_project_folder(root), trace.claude_project_folder(os.path.realpath(root))} - return folder in names + return ctx.host.folder_matches(ctx.repo.root, folder) def _headless(head, prompts): @@ -184,10 +183,10 @@ def plan(ctx, now=None): def skip(why): skipped[why] = skipped.get(why, 0) + 1 for log in ctx.host.history(ctx.env, cfg.history_dirs): - head = trace.claude_log_head(log["path"]) + head = ctx.host.log_head(log["path"]) if not is_this_repository(ctx, log["folder"], head.get("cwd"), cache): continue - sid = trace.claude_safe_session_id(log["session_id"]) + sid = ctx.host.safe_session_id(log["session_id"]) mtime, size = log["mtime"], log["size"] if sid is None: skip("unsafe_id") @@ -202,7 +201,7 @@ def skip(why): elif os.path.exists(ctx.store.path("sessions", f"{sid}.json")): skip("recorded_live") else: - prompts = trace.claude_prompt_count(log["path"]) + prompts = ctx.host.prompt_count(log["path"]) or 0 if prompts <= 0: skip("no_prompt") elif _headless(head, prompts): @@ -217,7 +216,7 @@ def skip(why): def _still_eligible(ctx, item): """Why a planned session is no longer to be imported (a resumed plan), or None.""" - sid = trace.claude_safe_session_id(item.get("id")) if isinstance(item, dict) else None + sid = ctx.host.safe_session_id(item.get("id")) if isinstance(item, dict) else None path = item.get("path") if isinstance(item, dict) else None if sid is None or not isinstance(path, str) or os.path.basename(path) != f"{sid}.jsonl": return "unsafe_id" @@ -250,12 +249,12 @@ def replay_envelope(ctx, transcript_path): level, overrides = cfg.loopguard_aggr, cfg.loopguard_thresholds thr = loopguard.base_thresholds(level, overrides) recorded = 0 - turns = trace.claude_prompt_turns(transcript_path) + turns = ctx.host.prompt_turns(transcript_path) turn = next(turns, None) while turn is not None: following = next(turns, None) guard = loopguard.TurnGuard() - for name, args, result, ok, _cwd in trace.claude_calls(turn): + for name, args, result, ok, _cwd in ctx.host.turn_calls(turn): result = (result or "")[:RESULT_CAP] if ok: code = claude_success_code(name, args) @@ -264,8 +263,8 @@ def replay_envelope(ctx, transcript_path): code = int(m.group(1)) if m else None guard.fold(name, args if isinstance(args, dict) else {}, result, code, envelope=None, thr=thr, judge=None) - normal = not trace.claude_turn_interrupted(turn) and ( - following is not None or trace.claude_turn_answered(turn)) + normal = not ctx.host.turn_interrupted(turn) and ( + following is not None or ctx.host.turn_answered(turn)) if guard.cum_turns and normal: loopguard.record_turn(ctx.store, guard, level=level, overrides=overrides) recorded += 1 @@ -496,7 +495,7 @@ def mark(d): if _update(ctx, mark, timeout=HISTORY_LOCK_S) is None or not out.get("n"): return None return (f"TokenEconomizer read {out['n']} earlier session(s) of {ctx.repo.label} from " - f"Claude Code's history.") + f"{HOST_LABEL.get(ctx.host.name, 'Claude Code')}'s history.") def summary(ctx): @@ -510,16 +509,23 @@ def summary(ctx): return out -def describe(doc): +# The agent's name as a person reads it, for the lines that name whose logs were read. +HOST_LABEL = {"claude": "Claude Code", "codex": "Codex", "copilot": "Copilot CLI", "pi": "Pi", + "opencode": "opencode", "cursor": "Cursor", "hermes": "Hermes Agent", + "droid": "Droid"} + + +def describe(doc, host="claude"): """One line for `te status`: what the import did here.""" if not doc: return None state = doc.get("state") n = int(_num(doc.get("imported"))) + who = HOST_LABEL.get(str(host or "claude"), "Claude Code") if state == "done": - return f"read {n} earlier session(s) from Claude Code's history" + return f"read {n} earlier session(s) from {who}'s history" if state in fold.HISTORY_BLOCKING: - return (f"reading Claude Code's history: {n} session(s) so far, {doc.get('left', '?')} " + return (f"reading {who}'s history: {n} session(s) so far, {doc.get('left', '?')} " f"to go; sessions ending meanwhile are folded after it") if state == "skipped": return f"not read ({doc.get('reason') or 'skipped'})" diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/hook.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/hook.py index 67bd1ae..52ab161 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/hook.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/hook.py @@ -1,7 +1,7 @@ """The entry point every plugin hook executes: hook JSON on stdin, hook JSON on stdout. - python -m tokeneconomizer.plugin.hook [--host antigravity|claude|codex|copilot|cursor|grok|hermes| - opencode|pi] [--event NAME] + python -m tokeneconomizer.plugin.hook [--host antigravity|claude|codex|copilot|cursor|droid|grok| + hermes|opencode|pi] [--event NAME] It never fails the agent. Whatever goes wrong -- unreadable input, a full disk, a bug -- the hook prints `{}` (which changes nothing) and records the traceback in `/errors.log`. It diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/hookqueue.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/hookqueue.py index e5ba1ff..12d7d0b 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/hookqueue.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/hookqueue.py @@ -143,6 +143,14 @@ def run(ctrl, event, handler): name = _safe(ctrl.sid) queue = os.path.join(base, name + ".queue") with Store(base).locked(name, timeout=WAITS.get(event, 3.0)) as got: + if got: + # Taking a lock writes nothing to its file, so its age would be the session's, and + # `_prune` would remove the lock of a session older than IDLE_S while a hook holds + # it: on POSIX the session's next hook would lock a new file and run beside it. + try: + os.utime(os.path.join(base, f".{name}.lock")) + except OSError: + pass _prune(base) if got: drain(ctrl, queue) diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/hosts.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/hosts.py index 556d40e..5351a9e 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/hosts.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/hosts.py @@ -229,6 +229,31 @@ def history(self, env, extra_dirs=()): the plugin reads.""" return [] + # -- the session-log details the history import reads --------------------------------- + def log_head(self, path): + """`{cwd, started, entrypoint?}` for a session log: the header the import filters on.""" + return trace.claude_log_head(path) + + def safe_session_id(self, sid): + return trace.claude_safe_session_id(sid) + + def prompt_turns(self, path): + return trace.claude_prompt_turns(path) + + def turn_calls(self, turn_lines): + return trace.claude_calls(turn_lines) + + def turn_interrupted(self, turn_lines): + return trace.claude_turn_interrupted(turn_lines) + + def turn_answered(self, turn_lines): + return trace.claude_turn_answered(turn_lines) + + def folder_matches(self, root, folder): + """Does a log's folder name this repository's root, when the log's cwd is gone?""" + return folder in {trace.claude_project_folder(root), + trace.claude_project_folder(os.path.realpath(root))} + def _failure_response(p): """A PostToolUseFailure payload's `error` as a response; None for any other payload. A @@ -1191,8 +1216,109 @@ def _ancestor_args(limit=4): return out -HOSTS = {"claude": ClaudeCode, "codex": Codex, "copilot": Copilot, "opencode": OpenCode, - "pi": Pi, "cursor": Cursor, "hermes": Hermes, "grok": Grok, +_DROID_SHELL = {"execute", "script"} +_DROID_EDIT = {"edit", "multiedit", "str_replace"} +_DROID_CREATE = {"create", "write"} + + +class Droid(Host): + """Factory Droid, through `plugin/.factory-plugin/` and its `hooks/hooks.json`. + + Droid runs the Claude-shaped hook contract (`session_id`, `transcript_path`, `cwd`, + `hook_event_name`) with its own tool names, and documents the same context channels: + `hookSpecificOutput.additionalContext` from SessionStart, `additionalContext` from + UserPromptSubmit and PostToolUse. It documents no `systemMessage` and no + `PostToolUseFailure`: a failed tool is a `tool_result.is_error` block in the session log, + and a hook message is only visible in Droid's detailed transcript view. Notices therefore + go through the model (`relays_notices`), never into the person's context as plugin chatter. + + The session log is `~/.factory/sessions//.jsonl`; its blocks are + Claude Code's, so `trace.droid_session_to_claude` unwraps the message records and the + existing readers take it from there. Usage lives beside it in `.settings.json` + (`trace.droid_session_usage`), so a folded session is priced like any other. + + The TUI has no persistent per-tool setting (`droid exec --only-tools` has no interactive + equivalent; Factory issue #65), so tool pruning is not available here: `denylist.supports` + says so and the controller writes nothing. + """ + name = "droid" + # Droid documents no interrupt key beyond its own UI; this is the generic instruction. + interrupt = "Interrupt the agent to stop it." + prompt_context = True # documented: UserPromptSubmit additionalContext + relays_notices = True + keeps_history = True + + def notice(self, text): + # No `systemMessage` in Droid's contract; stdout of a hook is only in the detailed + # transcript view. The controller relays an abort through the model when + # `relays_notices` is set, so this stays empty rather than adding plugin chatter. + return {} + + def env_session_id(self, env): + return str(env.get("TE_SESSION_ID") or env.get("FACTORY_SESSION_ID") or "") + + def tool_call(self, p): + name, args, text, code = super().tool_call(p) + low = name.lower() + if low in _DROID_SHELL: + cmd = args.get("command", args.get("script", "")) + return "bash", {"command": str(cmd or "")}, text, code + if low in _DROID_CREATE or low in _DROID_EDIT: + path = args.get("file_path") or args.get("path") or "" + return ("create" if low in _DROID_CREATE else "edit"), dict(args, path=path), text, code + if low in ("applypatch", "apply_patch"): + patch = next((v for v in (args.get("input"), args.get("patch"), args.get("command")) + if isinstance(v, str)), "") + paths = _PATCH_FILE_RE.findall(patch) + return "edit", {"path": paths[0] if paths else "", "paths": paths}, text, code + return name, args, text, code + + def headless(self, env, transcript=None): + # Droid does not publish a mode marker on the hook's environment; a TUI session is the + # default, and the wrong guess only changes the wording of an abort notice. + return False + + def mechanism_trace(self, transcript_path, workdir): + out = os.path.join(workdir, "droid_trace.jsonl") + n = trace.droid_session_to_claude(transcript_path, out) + return out if n is not None else None + + def session_usage(self, transcript_path): + return trace.droid_session_usage(transcript_path) + + def prompt_count(self, transcript_path): + return trace.droid_prompt_count(transcript_path) + + # -- the history import -------------------------------------------------------------- + def history(self, env, extra_dirs=()): + """Every top-level session under `$DROID_SESSIONS_DIR` (else `~/.factory/sessions`), + newest last. Subagent sessions are left out: they carry `callingSessionId` and are part + of the session that launched them.""" + rows = [] + for row in trace.droid_sessions(None, env): + if row.get("parent"): + continue + rows.append({"session_id": row["id"], "folder": row.get("folder"), + "path": row["path"], "mtime": row["mtime"], "size": row["size"]}) + return rows + + def log_head(self, path): + return trace.droid_log_head(path) + + def safe_session_id(self, sid): + return trace.droid_safe_session_id(sid) + + def prompt_turns(self, path): + return trace.droid_prompt_turns(path) + + def folder_matches(self, root, folder): + # Droid files a session under its workspace path with every separator written as `-`: + # `/Users/me/repo` becomes `-Users-me-repo`. Only asked when the recorded cwd is gone. + return folder == os.path.abspath(root).replace("\\", "-").replace("/", "-") + + +HOSTS = {"claude": ClaudeCode, "codex": Codex, "copilot": Copilot, "droid": Droid, + "opencode": OpenCode, "pi": Pi, "cursor": Cursor, "hermes": Hermes, "grok": Grok, "antigravity": Antigravity} @@ -1212,6 +1338,10 @@ def default_host(env=None, recent=None): return "cursor" if env.get("GROK_SESSION_ID"): return "grok" + # Droid marks its shell with the session it runs; checked last, so an agent started from + # inside Droid is read as its own host. + if env.get("FACTORY_SESSION_ID") or env.get("DROID_PLUGIN_ROOT"): + return "droid" return recent if recent in HOSTS else "claude" @@ -1237,6 +1367,11 @@ def detect(payload, env=None, hint=None): return Codex() if "/session-state/" in sp and tp.endswith("events.jsonl"): return Copilot() + # Droid's sessions live under `.factory/sessions//.jsonl`; its plugin hooks + # also mark the environment. The transcript test comes first, so a Droid session started + # from inside another agent is still Droid's. + if "/.factory/sessions/" in sp or (not tp and (env or {}).get("DROID_PLUGIN_ROOT")): + return Droid() # Claude Code always sends a transcript path; Copilot sends none before Stop, and marks its # hook processes. (Hooks inherit the parent's environment, so the marker alone would also # tag a Claude Code session started from inside Copilot -- hence the transcript test first.) diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/judge.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/judge.py index d4bd411..24b841d 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/judge.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/judge.py @@ -67,19 +67,35 @@ def run_job(ctx, session_id, job_id): req = ctx.store.read(REQUEST.format(sid=session_id)) or {} if req.get("id") != job_id: # superseded by a newer request return None - runner = (None if sidecall.paused(ctx.host.name, ctx.root) - else sidecall.runner_for(ctx.host.name, ctx.config)) + paused = sidecall.paused(ctx.host.name, ctx.root) + # Each call asks for its own runner: `local_roles` may put the judge on-device and leave + # the redirect on the agent's CLI, or the other way round. A paused host's CLI is skipped, + # but a local runner (which needs no login) still answers. + runner = sidecall.runner_for(ctx.host.name, ctx.config, role="judge") if not paused \ + else sidecall.local_runner("judge", ctx.config) + writer = sidecall.runner_for(ctx.host.name, ctx.config, role="nudge") if not paused \ + else sidecall.local_runner("nudge", ctx.config) verdict, written = None, None if runner is not None: try: verdict = loop_judge.llm_stuck_judge(req.get("digest") or "", runner, model="agent") except Exception: verdict = None + if verdict and getattr(runner, "answered_locally", False): + # The local model's confidences are coarse and high: a stuck verdict counts only at + # its own calibrated floor (`local_judge_confidence`); below it the turn is spared. + verdict["local"] = getattr(runner, "local", "local") + floor = float(getattr(ctx.config, "local_judge_confidence", 0.9) or 0) + if verdict.get("stuck") and float(verdict.get("confidence") or 0) < floor: + verdict["stuck"] = False + verdict["reason"] = ("below local_judge_confidence: " + + str(verdict.get("reason") or ""))[:160] conf = float((verdict or {}).get("confidence") or 0) if verdict and verdict.get("stuck") and conf >= float(req.get("threshold") or 0): try: - written = loop_judge.llm_nudge_writer(req.get("digest") or "", runner, - model="agent") + written = (loop_judge.llm_nudge_writer(req.get("digest") or "", writer, + model="agent") + if writer is not None else None) except Exception: written = None if written and (written.get("text") or "").strip(): diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py index d52ae56..5b0b8e4 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py @@ -53,15 +53,16 @@ def launcher_path(env=None): def ensure_launcher(env=None): - """Keep `/bin/te` pointing at this plugin's `te`. Returns its path, or None. + """Keep `bin/te` and Windows launch information pointing at this plugin. Returns te or None. A slash command has to name the CLI's path. Claude Code substitutes `${CLAUDE_PLUGIN_ROOT}` into a command's text; the Copilot CLI substitutes nothing but `$ARGUMENTS` (1.0.83: `${CLAUDE_PLUGIN_ROOT}`, `${PLUGIN_ROOT}`, `${COPILOT_PLUGIN_ROOT}`, `{{plugin_root}}` all - arrive literally), and its shell exports none of them. So every hook session start writes - this one-line launcher, the commands fall back to it, and a person on any host has a stable - `te` to run. The plugin's location comes from the bootstrap (`TE_PLUGIN_ROOT`); the file is - rewritten only when it changes, as an installed copy's path does across updates.""" + arrive literally), and its shell exports none of them. Session-start and prompt hooks keep + these launchers current, including in sessions already open when the plugin was updated. + The commands fall back to them, and a person on any host has a stable `te` to run. The plugin's + location comes from the bootstrap (`TE_PLUGIN_ROOT`); each file is rewritten only when it + changes, as an installed copy's path does across updates.""" import shlex env = os.environ if env is None else env plugin = env.get("TE_PLUGIN_ROOT") @@ -71,18 +72,27 @@ def ensure_launcher(env=None): path = launcher_path(env) body = ("#!/bin/sh\n# Written by the TokenEconomizer plugin at session start: its `te` " "command line.\nexec %s \"$@\"\n" % shlex.quote(target)) - try: - with open(path, encoding="utf-8") as fh: - if fh.read() == body: - return path - except OSError: - pass - os.makedirs(os.path.dirname(path), exist_ok=True) - tmp = "%s.%d.tmp" % (path, os.getpid()) - with open(tmp, "w", encoding="utf-8") as fh: - fh.write(body) - os.chmod(tmp, 0o700) - os.replace(tmp, path) + launchers = {path: body} + if os.name == "nt": + import json + import sys + launchers[path + ".json"] = json.dumps({ + "python": sys.executable, + "bootstrap": os.path.join(plugin, "scripts", "te_bootstrap.py"), + }) + "\n" + for launcher, body in launchers.items(): + try: + with open(launcher, encoding="utf-8") as fh: + if fh.read() == body: + continue + except OSError: + pass + os.makedirs(os.path.dirname(launcher), exist_ok=True) + tmp = "%s.%d.tmp" % (launcher, os.getpid()) + with open(tmp, "w", encoding="utf-8") as fh: + fh.write(body) + os.chmod(tmp, 0o700) + os.replace(tmp, launcher) return path @@ -190,10 +200,14 @@ def origin_url(root): def normalize_remote(url): """`git@github.com:Owner/Repo.git` and `https://github.com/owner/repo` -> one spelling.""" u = (url or "").strip() - u = re.sub(r"^[a-z+]+://", "", u) # scheme + scheme = re.match(r"^[a-z+]+://", u) + u = u[scheme.end():] if scheme else u # scheme u = re.sub(r"^[^@/]+@", "", u) # user@ u = re.sub(r"/+", "/", u.replace("\\", "/")) # local Windows remotes, including git's escaped slashes - u = u.replace(":", "/", 1) if not re.match(r"^[a-zA-Z]:/", u) and re.match(r"^[^/]+:[^/\d]", u) else u + # `host:port/...` only after a scheme; in git's scp form (`host:owner/repo`) the path may + # start with a digit (`git@github.com:42wim/repo.git`). + sep = r"^[^/]+:[^/\d]" if scheme else r"^[^/]+:[^/]" + u = u.replace(":", "/", 1) if not re.match(r"^[a-zA-Z]:/", u) and re.match(sep, u) else u u = re.sub(r"\.git$", "", u.rstrip("/")) return u.lower() diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/probe.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/probe.py index 588a061..4f8bf12 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/probe.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/probe.py @@ -128,10 +128,12 @@ def run_session(repo, env, plugin, model, cli="copilot", timeout=600): ev = json.loads(line) except ValueError: continue + if not isinstance(ev, dict): + continue if ev.get("type") == "result": sid = ev.get("sessionId") elif ev.get("type") == "assistant.message": - answer = (ev.get("data") or {}).get("content") or answer + answer = sidecall._obj(ev.get("data")).get("content") or answer return sid, answer.strip(), error[0] @@ -146,7 +148,12 @@ def inspect_session(sid): tests, tried_pytest = test_commands(cmds) for line in open(log, encoding="utf-8", errors="replace"): if '"hook.end"' in line and '"sessionStart"' in line: - out = (json.loads(line).get("data") or {}).get("output") or {} + try: + ev = json.loads(line) + except ValueError: + continue + data = sidecall._obj(ev.get("data")) if isinstance(ev, dict) else {} + out = sidecall._obj(data.get("output")) injected = injected or "fails here" in (out.get("additionalContext") or "") usage = trace.copilot_session_usage(log) first = tests[0] if tests else None diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py index dc617a2..3589b30 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py @@ -44,6 +44,12 @@ the person's default model. Never `hermes -z`, which auto-approves dangerous commands: a side call's prompt holds text a repository controls, and this form offers it no tool. See `hermes_call` for why `TE_SIDECALL` is not how it avoids the plugin's hooks. + * Factory Droid: `droid exec --output-format json --disable-builtin-skills --only-tools Read`, + in a throwaway directory at Droid's default read-only autonomy, on the person's default + model, with only the read-only `Read` tool allowed. OFF unless `droid_sidecall` is on (or + `TE_DROID_SIDECALL=1`): Droid writes a session log of its own for the call, and cannot be + left with no tool at all. Its usage is read from the call's result or from the settings file + beside that log. Every side call but Hermes's runs with `TE_SIDECALL=1`, which the plugin's hook entry point treats as "do nothing": without it the nested agent would run this plugin's hooks and recurse. A call that @@ -58,11 +64,19 @@ import re import shutil import subprocess +import sys import tempfile from .. import trace from . import accounting + +def _obj(v): + """`v` when it is a dict, else {}: agent CLI output is not schema-bound, + so a nested non-object where an object is expected must be skipped, not + trusted (#182).""" + return v if isinstance(v, dict) else {} + TIMEOUT_S = 180 @@ -315,11 +329,13 @@ def codex_call(prompt, model="", cli="codex", timeout=TIMEOUT_S, effort=""): ev = json.loads(line) except ValueError: continue - item = ev.get("item") or {} + if not isinstance(ev, dict): + continue + item = _obj(ev.get("item")) if ev.get("type") == "item.completed" and item.get("type") == "agent_message": - text = ev["item"].get("text") or text + text = item.get("text") or text elif ev.get("type") == "turn.completed": - usage = ev.get("usage") or usage + usage = _obj(ev.get("usage")) or usage if not text: _no_reply("codex", out) eff = None @@ -726,8 +742,10 @@ def copilot_call(prompt, model="", cli="copilot", timeout=TIMEOUT_S): ev = json.loads(line) except ValueError: continue + if not isinstance(ev, dict): + continue if ev.get("type") == "assistant.message": - text = (ev.get("data") or {}).get("content") or text + text = _obj(ev.get("data")).get("content") or text elif ev.get("type") == "result": sid = ev.get("sessionId") or sid if not text: @@ -745,9 +763,218 @@ def copilot_call(prompt, model="", cli="copilot", timeout=TIMEOUT_S): # Hosts the plugin makes no model call for: their CLI cannot run a prompt with every tool off. NO_SIDE_CALLS = frozenset({"antigravity"}) + +# ---- an on-device model for some side calls (`local_model`, `local_roles`) ------------------- +# Apple's Foundation Models CLI, `/usr/bin/fm` on macOS 27 with Apple Intelligence on. It runs a +# ~3B model on the Neural Engine and GPU with a 4,096-token window, needs no login or key, and +# takes the prompt on stdin. `--schema` constrains its decoding to a JSON schema, which is what +# makes the judge usable: in free text it often wraps or contradicts its verdict, under a schema +# it returns the object every time. A call it cannot make returns None, and the caller falls back +# to the agent's own CLI, so turning this on never costs a verdict. + +# Apple's Foundation Models CLI: macOS 27 ships it here, so it is run by this path, never looked +# up on PATH, and only on macOS. +FM_CLI = "/usr/bin/fm" +FM_TIMEOUT_S = 60 +# The judge's verdict, as `loopguard.judge.llm_stuck_judge` parses it. +JUDGE_SCHEMA = { + "title": "Verdict", "type": "object", "additionalProperties": False, + "x-order": ["stuck", "confidence", "reason"], "required": ["stuck", "confidence", "reason"], + "properties": { + "stuck": {"type": "boolean"}, + "confidence": {"type": "number", "description": "0.0 to 1.0"}, + "reason": {"type": "string", "description": "short leakage-safe justification"}}} +ROLE_SCHEMAS = {"judge": JUDGE_SCHEMA} +_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") +_fm_ok = {} + + +def _macos(): + return sys.platform == "darwin" + + +def local_routes(role, config): + """Whether `local_model` sends `role`'s side call on-device: the settings and the platform + alone, no subprocess, so a hook can ask on every tool call. Whether the model answers is + `fm_available`'s to say, in the judge's own job.""" + return (_macos() and getattr(config, "local_model", "off") == "fm" + and role in (getattr(config, "local_roles", None) or ())) + + +def fm_available(cli=FM_CLI): + """Whether `fm` is installed (macOS only) and reports its on-device model available (once + per process).""" + if cli not in _fm_ok: + ok = False + if _macos() and os.access(cli, os.X_OK): + try: + out = subprocess.run([cli, "available"], capture_output=True, encoding="utf-8", + errors="replace", timeout=30, env=_env(), + stdin=subprocess.DEVNULL) + ok = out.returncode == 0 and "unavailable" not in (out.stdout or "").lower() + except (OSError, subprocess.SubprocessError): + ok = False + _fm_ok[cli] = ok + return _fm_ok[cli] + + +def fm_call(prompt, schema=None, cli=FM_CLI, timeout=FM_TIMEOUT_S): + """(text, 0) from the on-device model, or (None, 0) when it gave no usable reply. Greedy + decoding, so the same digest gets the same verdict; `schema` (a JSON schema dict) constrains + the output. A prompt over the model's window fails here and falls back.""" + with tempfile.TemporaryDirectory(prefix="te-fm-", ignore_cleanup_errors=True) as tmp: + cmd = [cli, "respond", "--no-stream", "--greedy"] + if schema: + path = os.path.join(tmp, "schema.json") + with open(path, "w", encoding="utf-8") as fh: + json.dump(schema, fh) + cmd += ["--schema", path] + try: + out = subprocess.run(cmd, input=prompt, capture_output=True, encoding="utf-8", + errors="replace", timeout=timeout, env=_env(), cwd=tmp) + except (OSError, subprocess.SubprocessError) as e: + _log(f"sidecall fm: no reply ({type(e).__name__})\n") + return None, 0 + text = _ANSI_RE.sub("", out.stdout or "").strip() + if out.returncode != 0 or not text or text.startswith("Error:"): + err = _ANSI_RE.sub("", (out.stderr or out.stdout or "").strip())[:200] + _log(f"sidecall fm: no reply (exit {out.returncode}): {err}\n") + return None, 0 + return text, 0 + + +def local_runner(role, config, fallback=None): + """The side-call runner for `role` when `local_model` routes it on-device, else None. On a + failed local call the runner tries `fallback` (the agent's own runner), so a turned-on local + model never loses a verdict; with no fallback (a host in `NO_SIDE_CALLS`) it returns ''.""" + if not local_routes(role, config) or not fm_available(): + return None + schema = ROLE_SCHEMAS.get(role) + + def run(prompt, model="agent"): + text, eff = fm_call(prompt, schema=schema) + run.answered_locally = text is not None + if text is not None: + return text, eff + return fallback(prompt, model) if fallback is not None else ("", 0) + run.local = "fm" + run.answered_locally = False + return run + + +def droid_enabled(env=None): + """Whether `TE_DROID_SIDECALL` allows Droid side calls. The `droid_sidecall` setting does + the same from the config file, which is the only way from the desktop app. They are OFF by + default: `droid exec` writes a session log of its own under `~/.factory/sessions`, so a + person enables them knowingly.""" + env = os.environ if env is None else env + return str(env.get("TE_DROID_SIDECALL") or "").strip().lower() in ("1", "true", "yes", "on") + + +def _droid_sessions_root(): + return os.environ.get("DROID_SESSIONS_DIR") or os.path.join( + os.path.expanduser("~"), ".factory", "sessions") + + +def _droid_usage(d): + """A Droid usage object (camelCase from its settings, snake_case from `exec`) as the + breakdown `accounting.effective` reads.""" + if not isinstance(d, dict): + return None + + def key(camel, snake): + return d.get(snake, d.get(camel)) + usage = {"input_tokens": key("inputTokens", "input_tokens"), + "cache_read_input_tokens": key("cacheReadTokens", "cache_read_input_tokens"), + "cache_creation_input_tokens": key("cacheCreationTokens", + "cache_creation_input_tokens"), + "output_tokens": key("outputTokens", "output_tokens"), + "model": d.get("model")} + return usage if usage["input_tokens"] is not None else None + + +def _droid_settings_usage(sid): + """The usage Droid wrote beside a side call's own session log, or None.""" + if not sid: + return None + root = _droid_sessions_root() + try: + folders = os.listdir(root) + except OSError: + return None + for folder in folders: + path = os.path.join(root, folder, f"{sid}.settings.json") + try: + with open(path, encoding="utf-8") as fh: + data = json.load(fh) + except (OSError, ValueError): + continue + return _droid_usage(dict(data.get("tokenUsage") or {}, model=data.get("model"))) + return None + + +# A Droid side call only answers, and its prompt quotes commands the session ran, so it must not +# be able to act. Droid's default read-only autonomy still lists `Execute`, the web tools and every +# MCP tool as allowed (0.233.0, `droid exec --list-tools`), so the call names its tools with +# `--only-tools`, an allowlist. It cannot be empty -- `--only-tools ""` reads as no filter, and a +# name droid does not know is refused -- so it keeps the one read-only tool, as Grok's does. +# Verified on 0.233.0: with the call's own flags, `--list-tools` reports `Read` as the only +# tool allowed, MCP tools included. +DROID_TOOLS = "Read" + + +def droid_call(prompt, model="", cli="droid", timeout=TIMEOUT_S): + """A text-only completion through `droid exec`, in a throwaway directory, with only the + read-only `Read` tool allowed (`--only-tools`, see `DROID_TOOLS`). + + Droid cannot be left with no tool at all, and `droid exec` writes a session log of its own, + so this is off unless the person turns it on (`droid_enabled`, or the `droid_sidecall` + setting). `TE_SIDECALL=1` makes this plugin's own hooks no-ops inside the nested session, so + a side call cannot recurse. Its own usage is read from the `exec` result or from the + settings file beside the session it wrote, so the call is charged rather than guessed.""" + cmd = [*program(cli), "exec", "--output-format", "json", "--disable-builtin-skills", + "--only-tools", DROID_TOOLS, "--append-system-prompt", + "Answer with text only. Do not call any tool. Your entire reply is the answer."] + if model: + cmd += ["--model", model] + cmd.append(prompt) + with tempfile.TemporaryDirectory(prefix="te-side-", ignore_cleanup_errors=True) as cwd: + out = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", + errors="replace", timeout=timeout, env=_env(), cwd=cwd, + stdin=subprocess.DEVNULL) + text, sid, usage = "", "", None + for line in (out.stdout or "").splitlines(): + try: + ev = json.loads(line) + except ValueError: + continue + if not isinstance(ev, dict): + continue + sid = ev.get("session_id") or sid + data = ev.get("data") if isinstance(ev.get("data"), dict) else {} + usage = _droid_usage(ev.get("usage")) or _droid_usage(data.get("usage")) or usage + for key in ("result", "text", "message"): + if isinstance(ev.get(key), str) and ev[key].strip(): + text = ev[key] + for key in ("content", "result", "text"): + if isinstance(data.get(key), str) and data[key].strip(): + text = data[key] + if not text and (out.stdout or "").strip(): + # `--output-format json` that answers plain text (an older build): take it as-is. + text = out.stdout.strip() + if not text: + _no_reply("droid", out) + eff = None + usage = usage or _droid_settings_usage(sid) + if usage: + usage.setdefault("model", model or None) + eff, _ = accounting.effective(usage) + return text, eff + + # The command each agent's side calls run, as the notices name it; the rest run ` -p`. -_CALLS = {"codex": "codex exec", "opencode": "opencode run", "cursor": "cursor-agent -p", - "hermes": "hermes chat"} +_CALLS = {"codex": "codex exec", "droid": "droid exec", "opencode": "opencode run", + "cursor": "cursor-agent -p", "hermes": "hermes chat"} def call_name(host_name): @@ -755,13 +982,22 @@ def call_name(host_name): return _CALLS.get(host_name, f"{host_name} -p") -def runner_for(host_name, config): +def runner_for(host_name, config, role=None): """The optimizer callable for this host. Each host's calls go through that host's own CLI, never another agent's. The caller decides whether a call is allowed: micro-skills' proposer when micro-skills is on, the loop guard's judge when the guard is. None for a host in - `NO_SIDE_CALLS`. A call that raises is noted in errors.log (`_noted`).""" + `NO_SIDE_CALLS`. A call that raises is noted in errors.log (`_noted`). + + `role` (`judge`, `nudge`, `proposer`) lets `local_model` run that call on-device instead + (`local_runner`), falling back to the host's CLI when the local call fails; on a host in + `NO_SIDE_CALLS` the local model is the only runner.""" call = _host_call(host_name, config) - return None if call is None else _noted(host_name, call) + host = None if call is None else _noted(host_name, call) + if role is not None: + local = local_runner(role, config, fallback=host) + if local is not None: + return local + return host def _host_call(host_name, config): @@ -788,4 +1024,11 @@ def _host_call(host_name, config): return lambda prompt, _m="agent": codex_call(prompt, model=model, **kw) if host_name == "copilot": return lambda prompt, _m="agent": copilot_call(prompt, model=model) + if host_name == "droid": + # Off unless the person turned it on, by the setting or the variable: see + # `droid_enabled`. No runner means the free layer still learns; only the paid proposer + # and the judge wait. + if not (droid_enabled() or getattr(config, "droid_sidecall", False)): + return None + return lambda prompt, _m="agent": droid_call(prompt, model=model) return lambda prompt, _m="agent": claude_call(prompt, model=model or "haiku", **kw) diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/store.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/store.py index d0052cc..acd3ba0 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/store.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/store.py @@ -112,15 +112,17 @@ def append(self, name, record): fh.write(json.dumps(record, sort_keys=True) + "\n") def read_lines(self, name, limit=None): - """Records of a JSONL log, oldest first; the last `limit` when given.""" + """Object records of a JSONL log, oldest first; the last `limit` when given.""" out = [] try: with open(self.path(name), encoding="utf-8") as fh: for line in fh: try: - out.append(json.loads(line)) + rec = json.loads(line) except ValueError: continue + if isinstance(rec, dict): + out.append(rec) except OSError: return [] return out[-limit:] if limit else out diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/toolcheck.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/toolcheck.py index cc7f458..a4d0d83 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/toolcheck.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/toolcheck.py @@ -78,6 +78,8 @@ def _init_tools(extra_args, cli=None, timeout=60): ev = json.loads(line) except ValueError: continue + if not isinstance(ev, dict): + continue if ev.get("type") == "system" and ev.get("subtype") == "init": tools, version = ev.get("tools"), ev.get("claude_code_version") break diff --git a/plugins/tokeneconomizer/tokeneconomizer/pricing.py b/plugins/tokeneconomizer/tokeneconomizer/pricing.py index b188cab..09ebff0 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/pricing.py +++ b/plugins/tokeneconomizer/tokeneconomizer/pricing.py @@ -31,10 +31,16 @@ `cache_write_1h`; a table without that entry, or a row without the field, prices every cache-write token at `cache_write` as before. +Claude's cache-hit price is not uniform either: Anthropic bills a cache hit at 0.1x input, but at +0.05x on Opus 5.5 and Sonnet 5.5 and at 0.025x on Fable and Mythos 5.1 and 5.2 +(`_CLAUDE_CACHE_READ`). Cache hits are 90% or more of an agent session's tokens, so a wrong ratio +moves the whole figure. + Callers may override with an explicit effective_tokens(rec, weights=...). When the per-task breakdown is absent (older runs), effective_tokens() falls back to `tokens_total` at full weight so nothing crashes — call has_breakdown() to detect this. """ +import re # --------------------------------------------------------------------------- # Per-model-id price ratios (fresh-input-token equivalents; input := 1.0). @@ -92,14 +98,33 @@ "gpt-5.2-codex": dict(input=1.0, cache_read=0.10, cache_write=1.0, output=8.0), # codex-mini-latest: $1.50 in / $0.375 cached / $6.00 out => cr 0.25, out 4.0 "codex-mini-latest": dict(input=1.0, cache_read=0.25, cache_write=1.0, output=4.0), + # --- added 2026-11-13 from the vendors' Standard-tier price pages (short context) ------ + # OpenAI, https://developers.openai.com/api/docs/pricing. A cache write costs 1.25x input + # for the 30-minute cache and 2.5x for the 12-hour one; a Codex rollout does not say which + # lifetime a write used, so the 30-minute rate stands. gpt-6.1-sol and gpt-6.1-terra bill a + # cache hit at 0.05x input: $2.00 in / $0.10 cached / $10 out, and $1.00 / $0.05 / $5. + "gpt-6-astra": dict(input=1.0, cache_read=0.10, cache_write=1.25, output=5.0), + "gpt-6-luna": dict(input=1.0, cache_read=0.10, cache_write=1.25, output=5.0), + "gpt-6-sol": dict(input=1.0, cache_read=0.10, cache_write=1.25, output=5.0), + "gpt-6.1-sol": dict(input=1.0, cache_read=0.05, cache_write=1.25, output=5.0), + "gpt-6.1-terra": dict(input=1.0, cache_read=0.05, cache_write=1.25, output=5.0), + # Google, https://aistudio.google.com/docs/pricing. No cache-write charge. Gemini 4 bills a + # cache hit at 0.05x input ($2.00 in / $0.10 cached / $10 out for argon and carbon). The + # gemini-4-* prices rise on 2026-12-01 and gemini-3.8-flash's on 2027-01-01; the ratios stay. + "gemini-3.1-flash-lite": dict(input=1.0, cache_read=0.10, cache_write=0.0, output=6.0), + "gemini-3.5-flash-lite": dict(input=1.0, cache_read=0.10, cache_write=0.0, output=8.333), + "gemini-3.8-flash": dict(input=1.0, cache_read=0.10, cache_write=0.0, output=5.0), + "gemini-4-argon": dict(input=1.0, cache_read=0.05, cache_write=0.0, output=5.0), + "gemini-4-carbon": dict(input=1.0, cache_read=0.05, cache_write=0.0, output=5.0), + "gemini-4-hydrogen": dict(input=1.0, cache_read=0.05, cache_write=0.0, output=5.0), } # Billed model id for an agent when a row does NOT pin one (rec['model'] is None). -# Claude/Copilot agents map to None -> the Claude curve (their ratios are model-uniform -# across Opus/Sonnet/Haiku, so an exact id is unnecessary). Codex maps to codex's built-in -# default, gpt-5.6-sol (verified from codex's session rollout). Probed against the OpenAI -# Platform on 2026-09-09: `gpt-5.6-sol` is both listed by /v1/models AND accepted by -# /v1/responses (HTTP 200). +# Claude/Copilot agents map to None -> the Claude curve (a row that names its Claude model is +# priced by it, see _CLAUDE_CACHE_READ; one that names none gets the usual ratios). Codex maps +# to codex's built-in default, gpt-5.6-sol (verified from codex's session rollout). Probed +# against the OpenAI Platform on 2026-09-09: `gpt-5.6-sol` is both listed by /v1/models AND +# accepted by /v1/responses (HTTP 200). # # The trap a catalog check alone will not catch: the `-codex` ALIASES are listed by # /v1/models and 404 on /v1/responses ("does not exist or you do not have access to it" for @@ -109,9 +134,10 @@ "codex": "gpt-5.6-sol", } -# Claude-family price ratios (Opus/Sonnet/Haiku share them). Used as the default when a -# row has no resolvable model id (legacy rows, claude/copilot agents) so those stay -# byte-identical to historical behavior. Also the value of the back-compat WEIGHTS alias. +# Claude-family price ratios (Opus/Sonnet/Haiku share them, except the cache-hit ratio of a +# few models: see _CLAUDE_CACHE_READ). Used as the default when a row has no resolvable model +# id (legacy rows, claude/copilot agents) so those stay byte-identical to historical behavior. +# Also the value of the back-compat WEIGHTS alias. WEIGHTS_CLAUDE = { "input": 1.0, # input_tokens = fresh/uncached prompt tokens "cache_read": 0.10, # cache_read_input_tokens @@ -124,6 +150,24 @@ # weights_for(); effective_tokens() applies it automatically. WEIGHTS = WEIGHTS_CLAUDE +# Claude models whose cache hits are not billed at 0.1x input (Anthropic's price list, +# https://platform.claude.com/docs/en/about-claude/pricing). Every other ratio of the Claude +# curve is the same on every model. Matched on the id with dots as dashes, so a router's +# `claude-sonnet-5.5` and a dated snapshot match too. +_CLAUDE_CACHE_READ = ( + (re.compile(r"claude-(opus|sonnet)-5-5\b"), 0.05), + (re.compile(r"claude-(fable|mythos)-5-[12]\b"), 0.025), +) + + +def _claude_weights(key): + """The Claude curve for a lower-cased claude-* id, with the model's own cache-hit ratio.""" + name = key.replace(".", "-") + for pattern, cache_read in _CLAUDE_CACHE_READ: + if pattern.search(name): + return dict(WEIGHTS_CLAUDE, cache_read=cache_read) + return WEIGHTS_CLAUDE + def resolve_model(rec): """The billed model id for a row: its explicit `model`, else the agent's default @@ -151,7 +195,8 @@ def weights_for(rec): * resolve the billed id (resolve_model) — explicit `model`, else agent default; * id in MODEL_WEIGHTS -> that model's exact ratios; * id is a claude-* variant -> Claude curve (covers dotted ids like claude-opus-4.8 - not in the catalog snapshot; ratios are uniform); + not in the catalog snapshot), with the model's own + cache-hit ratio where it differs (_CLAUDE_CACHE_READ); * id present but UNPRICED -> raise ValueError (hard-fail: a new/unknown model must be added to MODEL_WEIGHTS, never silently mispriced); * no resolvable id at all -> Claude curve (legacy rows / claude / copilot: keeps @@ -165,7 +210,7 @@ def weights_for(rec): if key in MODEL_WEIGHTS: return MODEL_WEIGHTS[key] if "claude" in key: - return WEIGHTS_CLAUDE + return _claude_weights(key) raise ValueError( f"pricing: no weight entry for billed model {mid!r} " f"(agent={rec.get('agent')!r}). Add it to pricing.MODEL_WEIGHTS " diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/README.md b/plugins/tokeneconomizer/tokeneconomizer/trace/README.md index b335c69..adc6f14 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/README.md +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/README.md @@ -13,6 +13,7 @@ session as an ordered list of `(tool_name, args, result_text, success)` calls th | `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 | +| `droid.py` | Factory Droid sessions: one JSONL file per session, its message records unwrapped into a Claude transcript; prompts; usage from the `.settings.json` beside it | | `grok.py` | Grok Build sessions: `updates.jsonl` (ACP updates) written as a Claude transcript; prompts and usage from its session files | | `hermes.py` | Hermes Agent sessions: a copy of a session's `state.db` rows without the conversation's words, written as a Claude transcript; usage | | `pi.py` | Pi's session tree: the active branch, written as a Claude transcript; usage | diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py b/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py index b5c380a..f9d0de0 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py @@ -6,9 +6,9 @@ * `calls` -- `load_trajectory`: any agent's log as ordered `(name, args, result, ok)` calls; `call_cwds`, `tool_usage`, `strip_rtk_prefix`; * `catalog` -- the tool list a session loaded, from whichever source the agent publishes; - * `antigravity`, `claude`, `codex`, `copilot`, `grok`, `hermes`, `opencode`, `pi` -- each agent's - own session file: usage, metadata, prompt-turns, and the conversions that let - the readers above handle it. + * `antigravity`, `claude`, `codex`, `copilot`, `cursor`, `droid`, `grok`, `hermes`, + `opencode`, `pi` -- each agent's own session file: usage, metadata, + prompt-turns, and the conversions that let the readers above handle it. Stdlib only. """ @@ -30,6 +30,9 @@ from .antigravity import (antigravity_prompt_count, antigravity_read, antigravity_session_to_claude, antigravity_session_usage) from .cursor import cursor_events_to_claude, cursor_prompt_count +from .droid import (droid_log_head, droid_prompt_count, droid_prompt_turns, + droid_safe_session_id, droid_session_header, droid_session_to_claude, + droid_session_usage, droid_sessions) from .grok import (grok_json_reply, grok_prompt_count, grok_result, grok_session_to_claude, grok_session_usage, grok_tool) from .hermes import (hermes_export, hermes_find_session, hermes_prompt_count, hermes_result, @@ -56,6 +59,8 @@ "antigravity_prompt_count", "antigravity_read", "antigravity_session_to_claude", "antigravity_session_usage", "cursor_events_to_claude", "cursor_prompt_count", + "droid_log_head", "droid_prompt_count", "droid_prompt_turns", "droid_safe_session_id", + "droid_session_header", "droid_session_to_claude", "droid_session_usage", "droid_sessions", "grok_json_reply", "grok_prompt_count", "grok_result", "grok_session_to_claude", "grok_session_usage", "grok_tool", "hermes_export", "hermes_find_session", "hermes_prompt_count", "hermes_result", diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/antigravity.py b/plugins/tokeneconomizer/tokeneconomizer/trace/antigravity.py index e99b68e..6481b99 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/antigravity.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/antigravity.py @@ -43,7 +43,9 @@ "run_command": ("Bash", {"command": ("CommandLine",)}), "view_file": ("Read", {"file_path": _FILE}), "read_file": ("Read", {"file_path": _FILE}), + "write_file": ("Write", {"file_path": _FILE}), "write_to_file": ("Write", {"file_path": _FILE}), + "edit_file": ("Edit", {"file_path": _FILE}), "replace_file_content": ("Edit", {"file_path": _FILE}), "multi_replace_file_content": ("Edit", {"file_path": _FILE}), "sed_file": ("Edit", {"file_path": _FILE}), diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/claude.py b/plugins/tokeneconomizer/tokeneconomizer/trace/claude.py index 04f7bb0..ea79b13 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/claude.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/claude.py @@ -88,15 +88,23 @@ def _is_prompt(ev): "[Request interrupted")) +def _is_notification(ev): + """Is this entry Claude Code telling the model that a background task finished? It starts a + turn, as a prompt does, but nobody typed it (2.1.317: `origin.kind` "task-notification").""" + origin = ev.get("origin") + return isinstance(origin, dict) and origin.get("kind") == "task-notification" + + def claude_prompt_count(transcript_path): - """How many prompts the person gave a Claude Code session (`_is_prompt`).""" + """How many prompts the person gave a Claude Code session (`_is_prompt`, less the + background-task notifications).""" n = 0 for line in _lines(transcript_path): try: ev = json.loads(line) except ValueError: continue - n += isinstance(ev, dict) and _is_prompt(ev) + n += isinstance(ev, dict) and _is_prompt(ev) and not _is_notification(ev) return n diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/cursor.py b/plugins/tokeneconomizer/tokeneconomizer/trace/cursor.py index 5be6ed9..5f2c326 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/cursor.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/cursor.py @@ -44,6 +44,8 @@ def cursor_events_to_claude(path, out_path): event = json.loads(line) except ValueError: continue + if not isinstance(event, dict): + continue name = event.get("hook_event_name") if name == "UserPromptSubmit": prompt = event.get("prompt") @@ -93,6 +95,8 @@ def cursor_prompt_count(path): event = json.loads(line) except ValueError: continue + if not isinstance(event, dict): + continue count += event.get("hook_event_name") == "UserPromptSubmit" if isinstance(event.get("agent_transcript"), str): agent = event["agent_transcript"] diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/droid.py b/plugins/tokeneconomizer/tokeneconomizer/trace/droid.py new file mode 100644 index 0000000..3160c34 --- /dev/null +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/droid.py @@ -0,0 +1,340 @@ +"""Factory Droid: a session stored as one JSONL file under `~/.factory/sessions/`. + +Each line is a record with a `type`: + + * `session_start` -- the header: `id`, `cwd`, `version`, `title`, `owner`. This is the only + place a session says which repository it belongs to. + * `message` -- one message under `message`: `role`, `content` (the Claude Code block + list: `text`, `thinking`, `tool_use`, `tool_result`), `modelId`. Tool calls carry + `{type, id, name, input}`; results carry `{type, tool_use_id, is_error, content}`. + * `agent_turn_outcome`, `todo_state`, `compaction_state` -- bookkeeping, ignored here. + +The format is close enough to a Claude Code transcript that a session is read by unwrapping +each `message` record into a `{"type": role, "message": ...}` line, which the readers already +handle; `droid_session_to_claude` writes that file. + +Usage is not in the transcript. Droid keeps it beside the log, in `.settings.json`: +`tokenUsage` is this session's own breakdown (`inputTokens`, `outputTokens`, +`cacheCreationTokens`, `cacheReadTokens`, `thinkingTokens`, `factoryCredits`), and +`inclusiveTokenUsage` adds child sessions, which are folded separately -- so only `tokenUsage` +is read here, never the inclusive figure. A prompt is a `user` message that is neither an +injected system reminder nor a tool result; Droid marks messages it never shows the person with +`visibility: "user_only"` or `"llm_only"`, and those are not prompts either. +""" +import json +import os +import re +from datetime import datetime + +SYSTEM_PREFIXES = (".json`), so a log's id is taken +# only when it is a plain token: Droid's are UUIDs. +SESSION_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,127}") + + +def claude_tool_name(name): + """A Droid tool name as the equivalent Claude Code one, or unchanged.""" + return _TOOL_NAMES.get((name or "").lower(), name) + + +def droid_records(path): + """The parsed records of a Droid session, in file order (which is `seq` order).""" + out = [] + try: + with open(path, encoding="utf-8", errors="replace") as fh: + for line in fh: + line = line.strip() + if not line: + continue + try: + ev = json.loads(line) + except ValueError: + continue + if isinstance(ev, dict): + out.append(ev) + except OSError: + return [] + return out + + +def _epoch(ts): + """Droid's ISO timestamp as epoch seconds, or None.""" + if not isinstance(ts, str) or not ts: + return None + try: + return datetime.fromisoformat(ts[:-1] + "+00:00" if ts.endswith("Z") else ts).timestamp() + except (ValueError, OverflowError, OSError): + return None + + +def droid_session_header(path): + """The `session_start` record ({id, cwd, version, title, ...}), {} if absent.""" + for ev in droid_records(path): + if ev.get("type") == "session_start": + return ev + return {} + + +def droid_session_cwd(path): + """The directory the session started in, or None.""" + cwd = droid_session_header(path).get("cwd") + return cwd if isinstance(cwd, str) and cwd else None + + +def droid_log_head(path): + """A session's `{cwd, started}` from its header and first message, {} if unreadable. + + `started` is its first timestamp in epoch seconds, as every other host's head reports it.""" + head, started = {}, None + for ev in droid_records(path): + if ev.get("type") == "session_start" and not head: + head = ev + elif ev.get("type") == "message" and started is None: + started = _epoch(ev.get("timestamp")) + if head and started is not None: + break + out = {} + if isinstance(head.get("cwd"), str) and head["cwd"]: + out["cwd"] = head["cwd"] + if started: + out["started"] = started + return out + + +def droid_safe_session_id(sid): + """A log's id when it is a plain token (safe as a file name), else None.""" + return sid if isinstance(sid, str) and SESSION_ID_RE.fullmatch(sid) else None + + +def _droid_is_prompt(msg): + """A message the person (or the agent that launched a task) typed, not injected text.""" + if (msg.get("role") or "") != "user": + return False + if msg.get("visibility") in NOT_PROMPTS: + return False + content = msg.get("content") + if isinstance(content, str): + return bool(content.strip()) and not content.lstrip().startswith(SYSTEM_PREFIXES) + if not isinstance(content, list): + return False + texts = [] + for block in content: + if not isinstance(block, dict): + continue + if block.get("type") == "tool_result": + return False # a tool result returned to the model + if block.get("type") == "text": + texts.append(block.get("text") or "") + return any(t.strip() and not t.lstrip().startswith(SYSTEM_PREFIXES) for t in texts) + + +def droid_prompt_count(path): + """How many prompts the session ran.""" + return sum(1 for ev in droid_records(path) + if ev.get("type") == "message" + and _droid_is_prompt(ev.get("message") or {})) + + +def _droid_content(content): + """A message's content as blocks: strings become one text block.""" + if isinstance(content, list): + return [b for b in content if isinstance(b, dict)] + if isinstance(content, str) and content: + return [{"type": "text", "text": content}] + return [] + + +def _claude_line(ev, cwd=None): + """One Droid `message` record as the line `load_trajectory` reads, or None.""" + msg = ev.get("message") or {} + role = msg.get("role") + if role not in ("user", "assistant"): + return None + content = _droid_content(msg.get("content")) + if not content: + return None + content = [dict(b, name=claude_tool_name(b.get("name"))) + if b.get("type") == "tool_use" else b for b in content] + record = {"type": role, "message": {"role": role, "content": content}} + if msg.get("modelId"): + record["message"]["model"] = msg["modelId"] + if cwd: + record["cwd"] = cwd + return record + + +def droid_session_to_claude(path, out_path): + """Write a Droid session as Claude Code transcript lines, for `load_trajectory`. + + Every line carries the session's `cwd` (Droid records no per-call directory): a command + typed as `cd sub && make` is still read from where the session started. Returns the number + of tool calls written, or None when the file is missing.""" + if not path or not os.path.exists(path): + return None + cwd = droid_session_cwd(path) + n = 0 + with open(out_path, "w", encoding="utf-8") as out: + for ev in droid_records(path): + if ev.get("type") != "message": + continue + record = _claude_line(ev, cwd) + if record is None: + continue + n += sum(1 for b in record["message"]["content"] if b.get("type") == "tool_use") + out.write(json.dumps(record) + "\n") + return n + + +def droid_prompt_turns(path): + """Each prompt-turn of a Droid session, as Claude Code log lines from its prompt to the + next, one turn at a time. Used to seed the loop guard's envelope from imported sessions.""" + cwd = droid_session_cwd(path) + current = None + for ev in droid_records(path): + if ev.get("type") != "message": + continue + record = _claude_line(ev, cwd) + if record is None: + continue + line = json.dumps(record) + if _droid_is_prompt(ev.get("message") or {}): + if current is not None: + yield current + current = [line] + elif current is not None: + current.append(line) + if current is not None: + yield current + + +def droid_settings_path(transcript_path): + """The settings file Droid keeps beside a session log, or None.""" + if not transcript_path: + return None + base = transcript_path[:-len(".jsonl")] if transcript_path.endswith(".jsonl") else \ + transcript_path + return base + ".settings.json" + + +def droid_session_usage(transcript_path): + """Token breakdown of a Droid session from the settings file beside its log. + + Returns the four fields `pricing.effective_tokens` reads, plus `model`, `requests` (assistant + messages in the log), and Droid's own `factory_credits`. Only this session's `tokenUsage` is + read: `inclusiveTokenUsage` also counts child sessions, which are folded on their own. + Without a breakdown every count is None, so the ledger says `no_usage` rather than guessing. + """ + out = {"input_tokens": None, "cache_read_input_tokens": None, + "cache_creation_input_tokens": None, "output_tokens": None, + "requests": 0, "model": None, "factory_credits": None} + settings = droid_settings_path(transcript_path) + data = {} + if settings: + try: + with open(settings, encoding="utf-8") as fh: + data = json.load(fh) + except (OSError, ValueError): + data = {} + if not isinstance(data, dict): + data = {} + out["model"] = data.get("model") if isinstance(data.get("model"), str) else None + + models, assistant = {}, 0 + for ev in droid_records(transcript_path): + if ev.get("type") != "message": + continue + msg = ev.get("message") or {} + if msg.get("role") != "assistant": + continue + assistant += 1 + mid = msg.get("modelId") + if isinstance(mid, str) and mid: + models[mid] = models.get(mid, 0) + 1 + out["requests"] = assistant + if not out["model"] and models: + out["model"] = max(models, key=models.get) + + usage = data.get("tokenUsage") + if not isinstance(usage, dict): + return out + + def _int(key): + v = usage.get(key) + return int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0 + + counts = {"input_tokens": _int("inputTokens"), + "cache_read_input_tokens": _int("cacheReadTokens"), + "cache_creation_input_tokens": _int("cacheCreationTokens"), + "output_tokens": _int("outputTokens")} + if not any(counts.values()): + return out + out.update(counts) + credits = usage.get("factoryCredits") + if isinstance(credits, (int, float)) and not isinstance(credits, bool): + out["factory_credits"] = credits + return out + + +def droid_sessions(sessions_root=None, env=None): + """Every `*.jsonl` session under the Droid sessions directory, newest mtime first. + + Each row is `{path, id, cwd, version, title, started, mtime, size}`; `started` is the first + message's timestamp in epoch seconds when it has one, else the file's mtime. + `$DROID_SESSIONS_DIR` overrides + the location (tests, or a non-default install).""" + env = os.environ if env is None else env + root = sessions_root or env.get("DROID_SESSIONS_DIR") or os.path.join( + os.path.expanduser("~"), ".factory", "sessions") + if not os.path.isdir(root): + return [] + rows = [] + for dirpath, dirnames, filenames in os.walk(root): + depth = os.path.relpath(dirpath, root).count(os.sep) + if depth > 1: # `/.jsonl`, no deeper + dirnames[:] = [] + continue + for fname in filenames: + if not fname.endswith(".jsonl"): + continue + path = os.path.join(dirpath, fname) + header, started = {}, None + try: + mtime = os.path.getmtime(path) + size = os.path.getsize(path) + with open(path, encoding="utf-8", errors="replace") as fh: + for line in fh: + try: + ev = json.loads(line) + except ValueError: + continue + if ev.get("type") == "session_start" and not header: + header = ev + elif ev.get("type") == "message" and started is None: + started = _epoch(ev.get("timestamp")) + if header and started is not None: + break + except OSError: + continue + rows.append({"path": path, "id": header.get("id") or os.path.splitext(fname)[0], + "cwd": header.get("cwd") if isinstance(header.get("cwd"), str) else None, + "version": header.get("version"), "title": header.get("title"), + # A subagent session names the session that launched it; it is part + # of that session's work, not a person's session of its own. + "parent": header.get("callingSessionId"), + "started": started, "mtime": mtime, "size": size, + "folder": os.path.basename(dirpath)}) + rows.sort(key=lambda r: (r["mtime"], r["path"])) + return rows diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/pi.py b/plugins/tokeneconomizer/tokeneconomizer/trace/pi.py index 0eb182e..ede32cd 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/pi.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/pi.py @@ -8,7 +8,7 @@ Usage, per pi-ai's own type: `input` excludes the cache fields, `output` already includes reasoning, and `cacheWrite1h` is a subset of `cacheWrite` -- so the mapping to the ledger's four -fields is direct. +fields is direct, and `cacheWrite1h` is their 1-hour share (`cache_creation_1h_input_tokens`). """ import json import os @@ -55,6 +55,7 @@ def _pi_usage(u): "cache_read_input_tokens": int(u.get("cacheRead") or 0), "cache_creation_input_tokens": int(u.get("cacheWrite") or 0), "output_tokens": int(u.get("output") or 0), + "cache_creation_1h_input_tokens": int(u.get("cacheWrite1h") or 0), "cost_usd": float((u.get("cost") or {}).get("total") or 0)} @@ -139,7 +140,8 @@ def pi_json_reply(stdout): def pi_session_usage(path): """Token breakdown of a Pi session's active branch, plus Pi's own cost estimate.""" totals = {"input_tokens": 0, "cache_read_input_tokens": 0, - "cache_creation_input_tokens": 0, "output_tokens": 0} + "cache_creation_input_tokens": 0, "output_tokens": 0, + "cache_creation_1h_input_tokens": 0} cost, requests, models = 0.0, 0, {} for e in pi_active_branch(_pi_entries(path)): u = None