diff --git a/.github/upstream-state/tokeneconomizer/tokeneconomizer b/.github/upstream-state/tokeneconomizer/tokeneconomizer index 2d522d5..b87e498 100644 --- a/.github/upstream-state/tokeneconomizer/tokeneconomizer +++ b/.github/upstream-state/tokeneconomizer/tokeneconomizer @@ -1 +1 @@ -583fff78bf504b59d542f953c31e87d01d02ab42 +1bfeccdcecf48333b22762ad1dd9e36c6dc065df diff --git a/plugins/tokeneconomizer/LICENSE b/plugins/tokeneconomizer/LICENSE index d645695..9003ea9 100644 --- a/plugins/tokeneconomizer/LICENSE +++ b/plugins/tokeneconomizer/LICENSE @@ -1,202 +1,21 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +MIT License + +Copyright (c) 2026 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/tokeneconomizer/package.json b/plugins/tokeneconomizer/package.json index 0163a8a..04539b4 100644 --- a/plugins/tokeneconomizer/package.json +++ b/plugins/tokeneconomizer/package.json @@ -9,7 +9,7 @@ "tokens", "context" ], - "license": "Apache-2.0", + "license": "MIT", "repository": "https://github.com/microsoft/TokenEconomizer", "pi": { "extensions": [ diff --git a/plugins/tokeneconomizer/plugin/.antigravity-plugin/plugin.json b/plugins/tokeneconomizer/plugin/.antigravity-plugin/plugin.json index c90e35c..ce30834 100644 --- a/plugins/tokeneconomizer/plugin/.antigravity-plugin/plugin.json +++ b/plugins/tokeneconomizer/plugin/.antigravity-plugin/plugin.json @@ -6,5 +6,5 @@ "name": "TokenEconomizer authors" }, "repository": "https://github.com/microsoft/TokenEconomizer", - "license": "Apache-2.0" + "license": "MIT" } diff --git a/plugins/tokeneconomizer/plugin/.claude-plugin/plugin.json b/plugins/tokeneconomizer/plugin/.claude-plugin/plugin.json index 2f0db27..9dabf37 100644 --- a/plugins/tokeneconomizer/plugin/.claude-plugin/plugin.json +++ b/plugins/tokeneconomizer/plugin/.claude-plugin/plugin.json @@ -7,7 +7,7 @@ "name": "TokenEconomizer authors" }, "repository": "https://github.com/microsoft/TokenEconomizer", - "license": "Apache-2.0", + "license": "MIT", "commands": "./slash-commands/", "keywords": [ "cost", diff --git a/plugins/tokeneconomizer/plugin/.codex-plugin/plugin.json b/plugins/tokeneconomizer/plugin/.codex-plugin/plugin.json index 408879e..8a9e218 100644 --- a/plugins/tokeneconomizer/plugin/.codex-plugin/plugin.json +++ b/plugins/tokeneconomizer/plugin/.codex-plugin/plugin.json @@ -6,7 +6,7 @@ "name": "TokenEconomizer authors" }, "repository": "https://github.com/microsoft/TokenEconomizer", - "license": "Apache-2.0", + "license": "MIT", "keywords": [ "cost", "tokens", diff --git a/plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json b/plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json index 644144f..669dddd 100644 --- a/plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json +++ b/plugins/tokeneconomizer/plugin/.factory-plugin/plugin.json @@ -7,6 +7,6 @@ }, "homepage": "https://github.com/microsoft/TokenEconomizer", "repository": "https://github.com/microsoft/TokenEconomizer", - "license": "Apache-2.0", + "license": "MIT", "keywords": ["cost", "tokens", "context", "hooks", "micro-skills", "failure-loops", "droid"] } diff --git a/plugins/tokeneconomizer/plugin/.github/plugin/plugin.json b/plugins/tokeneconomizer/plugin/.github/plugin/plugin.json index 15647da..1500b22 100644 --- a/plugins/tokeneconomizer/plugin/.github/plugin/plugin.json +++ b/plugins/tokeneconomizer/plugin/.github/plugin/plugin.json @@ -6,7 +6,7 @@ "name": "TokenEconomizer authors" }, "repository": "https://github.com/microsoft/TokenEconomizer", - "license": "Apache-2.0", + "license": "MIT", "keywords": [ "cost", "tokens", diff --git a/plugins/tokeneconomizer/plugin/README.md b/plugins/tokeneconomizer/plugin/README.md index 0395d66..6b5c138 100644 --- a/plugins/tokeneconomizer/plugin/README.md +++ b/plugins/tokeneconomizer/plugin/README.md @@ -100,7 +100,8 @@ behaviour, run `claude plugin update tokeneconomizer@tokeneconomizer`. **Uninstall.** -1. In each repository where the plugin left tools out: `/tokeneconomizer:toolprune restore`. +1. In each repository where the plugin left tools out (`/tokeneconomizer:repos` lists them): + `/tokeneconomizer:toolprune restore`. 2. `claude plugin uninstall tokeneconomizer@tokeneconomizer`, then `claude plugin marketplace remove tokeneconomizer`. 3. Optional: `rm -rf ~/.tokeneconomizer` to delete what it learned. (A line the plugin added to a @@ -162,8 +163,9 @@ starts the hook with the `python` on PATH (3.10 or later), which `TE_PYTHON` doe **Uninstall.** -1. In each repository where the plugin turned packages off: - `~/.tokeneconomizer/bin/te --host codex toolprune restore` (it leaves an empty `.codex/`). +1. In each repository where the plugin turned packages off (`~/.tokeneconomizer/bin/te --host + codex repos` lists them): `~/.tokeneconomizer/bin/te --host codex toolprune restore` (it + leaves an empty `.codex/`). 2. `codex plugin remove tokeneconomizer@tokeneconomizer`, then `codex plugin marketplace remove tokeneconomizer`. 3. Optional: `rm -rf ~/.tokeneconomizer`. @@ -179,6 +181,45 @@ codex plugin add tokeneconomizer@tokeneconomizer To update it, rebuild the bundle and run `codex plugin add tokeneconomizer@tokeneconomizer` again. +## GitHub Copilot in VS Code + +Requires Python >= 3.10 on PATH and Copilot signed in inside VS Code. + +**1. Install.** + +1. Open your project and select **Copilot** as the chat session target. +2. Press **Ctrl+Shift+P**, run **Chat: Manage Plugin Marketplaces**, and choose **Add Marketplace**. +3. Enter `microsoft/TokenEconomizer` (or the path to your local clone). +4. Select the `tokeneconomizer` marketplace, choose **Browse**, and install `tokeneconomizer`. + +If you install from GitHub rather than a local clone (or on Windows without Git symlink +support), the copied plugin directory holds only `plugin/` without the Python package; either +install from a bundle built with `python scripts/build_plugin.py`, or clone the repository to +`~/.tokeneconomizer/src` (or set `TE_CORE_PATH` to your clone). + +See [VS Code's plugin installation guide](https://code.visualstudio.com/docs/agent-customization/agent-plugins). +GitHub CLI and standalone Copilot CLI are not needed for installation. + +**2. Optional: use without Copilot CLI.** Skip this step to keep your current settings. +To enable model-free micro-skills without the standalone CLI, enter this in a new Copilot chat: + +```text +/tokeneconomizer:config set microskills=envfacts toolprune=off loopguard=off +``` + +This is not required for installation. It disables the model-based proposer and loop guard, +which invoke the standalone CLI, and tool pruning, which has not been verified in VS Code. +These settings apply to this repository. + +**3. Check it.** Enter `/tokeneconomizer:status` in chat and check that it reports the +`copilot` host. If the command is missing, check **Chat: Open Customizations** > **Plugins** +and start a fresh chat with the plugin enabled. + +**Update.** Run **Chat: Update Plugins**, then start a new chat. + +**Uninstall.** Open **Chat: Open Customizations** > **Plugins**, select TokenEconomizer, +and choose **Uninstall**. + ## Copilot CLI **1. Install.** @@ -243,7 +284,8 @@ redirect shows "● TokenEconomizer: …" in the conversation (and on stdout und **Uninstall.** -1. In each repository where the plugin turned a server off: `/tokeneconomizer:toolprune restore`. +1. In each repository where the plugin turned a server off (`/tokeneconomizer:repos` lists them): + `/tokeneconomizer:toolprune restore`. 2. `copilot plugin uninstall tokeneconomizer@tokeneconomizer`, then `copilot plugin marketplace remove tokeneconomizer`. 3. Optional: `rm -rf ~/.tokeneconomizer`. @@ -413,6 +455,13 @@ ln -s /path/to/TokenEconomizer/plugin/opencode/tokeneconomizer.ts ~/.config/open (Per repository: `.opencode/plugins/`.) Python 3.10+ must be on `PATH`, or named by `TE_PYTHON`. +**A copied plugin, not a link,** has no `scripts/` beside it, so it cannot find the dispatcher on +its own. Point it at the checkout: `TE_CORE_PATH=/path/to/TokenEconomizer`, or `TE_PLUGIN_ROOT` +at the directory that holds `scripts/`. Without one of them a copied plugin starts no hook at all. +The state launcher (`~/.tokeneconomizer/bin/te`) is written once a hook has reached the +dispatcher, so it cannot make the first one work. On 2.x the variable must reach the service — +`opencode service restart` from a shell where it is set (see below). + **2. Check it.** Run a session, then `~/.tokeneconomizer/bin/te --host opencode status` in the repository. opencode has no plugin slash commands, so every command runs from a terminal. Tool pruning does not apply. Micro-skills is off by default: `te --host opencode config set @@ -429,8 +478,9 @@ session from its events and writes the same JSON (where that copy holds no promp 2.x's `opencode session export` instead). A turn ends at 2.x's `session.execution.*` events or the documented `session.idle`, whichever the release emits; a headless `opencode run` is folded when its turn ends and a deleted session when it is deleted. Quitting the TUI gives a plugin no -chance to say so: that session is folded by the next session's start, once its export has been -quiet for 10 minutes. +chance to say so, so the plugin hands a session over itself once it has been quiet for 10 +minutes — the window TE's own recovery uses (`fold.STALE_S`; `TE_OPENCODE_QUIET_MS` overrides it, +floor 10 s) — whether or not a later session start ever arrives. **Model calls.** The proposer and the loop guard's judge run through `opencode run` on your default opencode model (`paid_model` names another): tools that change anything are denied, @@ -453,8 +503,11 @@ the side call denies only `bash`, `edit`, `webfetch` and `websearch`. ## Hermes Agent Experimental, and narrower than the other agents: **micro-skills and the loop guard**, on Hermes's -**classic CLI** (`hermes`, `hermes chat`) and **one-shot runs** (`hermes -z`, `hermes chat --oneshot`), -with `terminal.backend: local`. Tested on 0.22.5 only. +**classic CLI** (`hermes`, `hermes chat`), **one-shot runs** (`hermes -z`, `hermes chat --oneshot`), +and gateway sessions (the API server and messaging platforms such as Discord and Telegram) and `cron` +runs, with `terminal.backend: local`. Tested on 0.22.5 only; the gateway and `cron` sessions have +been exercised against a recorded `state.db` and not against a live platform. Where Hermes has +`register_command`, `/te` runs the command line below. **1. Install.** Link the plugin directory, keeping it next to `scripts/` and `lib/`, enable it, and restart the gateway, which is what runs your sessions: @@ -489,9 +542,19 @@ quiet for 10 minutes. A session whose rows cannot be read then stays unfolded an each later start in that repository, for a week after its last hook; after that it is recorded as unreadable. -**Which repository.** Each session's own row names its directory, so sessions in different -repositories can run at once in the one gateway. A session with no directory on this machine is -not followed. +**Which repository.** Each session names its own directory, so sessions in different repositories +can run at once in the one gateway; the gateway's working directory and `TERMINAL_CWD` are never +used. A session's directory is its row's `cwd` in Hermes's `state.db`. A gateway or `cron` session +whose row records none takes the `terminal_cwd` of its chat's routing entry (`gateway_routing`), +then the directory Hermes scopes to the running turn; with none of these it is not followed yet, +and is looked at again at its next hook. Any other session with no directory on this machine is not +followed. A `cron` run is one turn and ends with it; a gateway chat ends at `/new` (a finalize or a +reset), at shutdown, or, if neither fires, when the next session starts in its repository after 10 +quiet minutes. + +**`/te`.** It runs in the repository of the session that typed it, found as above and by the chat's +`session_key`. `/te --cwd PATH status` names another. A session with no directory gets +`te: no working directory for this session; pass --cwd PATH`. **Model calls.** The proposer and the loop guard's judge run through `hermes chat --oneshot --source tool` on your default Hermes model (`paid_model` names another; `hermes_cli` or `TE_HERMES_CLI` @@ -543,9 +606,8 @@ off in mid-turn by a gateway that died, and two timed-out side calls, were recov * A session resumed after it was folded: its later turns are neither learned from nor priced, since a session folds once. That rule is shared by every agent. It matters more here, because a one-shot run folds as soon as its turn ends, so `hermes -c` after `hermes -z` always lands on it. -* The Ink TUI (`--tui`), Desktop, ACP, messaging platforms and cron are ignored, on purpose: nothing - has been verified there, and a chat is not repository work. So are subagents, whose tokens are - counted with their session and whose tool calls are not. +* The Ink TUI (`--tui`), Desktop and ACP are ignored, on purpose: nothing has been verified there. + So are subagents, whose tokens are counted with their session and whose tool calls are not. * Remote terminal backends, named profiles and `plugins.isolation: host`. * Tool pruning. Hermes has no per-repository tool setting. `llm_request` middleware removed a tool from a request in a probe, but keeping a session's list stable across its cache has not been built. @@ -874,6 +936,7 @@ first session there ends. | `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 | +| `tool_roles` | none | tools the mechanisms do not know by name, each given the role of a built-in one: `tool=role` entries separated by commas, a tool by name or pattern, a role `shell`, `edit` or `read` (`mcp__serena__replace_content=edit,mcp__serena__execute_shell_command=shell`). Micro-skills read a shell tool's commands, and an edit tool's file counts as edited; tool pruning still knows each tool by its own name | | `shadow` | `false` | decide and log everything, act on nothing | | `mode` | `auto` | `interactive` or `headless` to override what the plugin detects | @@ -967,8 +1030,9 @@ agents the default listed under [Settings](#settings). `status` prints the repos `overhead`, and a record of its own for each judge call (`"kind": "overhead"`, with the session's id). -These calls run through **your own agent's CLI**: `claude -p`; `codex exec`; `copilot -p`, with -every tool removed; and `pi -p`, with nothing loaded but the model. So they use whatever your +These calls run through **your own agent's CLI**: `claude -p`, in safe mode where your Claude +Code has `--safe-mode` (none of your CLAUDE.md, plugins or hooks); `codex exec`; `copilot -p`, +with every tool removed; and `pi -p`, with nothing loaded but the model. So they use whatever your sessions already use (a Claude subscription or Anthropic API key, your Codex login or OpenAI key, Copilot's subscription, or the provider and login Pi is set up with), are billed there, and are shown in `status`. Copilot with BYOK is the exception; see [Copilot CLI](#copilot-cli). diff --git a/plugins/tokeneconomizer/plugin/hermes/__init__.py b/plugins/tokeneconomizer/plugin/hermes/__init__.py index 5ab826e..3a7f720 100644 --- a/plugins/tokeneconomizer/plugin/hermes/__init__.py +++ b/plugins/tokeneconomizer/plugin/hermes/__init__.py @@ -18,19 +18,36 @@ turn cut short sends no Stop, so it cannot feed the envelope on_session_end (one-shot), - on_session_finalize -> SessionEnd a detached fold. `hermes -z` sends no finalize, + on_session_finalize, + on_session_reset -> SessionEnd a detached fold. `hermes -z` sends no finalize, nor does a killed session: the next session's start folds it once its hooks have gone quiet. The fold reads the session from `state.db` One gateway serves every session and every repository, and its own directory and environment -belong to neither, so everything about a session is read from its row in `state.db`, per session. - -The plugin follows only sessions a person started in a directory on this machine: `created_source` -`cli` or `oneshot`, with a `cwd`. That is also what keeps it out of its own side calls, which run -in this same gateway as `--source tool` and which `TE_SIDECALL` cannot reach; a session whose row -cannot be read is not followed. Subagents (`subagent`), messaging platforms, cron and the other -surfaces are not followed either. +(`os.getcwd()`, `TERMINAL_CWD`) belong to neither, so a session's directory is read per session, +and never from them. + +The plugin follows the sessions a person or a schedule started: `created_source` `cli` or +`oneshot` on this machine, a messaging platform or the API server (`GATEWAY_SOURCES`), and `cron`. +Each needs a directory, the first of: its row's `cwd` in `state.db`; for a gateway or `cron` +session whose row has none, the `terminal_cwd` of the `gateway_routing` entry that names it (a +database without that table has no such entries); then the directory Hermes scopes to the running +turn (`ctx.session_cwd()`, else `agent.runtime_cwd.scoped_session_cwd()`). A gateway or `cron` +session with none is not followed yet, and is looked at again at its next hook, since a chat can +be given a directory later; any other session without one is not followed. A `cron` run is one +turn, so it ends with it, as `hermes -z` does. Sessions of the plugin's own side calls run in this +same gateway as `--source tool` and `TE_SIDECALL` cannot reach them, and a session whose row cannot +be read is not followed, so both stay out. Subagents (`subagent`) are not followed: the fold +prices a session with its subagents, and a child of its own would count them twice. The terminal +UI and ACP are not followed either. + +`/te` runs the command line (`te --host hermes ...`) where Hermes has `register_command`, in the +calling session's directory: Hermes passes the `session_id` and `session_key` the handler declares, +and the directory is that session's (as above; a chat is also found by its `session_key` in +`gateway_routing`). A `--cwd` in the arguments is used as given. With no directory it says so and +runs nothing, rather than read the gateway's own repository. `on_session_reset` ends the session +a `/new` leaves, as `on_session_finalize` does, and one already ended is not ended twice. Hermes runs hooks under `plugins.hook_callback_timeout` (30s), and one overrun silences that callback for 60s for every session, so a dispatcher call has a shorter limit of its own. Every @@ -40,6 +57,7 @@ import logging import os import pathlib +import shlex import sqlite3 import subprocess import sys @@ -50,6 +68,10 @@ HERE = os.path.dirname(os.path.realpath(__file__)) BOOTSTRAP = os.path.join(HERE, "..", "scripts", "te_bootstrap.py") USER_SOURCES = ("cli", "oneshot") +GATEWAY_SOURCES = ("api_server", "discord", "telegram", "slack", "whatsapp", "signal", "matrix", + "mattermost", "email", "sms", "webhook") +SCHEDULED_SOURCES = ("cron",) +FOLLOWED_SOURCES = USER_SOURCES + GATEWAY_SOURCES + SCHEDULED_SOURCES HOOK_TIMEOUT_S = 20 LOCK_TIMEOUT_S = 5 HIDDEN = {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {} @@ -136,6 +158,41 @@ def lineage(con, session_id): return rows +def _routes(con): + """Every gateway routing entry, as dicts; none where `state.db` has no such table.""" + try: + rows = con.execute("SELECT session_key, entry_json FROM gateway_routing").fetchall() + except sqlite3.Error: + return [] + out = [] + for key, raw in rows: + try: + entry = json.loads(raw) + except (TypeError, ValueError): + continue + if isinstance(entry, dict): + meta = entry.get("metadata") + out.append((key, entry.get("session_id"), + meta.get("terminal_cwd") if isinstance(meta, dict) else None)) + return out + +def routed_cwd(con, session_ids): + """The directory a gateway chat works in, from the routing entry that names one of these + sessions.""" + for _, sid, cwd in _routes(con): + if cwd and sid in session_ids: + return cwd + return None + +def scoped_cwd(): + """The directory scoped to the session whose turn is running (Hermes binds it per turn and per + cron run), or "". Never the gateway's own.""" + try: + from agent.runtime_cwd import scoped_session_cwd + return scoped_session_cwd() or "" + except Exception: + return "" + def with_redirect(result, text): """`result` carrying `text`, or None when it cannot without losing its shape. A JSON object keeps every byte it had, after a first key of ours; plain text gets the line after it.""" @@ -160,9 +217,10 @@ class Bridge: """What the plugin keeps about sessions in the gateway's memory, keyed by the lineage's first id. A gateway restart loses it, and the next hook finds each session again.""" - def __init__(self, call=dispatch, home=hermes_home): + def __init__(self, call=dispatch, home=hermes_home, session_cwd=scoped_cwd): self.call = call self.home = home + self.session_cwd = session_cwd self.sessions = {} # any id of a followed session -> its record self.ignored = set() self.guard = threading.Lock() @@ -176,8 +234,8 @@ def _forget_ended(self): def _record(self, row, root): return {"id": root, "cwd": row["cwd"], "lock": threading.Lock(), "started": False, - "mode": "oneshot" if (row.get("created_source") or row.get("source")) == "oneshot" - else "cli", "held": [], "notices": []} + "mode": "oneshot" if (row.get("created_source") or row.get("source")) + in ("oneshot",) + SCHEDULED_SOURCES else "cli", "held": [], "notices": []} def session(self, session_id): """The record of a session the plugin follows, or None. A row that cannot be read is @@ -192,17 +250,24 @@ def session(self, session_id): con = _connect(self.home()) try: chain = lineage(con, session_id) + origin = (chain[0].get("created_source") or chain[0].get("source")) if chain else "" + cwd = (chain[-1].get("cwd") or chain[0].get("cwd")) if chain else None + scheduled = origin in GATEWAY_SOURCES + SCHEDULED_SOURCES + if chain and not cwd and scheduled: + cwd = routed_cwd(con, {r["id"] for r in chain}) # a chat's own directory finally: con.close() except (OSError, ValueError, sqlite3.Error): return None if not chain: return None - leaf, root = chain[-1], chain[0]["id"] - origin = chain[0].get("created_source") or chain[0].get("source") - cwd = leaf.get("cwd") or chain[0].get("cwd") + root = chain[0]["id"] + if not cwd and scheduled: + cwd = self.session_cwd() or None # this turn's, never the gateway's with self.guard: - if origin not in USER_SOURCES or not cwd or not os.path.isdir(cwd): + if scheduled and not (cwd and os.path.isdir(cwd)): + return None # a chat or run can be given a directory later + if origin not in FOLLOWED_SOURCES or not cwd or not os.path.isdir(cwd): if len(self.ignored) >= MAX_IGNORED: self.ignored.clear() self.ignored.add(session_id) @@ -316,11 +381,72 @@ def on_session_finalize(self, session_id=None, reason="", **_): return "\n".join(notices) or None + def on_session_reset(self, session_id="", old_session_id="", reason="", **_): + """`/new` ends the session it leaves; a surface that fires this and no finalize still ends + it. A session already ended is not ended twice.""" + return self.on_session_finalize(session_id=old_session_id or session_id, + reason=reason or "reset") + + def command_cwd(self, session_id="", session_key=""): + """The directory of the session that typed `/te`: not this process's, which is the + gateway's.""" + rec = self.session(session_id) + if rec is not None: + return rec["cwd"] + if session_key: + try: + con = _connect(self.home()) + try: + routes = [r for r in _routes(con) if r[0] == session_key] + finally: + con.close() + except (OSError, ValueError, sqlite3.Error): + routes = [] + for _, sid, cwd in routes: + rec = self.session(sid) + found = cwd if cwd and os.path.isdir(cwd) else rec and rec["cwd"] + if found: + return found + cwd = self.session_cwd() + return cwd if cwd and os.path.isdir(cwd) else None + + def command(self, raw_args="", session_id="", session_key="", platform="", source=None, **_): + """`/te ...` for the calling session. Hermes passes the arguments a handler declares.""" + try: + argv = shlex.split(raw_args or "") + if any(a == "--cwd" or a.startswith("--cwd=") for a in argv): + return te_command(raw_args) # the person named a repository + cwd = self.command_cwd(session_id, session_key) + except (ValueError, sqlite3.Error) as e: + return f"te: {e}" + if not cwd and argv[:1] not in (["repos"], ["doctor"]): + return "te: no working directory for this session; pass --cwd PATH" + return te_command(raw_args, cwd) + +def te_command(raw_args="", cwd=None): + """`/te ...`: the command line, as `te --host hermes ...`, and its output as the reply.""" + try: + argv = shlex.split(raw_args or "") + where = ["--cwd", cwd] if cwd else [] + out = subprocess.run([os.environ.get("TE_PYTHON") or sys.executable, BOOTSTRAP, "cli", + "--host", "hermes", *where, *argv], + cwd=cwd, capture_output=True, encoding="utf-8", errors="replace", + timeout=HOOK_TIMEOUT_S, stdin=subprocess.DEVNULL, + env=dict(os.environ, PYTHONUTF8="1", HERMES_HOME=hermes_home()), + **HIDDEN) + return ((out.stdout or "") + (out.stderr or "")).strip() or "te: no output" + except (OSError, ValueError, subprocess.SubprocessError) as e: + return f"te: {e}" + def register(ctx): - bridge = Bridge() + # `ctx.session_cwd()` is the calling session's directory, task-local to its turn. + bridge = Bridge(session_cwd=getattr(ctx, "session_cwd", scoped_cwd)) ctx.register_system_prompt_section(SECTION_ID, bridge.section, position="after_memory", max_chars=4000) ctx.register_hook("pre_llm_call", bridge.pre_llm_call) ctx.register_hook("transform_tool_result", bridge.transform_tool_result) ctx.register_hook("on_session_end", bridge.on_session_end) ctx.register_hook("on_session_finalize", bridge.on_session_finalize) + ctx.register_hook("on_session_reset", bridge.on_session_reset) + if hasattr(ctx, "register_command"): # older Hermes has none + ctx.register_command("te", bridge.command, description="TokenEconomizer status and settings") diff --git a/plugins/tokeneconomizer/plugin/hermes/plugin.yaml b/plugins/tokeneconomizer/plugin/hermes/plugin.yaml index 7835ee1..7d18ee7 100644 --- a/plugins/tokeneconomizer/plugin/hermes/plugin.yaml +++ b/plugins/tokeneconomizer/plugin/hermes/plugin.yaml @@ -7,3 +7,4 @@ provides_hooks: - transform_tool_result - on_session_end - on_session_finalize + - on_session_reset diff --git a/plugins/tokeneconomizer/plugin/opencode/tokeneconomizer.ts b/plugins/tokeneconomizer/plugin/opencode/tokeneconomizer.ts index ac9ffa6..c0d3dbb 100644 --- a/plugins/tokeneconomizer/plugin/opencode/tokeneconomizer.ts +++ b/plugins/tokeneconomizer/plugin/opencode/tokeneconomizer.ts @@ -16,12 +16,15 @@ * still-stuck notice is shown as a toast * event session.idle -> Stop closes the turn; the session is exported as * JSON and its path sent along - * event session.deleted, a headless run's end, or the process exiting - * -> SessionEnd hands the session to a detached fold; a - * TUI quit sends nothing, so the plugin's - * session-recovery folds it at the next - * start once its export has been quiet for - * 10 minutes + * event session.deleted, a headless run's end, a session quiet for 10 minutes, or the + * process exiting -> SessionEnd hands the session to a detached fold. On + * 2.x `opencode run` and the TUI are the + * same background process, so the plugin + * does not guess which one it is: any + * session quiet as long as TE's own + * recovery treats it as over (fold.STALE_S) + * is handed over, whether or not a later + * session start ever arrives. * * The module's one export is the default object below: opencode 1.x reads its `server`, 2.x its * `setup`, and 1.x would call a second export as another plugin. The two entries map the same @@ -37,7 +40,7 @@ */ import type { Plugin } from "@opencode-ai/plugin"; import { spawn, spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -49,7 +52,53 @@ const HERE = (() => { return __dirname; } })(); -const SCRIPTS = join(HERE, "..", "scripts"); +/** + * The directory holding the dispatcher (`te_bootstrap.py` / `te-hook`). Where it sits depends on + * how the plugin was put where opencode loads it from: the checkout keeps it at + * `/plugin/scripts`, an installed plugin at `/scripts`. Resolve rather than assume, so + * a move of the install is not a move of the dispatcher -- and the hook fails open rather than + * pointing at a path that is not there. + * + * Only the shipped layouts and the launcher the plugin writes itself are anchors. Nothing walks + * up from the plugin's directory: on Windows that walk ends at `C:\`, where a standard user can + * create folders by default, so a planted `scripts/te_bootstrap.py` would run in every hook -- + * and any unrelated ancestor would win over the dispatcher the plugin actually ships with. + */ +const findScripts = (): string => { + const wanted = (p: string) => existsSync(join(p, "te_bootstrap.py")); + // Named explicitly: `TE_PLUGIN_ROOT` is the package (`/scripts`), `TE_CORE_PATH` the + // checkout the bootstrap already documents (`/plugin/scripts`). A fresh install has no + // launcher yet, so these are what make the first hook work. + const explicit: string[] = []; + const pluginRoot = process.env.TE_PLUGIN_ROOT; + if (pluginRoot) explicit.push(join(pluginRoot, "scripts")); + const core = process.env.TE_CORE_PATH; + if (core) explicit.push(join(core, "plugin", "scripts")); + for (const c of explicit) { + if (wanted(c)) return c; + } + // The layout the plugin ships in: `/opencode/` next to `/scripts`. + const shipped = join(HERE, "..", "scripts"); + if (wanted(shipped)) return shipped; + const state = process.env.TOKENECONOMIZER_HOME || join(homedir(), ".tokeneconomizer"); + const launcher = join(state, "bin", "te"); + try { + if (existsSync(launcher)) { + // The launcher is `exec /scripts/te "$@"`, so its own directory is the dispatcher's. + const body = readFileSync(launcher, "utf8"); + const m = /exec\s+(.+?)\s+"\$@"/.exec(body); + if (m) { + const target = m[1].replace(/^['"]|['"]$/g, ""); + const scripts = dirname(target); + if (wanted(scripts)) return scripts; + } + } + } catch { + /* an unreadable launcher is no anchor */ + } + return shipped; +}; +const SCRIPTS = findScripts(); const HOOK_TIMEOUT_MS = 60_000; const truthy = (v: string | undefined) => @@ -192,8 +241,31 @@ const TokenEconomizer: Plugin = async ({ client, directory }) => { } }; + const cleanup = (sessionID: string) => { + manuals.delete(sessionID); + prompts.delete(sessionID); + turns.delete(sessionID); + if (current === sessionID) current = ""; + }; + + // Where the process ends without a `session.deleted` (quitting the TUI, `opencode run` + // finishing), the sessions still open are handed over, once, synchronously. + const onExit = () => { + for (const sessionID of open) { + const file = exportSession(sessionID, directory); + cleanup(sessionID); + hookSync({ + ...base(sessionID, file), + hook_event_name: "SessionEnd", + reason: "exit", + }); + } + open.clear(); + }; + const start = async (sessionID: string) => { if (open.has(sessionID)) return; + if (open.size === 0) process.once("exit", onExit); open.add(sessionID); prompts.set(sessionID, 0); const out = await hook({ @@ -207,23 +279,12 @@ const TokenEconomizer: Plugin = async ({ client, directory }) => { const end = async (sessionID: string, reason: string) => { if (!open.delete(sessionID)) return; + if (open.size === 0) process.off("exit", onExit); const file = exportSession(sessionID, directory); + cleanup(sessionID); await hook({ ...base(sessionID, file), hook_event_name: "SessionEnd", reason }); }; - // Where the process ends without a `session.deleted` (quitting the TUI, `opencode run` - // finishing), the sessions still open are handed over, once, synchronously. - process.once("exit", () => { - for (const sessionID of open) { - hookSync({ - ...base(sessionID, exportSession(sessionID, directory)), - hook_event_name: "SessionEnd", - reason: "exit", - }); - } - open.clear(); - }); - return { event: async ({ event }: { event: any }) => { const props = event?.properties ?? {}; @@ -332,6 +393,49 @@ const textOf = (content: any): string => .join("\n") : ""; +const deliverNudge = (e: any, ok: boolean, result: any, nudge: string): boolean => { + if (ok && result && typeof result === "object") { + if (typeof result.content === "string") { + result.content = `${result.content}\n\n${nudge}`; + return true; + } + if (Array.isArray(result.content)) { + result.content = [...result.content, { type: "text", text: nudge }]; + return true; + } + if (result.content === undefined && typeof result.output === "string") { + result.output = `${result.output}\n\n${nudge}`; + return true; + } + if (result.content === undefined) { + result.content = nudge; + return true; + } + return false; + } + if (!ok && e && typeof e === "object") { + if (e.error && typeof e.error === "object" && typeof e.error.message === "string") { + try { + const updated = e.error.message ? `${e.error.message}\n\n${nudge}` : nudge; + e.error.message = updated; + if (e.error.message === updated) return true; + } catch { + /* read-only error.message */ + } + } + if (typeof e.error === "string") { + try { + const updated = e.error ? `${e.error}\n\n${nudge}` : nudge; + e.error = updated; + if (e.error === updated) return true; + } catch { + /* read-only event.error */ + } + } + } + return false; +}; + const setupV2 = async (ctx: any) => { const directory: string = ctx.location?.directory ?? ctx.location?.path ?? process.cwd(); const open = new Set(); @@ -340,8 +444,9 @@ const setupV2 = async (ctx: any) => { const prompts = new Map(); const turns = new Map(); const records = new Map(); // sessionID -> messages, in the export's shape - const steps = new Map(); // assistantMessageID -> assistant message - const names = new Map(); // tool call id -> tool name + const steps = new Map(); + const names = new Map(); + const pendingNudges = new Map(); const base = (sessionID: string, transcript = "") => ({ session_id: sessionID, @@ -352,6 +457,19 @@ const setupV2 = async (ctx: any) => { if (typeof text === "string" && text) console.error(text); }; + /** A resumed session keeps the turns an earlier hand-over already wrote, so the export a fold + * reads is never replaced by only the new epoch. */ + const loadExport = (sessionID: string): any[] => { + const file = join(stateRoot(), "opencode-sessions", `${sessionID}.json`); + if (!existsSync(file)) return []; + try { + const doc = JSON.parse(readFileSync(file, "utf8")); + return Array.isArray(doc?.messages) ? doc.messages : []; + } catch { + return []; + } + }; + const writeExport = (sessionID: string): string => { const file = join(stateRoot(), "opencode-sessions", `${sessionID}.json`); // A copy of this plugin that saw none of the session's messages has nothing to add, and must @@ -372,18 +490,67 @@ const setupV2 = async (ctx: any) => { } }; + const cleanup = (id: string) => { + unsettled.delete(id); + manuals.delete(id); + prompts.delete(id); + turns.delete(id); + records.delete(id); + pendingNudges.delete(id); + for (const [mid, entry] of steps) { + if (entry.sessionID === id) steps.delete(mid); + } + for (const [cid, entry] of names) { + if (entry.sessionID === id) names.delete(cid); + } + }; + const start = async (id: string) => { if (open.has(id)) return; open.add(id); - records.set(id, []); + records.set(id, loadExport(id)); prompts.set(id, 0); const out = await hook({ ...base(id), hook_event_name: "SessionStart", source: "startup" }); manuals.set(id, out?.hookSpecificOutput?.additionalContext ?? ""); notify(out?.systemMessage); }; + /** + * A session that has been quiet this long is over, however it was started. opencode 2.x runs + * plugins in its background service, where `opencode run` and the TUI are the same process, so + * `mode()` cannot tell them apart -- and a release may move which one holds the plugin again. + * TE's own recovery already calls a session quiet for `fold.STALE_S` (600 s) over; this + * enforces the same rule here, so the hand-over does not wait for a later session start and + * does not depend on guessing the mode. Any activity resets the timer, and a turn still open + * (a long tool call, a permission prompt waiting on the person) is not quiet: the session is + * handed over only once its turn has ended. + */ + const QUIET_MS = (() => { + const raw = Number(process.env.TE_OPENCODE_QUIET_MS); + return Number.isFinite(raw) && raw > 0 ? Math.max(raw, 10_000) : 600_000; + })(); + const quiet = new Map>(); + const settled = (id: string) => { + const timer = quiet.get(id); + if (timer) clearTimeout(timer); + quiet.delete(id); + }; + const bumpQuiet = (id: string) => { + if (!open.has(id)) return; + settled(id); + const timer = setTimeout(() => { + quiet.delete(id); + if (unsettled.has(id)) bumpQuiet(id); + else if (open.has(id)) void end(id, "idle"); + }, QUIET_MS); + (timer as unknown as { unref?: () => void }).unref?.(); + quiet.set(id, timer); + }; const end = async (id: string, reason: string) => { + settled(id); if (!open.delete(id)) return; - await hook({ ...base(id, writeExport(id)), hook_event_name: "SessionEnd", reason }); + const file = writeExport(id); + cleanup(id); + await hook({ ...base(id, file), hook_event_name: "SessionEnd", reason }); }; /** A turn's end, however 2.x signals it. `session.execution.*` and `session.idle` both arrive * per turn on releases that emit both; the first settles the turn and the second is a no-op. @@ -391,28 +558,37 @@ const setupV2 = async (ctx: any) => { * hook in the dispatcher instead. */ const closeTurn = async (id: string) => { if (!unsettled.delete(id)) return; + pendingNudges.delete(id); await hook({ ...base(id, writeExport(id)), hook_event_name: "Stop", prompt_id: turns.get(id) ?? "", stop_hook_active: false, }); + // Where the process really is a one-shot run, hand the session over now; everywhere else the + // quiet timer does it, so the fold no longer depends on how the plugin was launched. if (mode() === "run") await end(id, "run"); + else bumpQuiet(id); }; - process.once("exit", () => { - for (const id of open) - hookSync({ ...base(id, writeExport(id)), hook_event_name: "SessionEnd", reason: "exit" }); + const onExit = () => { + for (const id of open) { + const file = writeExport(id); + cleanup(id); + hookSync({ ...base(id, file), hook_event_name: "SessionEnd", reason: "exit" }); + } open.clear(); - }); + }; + process.once("exit", onExit); const assistant = (sessionID: string, messageID: string) => { - let m = steps.get(messageID); - if (!m) { - m = { info: { id: messageID, role: "assistant", path: { cwd: directory } }, parts: [] }; - steps.set(messageID, m); - records.get(sessionID)?.push(m); + let entry = steps.get(messageID); + if (!entry) { + const msg = { info: { id: messageID, role: "assistant", path: { cwd: directory } }, parts: [] }; + entry = { sessionID, msg }; + steps.set(messageID, entry); + records.get(sessionID)?.push(msg); } - return m; + return entry.msg; }; const toolPart = (m: any, callID: string) => m.parts.find((p: any) => p.callID === callID); @@ -421,11 +597,13 @@ const setupV2 = async (ctx: any) => { await ctx.session.hook("prompt", async (e: any) => { const id: string = e.sessionID; await start(id); + pendingNudges.delete(id); const n = (prompts.get(id) ?? 0) + 1; prompts.set(id, n); const turn = `${id}:${n}`; turns.set(id, turn); unsettled.add(id); + bumpQuiet(id); const text: string = e.prompt?.text ?? ""; records.get(id)?.push({ info: { id: String(e.messageID ?? turn), role: "user" }, @@ -453,6 +631,8 @@ const setupV2 = async (ctx: any) => { try { await ctx.tool.hook("execute.after", async (e: any) => { const id: string = e.sessionID; + bumpQuiet(id); + const turnAtCall = turns.get(id) ?? ""; const ok = e.status === "completed"; const result = ok ? e.result : undefined; const text = ok @@ -462,7 +642,7 @@ const setupV2 = async (ctx: any) => { const out = await hook({ ...base(id), hook_event_name: "PostToolUse", - prompt_id: turns.get(id) ?? "", + prompt_id: turnAtCall, tool_name: e.tool, tool_use_id: e.id, tool_input: e.input ?? {}, @@ -472,12 +652,14 @@ const setupV2 = async (ctx: any) => { exit_code: exit, }, }); + const held = pendingNudges.get(id); const nudge = out?.hookSpecificOutput?.additionalContext; - if (nudge && ok && result) { - if (typeof result.content === "string") result.content = `${result.content}\n\n${nudge}`; - else if (Array.isArray(result.content)) - result.content = [...result.content, { type: "text", text: nudge }]; - else result.content = nudge; + const combined = [held, nudge] + .filter((v): v is string => typeof v === "string" && Boolean(v)) + .join("\n\n"); + if (combined) { + if (deliverNudge(e, ok, result, combined)) pendingNudges.delete(id); + else if ((turns.get(id) ?? "") === turnAtCall) pendingNudges.set(id, combined); } notify(out?.systemMessage); }); @@ -500,13 +682,15 @@ const setupV2 = async (ctx: any) => { m.info.cost = p.cost ?? 0; m.info.tokens = p.tokens; } else if (t === "session.tool.input.started") { - names.set(p.id, p.name); + names.set(p.id, { sessionID: id, name: p.name }); } else if (t === "session.tool.called") { const m = assistant(id, p.assistantMessageID); + const name = names.get(p.id)?.name ?? ""; + names.delete(p.id); m.parts.push({ type: "tool", callID: p.id, - tool: names.get(p.id) ?? "", + tool: name, state: { status: "running", input: p.input ?? {} }, }); } else if (t === "session.tool.success" || t === "session.tool.failed") { @@ -530,7 +714,10 @@ const setupV2 = async (ctx: any) => { } })(); - return () => controller.abort(); + return () => { + controller.abort(); + process.off("exit", onExit); + }; }; // One default export for both: v1 reads `server`, v2 reads `setup`. diff --git a/plugins/tokeneconomizer/plugin/package.json b/plugins/tokeneconomizer/plugin/package.json index 9f55688..d51f261 100644 --- a/plugins/tokeneconomizer/plugin/package.json +++ b/plugins/tokeneconomizer/plugin/package.json @@ -9,7 +9,7 @@ "tokens", "context" ], - "license": "Apache-2.0", + "license": "MIT", "repository": "https://github.com/microsoft/TokenEconomizer", "pi": { "extensions": [ diff --git a/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts b/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts index 6ca2deb..dff1e0a 100644 --- a/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts +++ b/plugins/tokeneconomizer/plugin/pi/tokeneconomizer.ts @@ -20,7 +20,8 @@ * * Like the hooks on the other agents it fails open: a dispatcher that is missing, slow or * broken answers "no change". It does nothing under TE_SIDECALL=1 (the plugin's own side - * calls) or TE_DISABLE=1. `/te ` runs the `te` command line for this repository. + * calls) or TE_DISABLE=1. `/te ` runs the `te` command line for this repository, and + * completes its subcommands, actions and options as they are typed. */ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; import { spawn } from "node:child_process"; @@ -149,6 +150,45 @@ export function carriedSection(entries: any[]): string { : text; } +/** What `/te` completes: each `te` subcommand a Pi user runs, with its actions and options, as + * `build_parser()` declares them (a test holds the two together). Not `fold` and `judge`, which + * the plugin starts itself, nor `probe`, which runs on Copilot only. */ +export const TE_COMMANDS: Record = { + status: { actions: [], flags: ["--json", "--explain"] }, + microskills: { actions: ["show", "forget", "unforget"], flags: [] }, + toolprune: { + actions: ["show", "apply", "restore", "refresh-catalog", "measure", "apply-pending"], + flags: [], + }, + config: { actions: ["show", "set", "unset"], flags: ["--global"] }, + doctor: { actions: [], flags: [] }, + repos: { actions: ["list", "migrate", "merge"], flags: ["--json", "--quiet"] }, + history: { actions: ["status", "import"], flags: ["--dry-run", "--status"] }, + repomap: { actions: ["show", "refresh"], flags: [] }, +}; + +/** `/te` argument completions: the subcommand, then its action, then options not yet given. + * Pi passes the arguments typed so far and replaces them with the chosen item's value, so a + * value restates them, completes the last word and adds a space for the next one. */ +export function completeTe(prefix: string): { value: string; label: string }[] | null { + const words = prefix.trimStart().split(/\s+/); + const word = words.pop() ?? ""; + const head = prefix.slice(0, prefix.length - word.length); + let candidates: string[]; + if (words.length === 0) { + candidates = Object.keys(TE_COMMANDS); + } else { + const spec = TE_COMMANDS[words[0]]; + if (!spec) return null; + const actionGiven = words.slice(1).some((w) => !w.startsWith("-")); + candidates = [...(actionGiven ? [] : spec.actions), ...spec.flags.filter((f) => !words.includes(f))]; + } + const items = candidates + .filter((c) => c.startsWith(word)) + .map((c) => ({ value: `${head}${c} `, label: c })); + return items.length ? items : null; +} + export default function tokeneconomizer(pi: ExtensionAPI) { let manual = ""; let prompts = 0; @@ -224,6 +264,7 @@ export default function tokeneconomizer(pi: ExtensionAPI) { pi.registerCommand("te", { description: "TokenEconomizer: status | microskills | config | repos (what it learned here, what it did)", + getArgumentCompletions: completeTe, handler: async (args, ctx) => { // `te` splits the line itself (shlex), so a quoted fact id with spaces stays one argument. const argv = ["--argline", (args || "").trim() || "status"]; diff --git a/plugins/tokeneconomizer/plugin/scripts/te b/plugins/tokeneconomizer/plugin/scripts/te index ecc0f17..4cc028a 100755 --- a/plugins/tokeneconomizer/plugin/scripts/te +++ b/plugins/tokeneconomizer/plugin/scripts/te @@ -6,6 +6,11 @@ if [ "${OS:-}" = Windows_NT ]; then case $self in *\\*) self=$(printf '%s' "$self" | tr '\\' '/') ;; esac fi dir=$(CDPATH= cd -- "${self%/*}" && pwd) +# Git Bash: `pwd` gives /c/Users/...; native Python reads that as C:\c\Users\... once MSYS path +# conversion is off (MSYS_NO_PATHCONV=1, as in hooks), so pass it the Windows form instead. +if [ "${OS:-}" = Windows_NT ]; then + dir=$(CDPATH= cd -- "$dir" && pwd -W 2>/dev/null) || dir=$(CDPATH= cd -- "${self%/*}" && pwd) +fi # Session logs are UTF-8; without this, Python on Windows reads them in the ANSI code page. export PYTHONUTF8=1 outside_windowsapps() { diff --git a/plugins/tokeneconomizer/plugin/scripts/te-hook b/plugins/tokeneconomizer/plugin/scripts/te-hook index 94da312..6281f62 100755 --- a/plugins/tokeneconomizer/plugin/scripts/te-hook +++ b/plugins/tokeneconomizer/plugin/scripts/te-hook @@ -10,6 +10,11 @@ if [ "${OS:-}" = Windows_NT ]; then case $self in *\\*) self=$(printf '%s' "$self" | tr '\\' '/') ;; esac fi dir=$(CDPATH= cd -- "${self%/*}" && pwd) +# Git Bash: `pwd` gives /c/Users/...; native Python reads that as C:\c\Users\... once MSYS path +# conversion is off (MSYS_NO_PATHCONV=1, as in hooks), so pass it the Windows form instead. +if [ "${OS:-}" = Windows_NT ]; then + dir=$(CDPATH= cd -- "$dir" && pwd -W 2>/dev/null) || dir=$(CDPATH= cd -- "${self%/*}" && pwd) +fi # Session logs are UTF-8; without this, Python on Windows reads them in the ANSI code page. export PYTHONUTF8=1 outside_windowsapps() { diff --git a/plugins/tokeneconomizer/plugin/scripts/te_bootstrap.py b/plugins/tokeneconomizer/plugin/scripts/te_bootstrap.py index 83dd420..f32dcc4 100644 --- a/plugins/tokeneconomizer/plugin/scripts/te_bootstrap.py +++ b/plugins/tokeneconomizer/plugin/scripts/te_bootstrap.py @@ -18,7 +18,16 @@ `source` (the clone a local marketplace was added from), or Codex's own checkout of a git marketplace, `/.tmp/marketplaces/`; - 5. an installed package -- `pip install` of the repository. + 5. a Copilot or VS Code copy -- for a copy under `/installed-plugins/...` + or VS Code's `agentPlugins/...`, the marketplace + checkouts under the Copilot home and the sources its + `config.json`, `marketplaces.json` or VS Code's + `installed.json` name; + 6. Claude Code's marketplace -- the source `~/.claude/plugins/known_marketplaces.json` + records for this marketplace, which another agent's + copy can share; + 7. `/src` -- a clone kept in the state directory; + 8. an installed package -- `pip install` of the repository. When none has it, a hook answers `{}` as always, and says why once in the plugin's errors.log. @@ -95,6 +104,211 @@ def _marketplace_sources(plugin_root): return out +def _state_home(): + return os.environ.get("TOKENECONOMIZER_HOME") or os.path.join( + os.path.expanduser("~"), ".tokeneconomizer") + + +def _strip_jsonc(text): + """Strip `//`, `/* ... */` comments and trailing commas outside JSON strings.""" + out = [] + i = 0 + n = len(text) + in_str = False + while i < n: + ch = text[i] + if in_str: + out.append(ch) + if ch == "\\" and i + 1 < n: + out.append(text[i + 1]) + i += 2 + continue + if ch == '"': + in_str = False + i += 1 + continue + if ch == '"': + in_str = True + out.append(ch) + i += 1 + continue + if ch == "/" and i + 1 < n: + nxt = text[i + 1] + if nxt == "/": + end = text.find("\n", i + 2) + i = n if end == -1 else end + continue + if nxt == "*": + end = text.find("*/", i + 2) + if end == -1: + break + for c in text[i:end + 2]: + if c == "\n": + out.append("\n") + i = end + 2 + continue + if ch == ",": + j = i + 1 + while j < n: + if text[j] in " \t\r\n": + j += 1 + elif text[j:j + 2] == "//": + end = text.find("\n", j + 2) + j = n if end == -1 else end + 1 + elif text[j:j + 2] == "/*": + end = text.find("*/", j + 2) + j = n if end == -1 else end + 2 + else: + break + if j < n and text[j] in "}]": + i += 1 + continue + out.append(ch) + i += 1 + return "".join(out) + + +def _json_load_relaxed(path): + """Read a JSON/JSONC file (comments and trailing commas allowed outside strings).""" + import json + try: + fh = open(path, encoding="utf-8", errors="replace") + try: + text = fh.read() + finally: + fh.close() + except (IOError, OSError): + return None + try: + return json.loads(_strip_jsonc(text), strict=False) + except ValueError: + return None + + +def _paths_from_entry(entry): + """Extract string directory candidates from a marketplace registry entry.""" + out = [] + if isinstance(entry, str): + out.append(entry) + elif isinstance(entry, dict): + src = entry.get("source") + if isinstance(src, str): + out.append(src) + elif isinstance(src, dict): + for key in ("path", "location", "root"): + if isinstance(src.get(key), str): + out.append(src[key]) + for key in ("path", "installLocation", "location", "sourcePath", "uri"): + val = entry.get(key) + if isinstance(val, str): + out.append(val) + cleaned = [] + for cand in out: + if cand.startswith("file:///"): + from urllib.parse import unquote + # `file:///C:/foo` -> `C:/foo`; `file:///home/foo` -> `/home/foo` + tail = unquote(cand[8:]) + if len(tail) >= 2 and tail[1] == ":": + cand = tail + else: + cand = "/" + tail + cleaned.append(cand) + return cleaned + + +def _known_marketplace_sources(plugins_dir, market): + data = _json_load_relaxed(os.path.join(plugins_dir, "known_marketplaces.json")) + if not isinstance(data, dict): + return [] + out = [] + keys = [market] if market else [] + for k in data: + if k not in keys and "tokeneconomizer" in str(k).lower(): + keys.append(k) + for k in keys: + out.extend(_paths_from_entry(data.get(k))) + return out + + +def _copilot_sources(copilot_home, market): + """Marketplace checkouts and registered local sources under a Copilot home directory.""" + out = [] + names = [market] if market and market != "_direct" else [] + if "tokeneconomizer" not in names: + names.append("tokeneconomizer") + for sub in ("marketplaces", ".marketplaces", os.path.join("plugins", "marketplaces"), + "marketplace-cache"): + base = os.path.join(copilot_home, sub) + for name in names: + out.append(os.path.join(base, name)) + try: + entries = sorted(os.listdir(base)) + except OSError: + entries = [] + for entry in entries: + if "tokeneconomizer" in entry.lower(): + out.append(os.path.join(base, entry)) + for fname in ("config.json", "marketplaces.json", "known_marketplaces.json"): + data = _json_load_relaxed(os.path.join(copilot_home, fname)) + if not isinstance(data, dict): + continue + for section in (data, data.get("marketplaces"), data.get("pluginMarketplaces")): + if isinstance(section, dict): + for name in names: + out.extend(_paths_from_entry(section.get(name))) + for k, v in section.items(): + if "tokeneconomizer" in str(k).lower(): + out.extend(_paths_from_entry(v)) + return out + + +def _extra_sources(plugin_root): + """Package locations outside Claude/Codex's cache layout: Copilot `installed-plugins`, + VS Code's `agentPlugins` mirrors, cross-cache `~/.claude/plugins/known_marketplaces.json` + (`omp`/Copilot on Windows), and `/src`.""" + out = [] + norm = os.path.normpath(plugin_root).rstrip(os.sep) + parts = norm.split(os.sep) + market = None + user_home = os.path.expanduser("~") + + if "installed-plugins" in parts: + idx = parts.index("installed-plugins") + copilot_home = os.sep.join(parts[:idx]) or os.sep + if idx + 1 < len(parts): + market = parts[idx + 1] + out.extend(_copilot_sources(copilot_home, market)) + if market == "_direct" and idx + 2 < len(parts): + out.extend(_copilot_sources(copilot_home, parts[idx + 2])) + + if "agentPlugins" in parts: + ap_idx = parts.index("agentPlugins") + ap_dir = os.sep.join(parts[:ap_idx + 1]) or os.sep + for cfg_dir in (ap_dir, os.path.dirname(ap_dir)): + data = _json_load_relaxed(os.path.join(cfg_dir, "installed.json")) + if isinstance(data, dict): + for item in data.values(): + out.extend(_paths_from_entry(item)) + elif isinstance(data, list): + for item in data: + out.extend(_paths_from_entry(item)) + user_copilot = os.path.join(user_home, ".copilot") + out.extend(_copilot_sources(user_copilot, "tokeneconomizer")) + inst_root = os.path.join(user_copilot, "installed-plugins") + try: + for sub in sorted(os.listdir(inst_root)): + if os.path.isdir(os.path.join(inst_root, sub)): + out.extend(_copilot_sources(user_copilot, sub)) + except OSError: + pass + + if not market and len(parts) >= 6 and parts[-4] == "cache" and parts[-5] == "plugins": + market = parts[-3] + out.extend(_known_marketplace_sources(os.path.join(user_home, ".claude", "plugins"), market)) + out.append(os.path.join(_state_home(), "src")) + return out + + def _symlink_stub(plugin_root): """Where `lib/tokeneconomizer` points when git checked the symlink out as a plain file holding its target (Windows without symlink support): the directory holding the package.""" @@ -112,7 +326,8 @@ def core_path(): plugin_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) for cand in ([os.environ.get("TE_CORE_PATH"), os.path.join(plugin_root, "lib"), _symlink_stub(plugin_root), os.path.dirname(plugin_root)] - + _marketplace_sources(plugin_root)): + + _marketplace_sources(plugin_root) + + _extra_sources(plugin_root)): if cand and os.path.isfile(os.path.join(cand, "tokeneconomizer", "plugin", "hook.py")): return cand return None @@ -120,10 +335,10 @@ def core_path(): def _say_missing(plugin_root): """One line in the plugin's errors.log (not repeated) when the core cannot be found.""" - home = os.environ.get("TOKENECONOMIZER_HOME") or os.path.join(os.path.expanduser("~"), - ".tokeneconomizer") + home = _state_home() line = ("bootstrap: the tokeneconomizer package was not found for the plugin at %s; " - "install from the bundle (scripts/build_plugin.py) or set TE_CORE_PATH\n" % plugin_root) + "install from the bundle (scripts/build_plugin.py), clone into " + "~/.tokeneconomizer/src, or set TE_CORE_PATH\n" % plugin_root) path = os.path.join(home, "errors.log") try: if os.path.exists(path) and line in open(path, encoding="utf-8", errors="replace").read(): diff --git a/plugins/tokeneconomizer/plugin/slash-commands/config.md b/plugins/tokeneconomizer/plugin/slash-commands/config.md index f7e73dc..a045f97 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/config.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/config.md @@ -9,9 +9,20 @@ 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 +$meta = Join-Path $root 'bin\te.json' $OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding -& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path config $ARGUMENTS +if (Test-Path -LiteralPath $meta) { + $launcher = Get-Content -LiteralPath $meta -Raw -ErrorAction Stop | ConvertFrom-Json + & $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path config $ARGUMENTS +} elseif ($env:COPILOT_PLUGIN_ROOT -and (Test-Path -LiteralPath (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py'))) { + $py = if ($env:TE_PYTHON) { $env:TE_PYTHON } else { 'python' } + & $py -X utf8 (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py') cli --host copilot --cwd (Get-Location).Path config $ARGUMENTS +} else { + $err = Join-Path $root 'errors.log' + $detail = if (Test-Path -LiteralPath $err) { (Get-Content -LiteralPath $err -Tail 3) -join "`n" } else { "start a new chat session or install from a local clone / bundle so the hook writes $meta" } + [Console]::Error.WriteLine("TokenEconomizer is not initialized yet ($meta missing): $detail") + cmd /c exit 1 +} ``` Otherwise, run this command with the Bash tool: diff --git a/plugins/tokeneconomizer/plugin/slash-commands/facts.md b/plugins/tokeneconomizer/plugin/slash-commands/facts.md index 86efecc..e52657e 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/facts.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/facts.md @@ -7,9 +7,20 @@ 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 +$meta = Join-Path $root 'bin\te.json' $OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding -& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path microskills +if (Test-Path -LiteralPath $meta) { + $launcher = Get-Content -LiteralPath $meta -Raw -ErrorAction Stop | ConvertFrom-Json + & $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path microskills +} elseif ($env:COPILOT_PLUGIN_ROOT -and (Test-Path -LiteralPath (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py'))) { + $py = if ($env:TE_PYTHON) { $env:TE_PYTHON } else { 'python' } + & $py -X utf8 (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py') cli --host copilot --cwd (Get-Location).Path microskills +} else { + $err = Join-Path $root 'errors.log' + $detail = if (Test-Path -LiteralPath $err) { (Get-Content -LiteralPath $err -Tail 3) -join "`n" } else { "start a new chat session or install from a local clone / bundle so the hook writes $meta" } + [Console]::Error.WriteLine("TokenEconomizer is not initialized yet ($meta missing): $detail") + cmd /c exit 1 +} ``` Otherwise, run this command with the Bash tool: diff --git a/plugins/tokeneconomizer/plugin/slash-commands/microskills.md b/plugins/tokeneconomizer/plugin/slash-commands/microskills.md index 3aa504c..7531809 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/microskills.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/microskills.md @@ -7,9 +7,20 @@ 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 +$meta = Join-Path $root 'bin\te.json' $OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding -& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path microskills +if (Test-Path -LiteralPath $meta) { + $launcher = Get-Content -LiteralPath $meta -Raw -ErrorAction Stop | ConvertFrom-Json + & $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path microskills +} elseif ($env:COPILOT_PLUGIN_ROOT -and (Test-Path -LiteralPath (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py'))) { + $py = if ($env:TE_PYTHON) { $env:TE_PYTHON } else { 'python' } + & $py -X utf8 (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py') cli --host copilot --cwd (Get-Location).Path microskills +} else { + $err = Join-Path $root 'errors.log' + $detail = if (Test-Path -LiteralPath $err) { (Get-Content -LiteralPath $err -Tail 3) -join "`n" } else { "start a new chat session or install from a local clone / bundle so the hook writes $meta" } + [Console]::Error.WriteLine("TokenEconomizer is not initialized yet ($meta missing): $detail") + cmd /c exit 1 +} ``` Otherwise, run this command with the Bash tool: diff --git a/plugins/tokeneconomizer/plugin/slash-commands/repos.md b/plugins/tokeneconomizer/plugin/slash-commands/repos.md index e780f0f..09cba7f 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/repos.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/repos.md @@ -9,9 +9,20 @@ 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 +$meta = Join-Path $root 'bin\te.json' $OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding -& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path repos $ARGUMENTS +if (Test-Path -LiteralPath $meta) { + $launcher = Get-Content -LiteralPath $meta -Raw -ErrorAction Stop | ConvertFrom-Json + & $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path repos $ARGUMENTS +} elseif ($env:COPILOT_PLUGIN_ROOT -and (Test-Path -LiteralPath (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py'))) { + $py = if ($env:TE_PYTHON) { $env:TE_PYTHON } else { 'python' } + & $py -X utf8 (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py') cli --host copilot --cwd (Get-Location).Path repos $ARGUMENTS +} else { + $err = Join-Path $root 'errors.log' + $detail = if (Test-Path -LiteralPath $err) { (Get-Content -LiteralPath $err -Tail 3) -join "`n" } else { "start a new chat session or install from a local clone / bundle so the hook writes $meta" } + [Console]::Error.WriteLine("TokenEconomizer is not initialized yet ($meta missing): $detail") + cmd /c exit 1 +} ``` Otherwise, run this command with the Bash tool: diff --git a/plugins/tokeneconomizer/plugin/slash-commands/status.md b/plugins/tokeneconomizer/plugin/slash-commands/status.md index 3c71d19..cbde354 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/status.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/status.md @@ -7,9 +7,20 @@ 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 +$meta = Join-Path $root 'bin\te.json' $OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding -& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path status +if (Test-Path -LiteralPath $meta) { + $launcher = Get-Content -LiteralPath $meta -Raw -ErrorAction Stop | ConvertFrom-Json + & $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path status +} elseif ($env:COPILOT_PLUGIN_ROOT -and (Test-Path -LiteralPath (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py'))) { + $py = if ($env:TE_PYTHON) { $env:TE_PYTHON } else { 'python' } + & $py -X utf8 (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py') cli --host copilot --cwd (Get-Location).Path status +} else { + $err = Join-Path $root 'errors.log' + $detail = if (Test-Path -LiteralPath $err) { (Get-Content -LiteralPath $err -Tail 3) -join "`n" } else { "start a new chat session or install from a local clone / bundle so the hook writes $meta" } + [Console]::Error.WriteLine("TokenEconomizer is not initialized yet ($meta missing): $detail") + cmd /c exit 1 +} ``` Otherwise, run this command with the Bash tool: diff --git a/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md b/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md index 46b4f36..06ca2cd 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/toolprune.md @@ -9,9 +9,20 @@ 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 +$meta = Join-Path $root 'bin\te.json' $OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding -& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path toolprune $ARGUMENTS +if (Test-Path -LiteralPath $meta) { + $launcher = Get-Content -LiteralPath $meta -Raw -ErrorAction Stop | ConvertFrom-Json + & $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path toolprune $ARGUMENTS +} elseif ($env:COPILOT_PLUGIN_ROOT -and (Test-Path -LiteralPath (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py'))) { + $py = if ($env:TE_PYTHON) { $env:TE_PYTHON } else { 'python' } + & $py -X utf8 (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py') cli --host copilot --cwd (Get-Location).Path toolprune $ARGUMENTS +} else { + $err = Join-Path $root 'errors.log' + $detail = if (Test-Path -LiteralPath $err) { (Get-Content -LiteralPath $err -Tail 3) -join "`n" } else { "start a new chat session or install from a local clone / bundle so the hook writes $meta" } + [Console]::Error.WriteLine("TokenEconomizer is not initialized yet ($meta missing): $detail") + cmd /c exit 1 +} ``` Otherwise, run this command with the Bash tool: diff --git a/plugins/tokeneconomizer/plugin/slash-commands/untool.md b/plugins/tokeneconomizer/plugin/slash-commands/untool.md index 5ab36f6..4326178 100644 --- a/plugins/tokeneconomizer/plugin/slash-commands/untool.md +++ b/plugins/tokeneconomizer/plugin/slash-commands/untool.md @@ -9,9 +9,20 @@ 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 +$meta = Join-Path $root 'bin\te.json' $OutputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding -& $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path toolprune $ARGUMENTS +if (Test-Path -LiteralPath $meta) { + $launcher = Get-Content -LiteralPath $meta -Raw -ErrorAction Stop | ConvertFrom-Json + & $launcher.python -X utf8 $launcher.bootstrap cli --host copilot --cwd (Get-Location).Path toolprune $ARGUMENTS +} elseif ($env:COPILOT_PLUGIN_ROOT -and (Test-Path -LiteralPath (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py'))) { + $py = if ($env:TE_PYTHON) { $env:TE_PYTHON } else { 'python' } + & $py -X utf8 (Join-Path $env:COPILOT_PLUGIN_ROOT 'scripts\te_bootstrap.py') cli --host copilot --cwd (Get-Location).Path toolprune $ARGUMENTS +} else { + $err = Join-Path $root 'errors.log' + $detail = if (Test-Path -LiteralPath $err) { (Get-Content -LiteralPath $err -Tail 3) -join "`n" } else { "start a new chat session or install from a local clone / bundle so the hook writes $meta" } + [Console]::Error.WriteLine("TokenEconomizer is not initialized yet ($meta missing): $detail") + cmd /c exit 1 +} ``` Otherwise, run this command with the Bash tool: diff --git a/plugins/tokeneconomizer/pyproject.toml b/plugins/tokeneconomizer/pyproject.toml index 2f41947..cb72d48 100644 --- a/plugins/tokeneconomizer/pyproject.toml +++ b/plugins/tokeneconomizer/pyproject.toml @@ -8,7 +8,7 @@ version = "0.1.0" description = "Experience-driven black-box cost control for coding agents (Claude Code, Codex, Copilot CLI, Pi), as a plugin." readme = "README.md" requires-python = ">=3.10" -license = { text = "Apache-2.0" } +license = { text = "MIT" } authors = [{ name = "TokenEconomizer authors" }] keywords = ["llm-agents", "cost-optimization", "swe-bench", "token-economy"] diff --git a/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py b/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py index 34676d9..818131b 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py +++ b/plugins/tokeneconomizer/tokeneconomizer/loopguard/shell_edits.py @@ -251,6 +251,8 @@ def _bare(cmds): while tokens: if tokens[0] in _WRAPPERS: tokens = _past_wrapper(tokens) + elif tokens[0] == "rtk" and len(tokens) > 1: # trace.strip_rtk_prefix + tokens = tokens[2:] if tokens[1] == "proxy" and len(tokens) > 2 else tokens[1:] elif re.match(r"^\w+=", tokens[0]): tokens = tokens[1:] else: diff --git a/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py b/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py index cce521f..74c17d5 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py +++ b/plugins/tokeneconomizer/tokeneconomizer/loopguard/state.py @@ -10,7 +10,7 @@ import json import re -from ..trace import load_trajectory as _load_trajectory +from ..trace import load_trajectory as _load_trajectory, tool_kind # An output that RAN code to verify behavior (the test/repro step of the edit->test # loop). @@ -36,7 +36,7 @@ # Code's stream-json (which names tools Bash/Read/Edit/Write/Grep/Glob/MultiEdit). Unknown # names pass through unchanged. _TOOL_CANON = { - "bash": "bash", "shell": "bash", + "bash": "bash", "shell": "bash", "powershell": "bash", "read": "view", "view": "view", "grep": "grep", "glob": "glob", @@ -47,7 +47,7 @@ def canon_tool(name): - return _TOOL_CANON.get((name or "").lower(), name or "?") + return _TOOL_CANON.get(tool_kind(name), name or "?") def completed_calls(line, pend): @@ -185,7 +185,8 @@ def update(self, tool_name, args, result_text, failed=None): # 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")] + paths = [args.get("path") or args.get("filePath") or args.get("file_path") + or args.get("relative_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: diff --git a/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py b/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py index 5495c89..7475298 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py +++ b/plugins/tokeneconomizer/tokeneconomizer/loopguard/turn.py @@ -21,6 +21,7 @@ import shlex import time +from ..trace import RTK_WORDS from .rules import DEFAULT_THRESHOLDS, assess_abort, is_stuck, nudge_text from .shell_edits import (_split_heredocs, fold_shell_edits, shell_edit_targets, shell_revert_targets) @@ -38,13 +39,32 @@ # `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*))*)") +# A value of one of make's options or variables: a word, or a `$(...)`/`${...}` whose brackets +# `_pieces` has turned into spaces (`-j$(nproc)` reads `-j$ nproc`). +_MAKE_VALUE = r"(?:\$\s*\w+|[^\s\-]\S*)" VERIFY_RE = re.compile( r"(?i)(?:^|[\s;&|(])(?:(?:~?/)?(?:[\w.\-]+/)*" + _PYTHON + r"\s+)?" - r"(?:~?/)?(?:[\w.\-]+/)*(?:pytest|py\.test|tox|nox|" + _PYTHON + r"\s+-m\s+(?:pytest|unittest)|" + r"(?:~?/)?(?:[\w.\-]+/)*(?:pytest|py\.test|tox|nox|" + + _PYTHON + r"\s+-m\s+(?:pytest|unittest|tox|nox)|" + # coverage.py measuring a test run (`coverage run -m pytest`, `python -m coverage run + # manage.py test`), past its own options, of which these take a value + r"(?:-m\s+)?coverage\s+run(?:\s+(?:--(?:rcfile|source|omit|include|data-file|context|" + r"concurrency|debug|save-signal)(?:=|\s+)\S+|-[-\w]+))*\s+" + r"(?:-m\s+(?:pytest|unittest)|(?:[\w.\-]+/)*(?:manage\.py\s+test|runtests(?:\.py)?))|" 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|" + # make's own options and variables before the target (`make -j8 check`, `make -C build + # test`, `make V=1 test`, `make -j$(nproc) check`, whose `$(nproc)` reaches here as + # `$ nproc`). They are case-sensitive. `-C`, `-f`, `-I`, `-o` and `-W` always take a value, + # `-j` and `-l` may; the generic option does not also read one of them with its value, so + # a long line of options does not backtrack exponentially. + r"make(?-i:(?:\s+(?:-[CfIjloW]\s*" + _MAKE_VALUE + r"|" + r"--(?:directory|file|makefile|include-dir|jobs|load-average|old-file|assume-old|" + r"what-if|new-file|assume-new)\s+" + _MAKE_VALUE + r"|" + r"-(?![CfIoW]|[jl][^\s\-])[-\w]+(?:=(?:\$\s*\w+|\S*))?|\w+=(?:\$\s*\w+|\S*)))*)" + r"\s+(?:test|check)|" + r"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 @@ -68,16 +88,31 @@ # 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`, `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+)?|" +# `sudo -u bob`, `time -p`, and a launcher that runs it in the project's environment, `uv run +# pytest`, `npx jest`, `bundle exec rspec`. `command -v pytest` looks the runner up; only +# `command -p` runs it. +_PREFIX_RE = re.compile(r"^\s*(?:(?:\w+=\S*|nohup|command(?:\s+-p)?(?:\s+--)?|" + # time's options; `-f` and `-o` take a value + r"time(?:\s+(?:-[fo](?:\s+\S+|\S+)|--(?:format|output)(?:=|\s+)\S+|" + r"-[pvaq]+|--(?:portability|verbose|append|quiet)))*|" + r"exec(?:\s+(?:-a\s*[^\s-]\S*|-[cl]+))*(?:\s+--)?|" + # sudo's options; these letters and long forms take a value + r"sudo(?:\s+(?:-\w*[ugpCDRrtTU]\s*[^\s-]\S*|--(?:user|group|prompt|" + r"close-from|chdir|chroot|role|type|command-timeout|other-user)" + r"(?:=|\s+)\S+|-[-\w]*(?:=\S*)?))*|" + r"nice(?:\s+(?:-n\s*|--adjustment(?:=|\s+))?[-+]?\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*))+|" + # `conda run -n ml`, `mamba run -p ./env`, `micromamba run -r /opt -n ml`: + # the environment's name or path, and the other options that take a value + r"(?:conda|mamba|micromamba)\s+run(?:\s+(?:(?:-[npr]|--name|--prefix|" + r"--root-prefix|--cwd)(?:=|\s*)[^\s-]\S*|-[-\w]*))*|" r"(?:(?:uv|poetry|pipenv|pdm|hatch|rye)\s+run|npx|bunx|" r"(?:npm|pnpm|yarn)\s+(?:exec|dlx)|bundle\s+exec|xvfb-run)" r"(?:\s+-\S+)*|" + # rtk's prefix, `rtk pytest`, `rtk proxy npm test` (trace.RTK_WORDS) + + RTK_WORDS + r"(?=\s+\S)|" # `dotenv -e .env.local -- npx vitest run`: dotenv-cli's options, then `--` r"dotenv(?:\s+(?!--(?:\s|$))\S+)*\s+--)\s+)*") # What only reports on the run before it: `echo "exit=$?"`, `true`, `exit 0`. diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py index 2bb2629..ae42cec 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/distiller.py @@ -21,7 +21,7 @@ import re from ..names import repo_filename -from ..trace import call_cwds +from ..trace import SHELL_TOOLS, call_cwds, tool_kind from ..trace.claude import CONVERSATION from .lifecycle import Forgetting, Lifecycle, edited_files, edited_pyfiles, write_json_atomic @@ -66,7 +66,7 @@ def load_calls(fp): break if is_codex or is_copilot: from ..trace import load_trajectory - return [(name.lower(), args, out) + return [(tool_kind(name), args, out) for name, args, out, _ok in load_trajectory(fp)] except OSError: return [] @@ -107,13 +107,13 @@ def load_calls(fp): else: txt = cont if isinstance(cont, str) else json.dumps(cont) res[tid] = txt - return [(uses[t][0].lower(), uses[t][1], res.get(t, "")) for t in order] + return [(tool_kind(uses[t][0]), uses[t][1], res.get(t, "")) for t in order] def bash_cmds(calls): out = [] for tool, args, res in calls: - if tool in ("bash", "shell", "stop_bash"): + if tool in SHELL_TOOLS: out.append(((args.get("command") or args.get("cmd") or ""), res)) return out diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py index 6026073..fa125b7 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/envfacts.py @@ -183,8 +183,8 @@ def typed_ok(o): return form_worked(o) and not o.env -_RUN_WORDS = frozenset({"run", "npx", "uv", "uvx", "pipx", "poetry", "pipenv", "conda", "-m", - "python", "python3"}) +_RUN_WORDS = frozenset({"run", "npx", "uv", "uvx", "pipx", "poetry", "pipenv", "conda", + "micromamba", "-m", "python", "python3"}) def _repairs(form, a_form, intent): diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py index 85465db..7bae14c 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/lifecycle.py @@ -27,7 +27,7 @@ def edited_pyfiles(calls): fs = set() for tool, args, _ in calls: if tool in ("edit", "multiedit", "write", "create", "str_replace_editor"): - p = args.get("file_path") or args.get("path") or "" + p = args.get("file_path") or args.get("path") or args.get("relative_path") or "" if p.endswith(".py"): fs.add(os.path.basename(p)) elif tool == "apply_patch": @@ -43,7 +43,7 @@ def edited_files(calls): fs = set() for tool, args, _ in calls: if tool in ("edit", "multiedit", "write", "create", "str_replace_editor"): - p = args.get("file_path") or args.get("path") or "" + p = args.get("file_path") or args.get("path") or args.get("relative_path") or "" if p: fs.add(os.path.basename(p)) elif tool == "apply_patch": diff --git a/plugins/tokeneconomizer/tokeneconomizer/microskills/observe.py b/plugins/tokeneconomizer/tokeneconomizer/microskills/observe.py index f916330..883c3dc 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/microskills/observe.py +++ b/plugins/tokeneconomizer/tokeneconomizer/microskills/observe.py @@ -15,7 +15,7 @@ import re from dataclasses import dataclass -from ..trace import call_cwds, load_trajectory, strip_rtk_prefix +from ..trace import SHELL_TOOLS, call_cwds, load_trajectory, strip_rtk_prefix, tool_kind from .lifecycle import edited_files, edited_pyfiles @@ -98,7 +98,24 @@ class Vocabulary: GIT_FETCH_SUBS = frozenset({"fetch", "clone", "pull", "ls-remote"}) GIT_PROBE_SUBS = frozenset({"remote", "branch", "tag", "fsck", "stash", "show-ref", "for-each-ref"}) -PREFIX_HEADS = ("sudo", "env", "time", "exec", "nice", "nohup", "timeout") +# Wrappers a command can be typed behind, each with its options that take a value: `sudo -u bob +# pytest` and `nice -n 10 pytest` are pytest runs, not a command named `-u` or `-n`. +# loopguard/shell_edits.py keeps the same table for the edits it reads (`_WRAPPERS`). +PREFIX_HEADS = { + "sudo": frozenset({"-u", "-g", "-p", "-C", "-D", "-R", "-r", "-t", "-T", "-U", "--user", + "--group", "--prompt", "--close-from", "--chdir", "--chroot", "--role", + "--type", "--command-timeout", "--other-user"}), + "env": frozenset({"-u", "-C", "-S", "--unset", "--chdir", "--split-string"}), + "time": frozenset({"-f", "-o", "--format", "--output"}), + "exec": frozenset({"-a"}), + "nice": frozenset({"-n", "--adjustment"}), + "nohup": frozenset(), + "timeout": frozenset({"-s", "-k", "--signal", "--kill-after"}), +} +# `env` options that change the environment or the directory the command runs in, which the +# command's form leaves out, as it leaves out a `VAR=value`. +_ENV_CHANGES_RE = re.compile(r"^(?:-$|-[a-zA-Z0-9]*[iuCS]|" + r"--(?:ignore-environment|unset|chdir|split-string)\b)") _PASSTHROUGH = frozenset({"cd", "echo", "head", "tail", "cat", "sort", "uniq", "tee", "true", "printf", "less", "more"}) @@ -106,9 +123,20 @@ class Vocabulary: _CD_RE = re.compile(r"^cd\s+(['\"]?)([^\s;&|'\"]+)\1\s*$") _CD_FAILED_RE = re.compile(r"\bcd: [^\n]*: (?:No such file or directory|Not a directory)") _CONDA_ACTIVATE_RE = re.compile(r"^(?:conda|mamba)\s+activate\s+([\w.-]+)\s*$") -_CONDA_RUN_RE = re.compile(r"^(?:conda|mamba)\s+run\s+(?:--no-capture-output\s+|--live-stream\s+)*" - r"(?:-n|--name)\s+([\w.-]+)\s+") -_TOOL_RUN_RE = re.compile(r"^(poetry|pipenv|uv|npx|bundle|yarn|pnpm)\s+(?:run|exec)\s+") +# The environment by name (`-n ml`) or by path (`-p ./env`); micromamba takes the same options. +_CONDA_RUN_RE = re.compile(r"^(conda|mamba|micromamba)\s+run\s+" + r"(?:--no-capture-output\s+|--live-stream\s+)*" + r"(?:(?:-n|--name)(?:\s+|=)([\w.-]+)|" + r"(?:-p|--prefix)(?:\s+|=)([^\s;&|'\"]+))\s+") +_TOOL_RUN_RE = re.compile(r"^(poetry|pipenv|uv|pdm|hatch|rye|npx|bundle|yarn|pnpm)\s+(?:run|exec)\s+") +# A Python launcher's own options before the command (`uv run --frozen --extra test pytest`), of +# which these take a value; a bare `--` ends them. They stay in the form: an extra, a group or a +# `--with` is often what makes the command work. +_PY_LAUNCHERS = frozenset({"poetry", "pipenv", "uv", "pdm", "hatch", "rye"}) +_RUN_OPTION_RE = re.compile(r"^(?:((?:--with(?:-editable|-requirements)?|--extra|" + r"--(?:only-|no-)?group|--python|-p|--package|--project|--directory|" + r"--env-file|--index|--pyproject)(?:=|\s+)[^\s-]\S*|" + r"--?[A-Za-z][\w-]*(?:=\S+)?)|--)\s+") _NPX_RE = re.compile(r"^npx\s+(?:(?:--yes|-y|--no-install|--no)\s+)*") # Launchers that fetch and run a Python tool in a throwaway environment (generic reading only). _TOOL_LAUNCH_RE = re.compile(r"^(uvx|uv\s+tool\s+run|pipx\s+run)\s+") @@ -340,12 +368,20 @@ def classify_command(cmd, call_index=0, vocab=None, cwd="", root=None, top=None) body = seg m = _CONDA_RUN_RE.match(body) if m: - prefix = (prefix + " " if prefix else "") + f"conda run -n {m.group(1)}" + launcher = "micromamba" if m.group(1) == "micromamba" else "conda" + env = f"-n {m.group(2)}" if m.group(2) else f"-p {m.group(3)}" + prefix = (prefix + " " if prefix else "") + f"{launcher} run {env}" body = body[m.end():] m = _TOOL_RUN_RE.match(body) if m: - prefix = (prefix + " " if prefix else "") + f"{m.group(1)} run" + launcher = [f"{m.group(1)} run"] body = body[m.end():] + while m.group(1) in _PY_LAUNCHERS and (o := _RUN_OPTION_RE.match(body)): + body = body[o.end():] + if o.group(1) is None: # `--`: the command follows + break + launcher.append(" ".join(o.group(1).split())) + prefix = (prefix + " " if prefix else "") + " ".join(launcher) else: m = _NPX_RE.match(body) if m and m.end() > 0: @@ -360,11 +396,15 @@ def classify_command(cmd, call_index=0, vocab=None, cwd="", root=None, top=None) if _ASSIGN_TOKEN_RE.match(toks[0]): # `env VAR=value cmd` assigned, toks = True, toks[1:] else: - toks = toks[1:] if toks[0] != "timeout" else toks[2:] + rest = _past_prefix(toks) + if toks[0] == "env" and any(_ENV_CHANGES_RE.match(t) + for t in toks[1:len(toks) - len(rest)]): + assigned = True # `env -u VAR cmd`, `env -i cmd` + toks = rest if not toks: continue head = toks[0] - base = head.rsplit("/", 1)[-1] + base = _command_base(head) rest = toks[1:] o = _classify(head, base, rest, body, prefix, seg, call_index, vocab) if o is not None: @@ -373,6 +413,30 @@ def classify_command(cmd, call_index=0, vocab=None, cwd="", root=None, top=None) return obs +def _past_prefix(toks): + """The words after a wrapper such as `sudo` or `timeout`: past its own options (`-u bob`, + `-Eu bob`, `-n10`, `--signal KILL`, `--`) and, for `timeout`, the duration.""" + takes_value = PREFIX_HEADS[toks[0]] + i = 1 + while i < len(toks) and toks[i].startswith("-"): + t = toks[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 toks[0] == "timeout": + i += 1 + return toks[i:] + + def _runner_script(rest, vocab): for t in rest: if t.startswith("-"): @@ -384,15 +448,45 @@ def _runner_script(rest, vocab): return None +# coverage.py's `run` options that take a value (`--source pkg`); the others are flags. +_COVERAGE_VALUE_OPTS = frozenset({"--rcfile", "--source", "--omit", "--include", "--data-file", + "--context", "--concurrency", "--debug", "--save-signal"}) + + +def _coverage_target(args, vocab): + """What `coverage run ` runs, when it is a test runner: `-m pytest`, `manage.py` + (given `test`) or a runner script; None for anything else.""" + i = 0 + while i < len(args) and args[i].startswith("-") and args[i] != "-m": + i += 2 if args[i] in _COVERAGE_VALUE_OPTS else 1 + if args[i:i + 1] == ["-m"]: + mod = args[i + 1] if i + 1 < len(args) else "" + return f"-m {mod}" if mod in vocab.runner_modules else None + script = _runner_script(args[i:i + 1], vocab) + if script and (script != "manage.py" or "test" in args[i + 1:]): + return script + return None + + def _classify(head, base, rest, body, prefix, seg, call, vocab): def form(expr): return (prefix + " " + expr).strip() if prefix else expr + if base == "coverage" and rest[:1] == ["run"]: # `coverage run -m pytest` + target = _coverage_target(rest[1:], vocab) + if target: + return Observation(call, "run_tests", form(f"{head} run {target}"), head, prefix, seg) if base in vocab.interpreters or _INTERP_VERSIONED_RE.match(base): if rest and all(t in ("--version", "-V", "-VV", "-v") for t in rest): return Observation(call, "probe_env", form(head), head, prefix, seg) if "-m" in rest: mod = rest[rest.index("-m") + 1] if rest.index("-m") + 1 < len(rest) else "" + after = rest[rest.index("-m") + 2:] + if mod == "coverage" and after[:1] == ["run"]: # `python -m coverage run -m pytest` + target = _coverage_target(after[1:], vocab) + if target: + return Observation(call, "run_tests", form(f"{head} -m coverage run {target}"), + head, prefix, seg) if mod in vocab.runner_modules: return Observation(call, "run_tests", form(f"{head} -m {mod}"), head, prefix, seg) # `python -m mypy` runs the checker itself, not the interpreter. @@ -611,9 +705,9 @@ def observe_task(transcript_path, vocab=None): triples = [] env_calls = [] for idx, (name, args, out, ok) in enumerate(calls): - tool = (name or "").lower() + tool = tool_kind(name) triples.append((tool, args if isinstance(args, dict) else {}, out or "")) - if tool not in ("shell", "bash", "stop_bash"): + if tool not in SHELL_TOOLS: continue cmd = (args.get("command") or args.get("cmd") or "") if isinstance(args, dict) else "" out = out or "" @@ -717,6 +811,13 @@ def _base(path): return (path or "").replace("\\", "/").rsplit("/", 1)[-1] +def _command_base(head): + """The command a segment's head names: its last path part, less a Windows `.exe`, so + `C:\\Python312\\python.exe` and `.venv/bin/python` are both the `python` interpreter.""" + base = _base(head) + return base[:-4] if base.lower().endswith(".exe") else base + + def _not_found_name(line): """The command a "not found" line says is missing, by its last path part; "" if none.""" m = _NOT_FOUND_NAME_RE.search(line or "") diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/adapter.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/adapter.py index b75b502..73414e7 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/adapter.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/adapter.py @@ -35,7 +35,8 @@ # Tools a person relies on in an interactive session, beyond the benchmark work surface. INTERACTIVE_PROTECTED = frozenset({ - "Bash", "Read", "Edit", "MultiEdit", "Write", "Grep", "Glob", "LS", "NotebookRead", + "Bash", "PowerShell", "Read", "Edit", "MultiEdit", "Write", "Grep", "Glob", "LS", + "NotebookRead", "BashOutput", "KillShell", "KillBash", "AskUserQuestion", "EnterPlanMode", "ExitPlanMode", "TodoWrite", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "TaskOutput", "TaskStop", diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py index f0a66f7..d1698b3 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/cli.py @@ -30,7 +30,8 @@ it by itself) te history [import --status] what that import did here te repos every repository with state here: how it was identified, - its agents and sessions, the checkouts seen + its agents and sessions, the checkouts seen, and the + tools left out of each one's settings te repos migrate send state recorded under earlier keys where it belongs now (runs by itself, once, after an upgrade) te repos merge KEY [INTO] merge the state directory KEY into INTO (default: this @@ -751,7 +752,10 @@ def cmd_history(args): res = history.run(ctx, auto=args.auto, log=lambda line: print(line, flush=True)) if args.auto: return 0 - if res["state"] in ("refused", "skipped", "busy"): + if res["state"] in ("refused", "skipped", "busy", "error"): + # "error" is a fatal error inside the import: `run` recorded the reason + # and left no `imported` count, so it is reported like the other + # failure states rather than read as one. print(f"not imported: {res['reason']}") return 1 print(f"imported {res['imported']} earlier session(s) of {ctx.repo.label}" @@ -851,8 +855,15 @@ def cmd_repos(args): elif row["cwds"]: print(" ran in " + ", ".join(row["cwds"][:3]) + (f" (+{len(row['cwds']) - 3})" if len(row["cwds"]) > 3 else "")) + for h, by_path in sorted(row["pruned"].items()): + for path, n in by_path.items(): + print(f" left out {h} {n} {denylist.unit(h, plural=n != 1)}" + + (f" in {path}" if path else "")) for n in row["notes"]: print(f" note {n}") + if any(row["pruned"] for row in rows): + print("\n`te toolprune show` in a checkout lists what was left out there, and " + "`te toolprune restore` gives it back") if merged: print(f"\n{merged} earlier state director{'y' if merged == 1 else 'ies'} merged into " f"the above, kept under {os.path.join(root, 'merged')}") diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py index 1377204..369bac9 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/config.py @@ -41,6 +41,12 @@ * toolprune_quiet_minutes -- how long every session of the repository must have been idle before `auto` writes a deny list (0: at once), so that no conversation resumed with a warm prompt cache loses it; + * tool_roles -- tools the mechanisms do not know by name, each given the role + of a built-in one, comma-separated `tool=role` (a tool may be + a pattern; role: shell, edit or read), such as an MCP server's + edit tool (`mcp__serena__replace_content=edit`): micro-skills + read a shell tool's commands and every mechanism counts an + edit tool's file as edited; * loopguard_aggr -- the guard's threshold preset; * loopguard_nudges -- redirects per prompt-turn before the guard only notifies; * loopguard. -- one guard threshold, pinned over the preset and over what the @@ -95,6 +101,8 @@ import os from dataclasses import asdict, dataclass, field, fields +from ..trace import TOOL_ROLES, parse_tool_role + 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). @@ -189,6 +197,7 @@ class LiveConfig: toolprune_sessions: int = 5 toolprune_quiet_minutes: int = 60 toolprune_protect: list = field(default_factory=list) + tool_roles: list = field(default_factory=list) loopguard: str = "nudge" loopguard_aggr: str = "default" loopguard_nudges: int = 1 @@ -294,6 +303,12 @@ 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 == "tool_roles": + bad = [e for e in v if parse_tool_role(e) is None] + if bad: + self.warnings.append(f"{source}: tool_roles {bad!r} not `tool=role` with a role " + f"in {tuple(TOOL_ROLES)}") + return False if key == "local_roles": bad = [r for r in v if r not in LOCAL_ROLES] if bad: @@ -354,7 +369,7 @@ def _set_threshold(self, name, value, source): "TE_TOOLPRUNE_QUIET_MINUTES": "toolprune_quiet_minutes", "TE_TOOLPRUNE_MIN_SESSIONS": "toolprune_min_sessions", "TE_TOOLPRUNE_SESSIONS": "toolprune_sessions", - "TE_TOOLPRUNE_PROTECT": "toolprune_protect", + "TE_TOOLPRUNE_PROTECT": "toolprune_protect", "TE_TOOL_ROLES": "tool_roles", "TE_LOOPGUARD": "loopguard", "TE_LOOPGUARD_AGGR": "loopguard_aggr", "TE_LOOPGUARD_NUDGES": "loopguard_nudges", "TE_REPOMAP": "repomap", "TE_REPOMAP_TOKENS": "repomap_tokens", diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/context.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/context.py index 85865d3..7308998 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/context.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/context.py @@ -4,6 +4,7 @@ import sys from dataclasses import dataclass +from ..trace import set_tool_roles from . import repos from .config import LiveConfig, load_config from .paths import RepoId, repo_identity, repo_state_dir, state_root @@ -54,6 +55,7 @@ def build(cls, host, cwd, env=None, session_id=None, settle=True): ctx = cls(host=host, repo=repo, root=root, store=Store(base), config=load_config(root, repo_dir=os.path.dirname(base), env=env), env=env, unsettled=unsettled) + set_tool_roles(ctx.config.tool_roles) if settle: ctx.settle() return ctx @@ -69,6 +71,7 @@ def settle(self): # A merge may have brought this repository its settings file. self.config = load_config(self.root, repo_dir=os.path.dirname(self.store.base), env=self.env) + set_tool_roles(self.config.tool_roles) def spawn(self, argv, log_name): """Run `te ` for this host and repository in a detached process, its output diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py index cd338f7..5eacd9a 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/controller.py @@ -28,12 +28,20 @@ import traceback from .. import loopguard +from ..trace import droid as droid_trace from . import denylist, fold, history, hookqueue, repomap, repos, sidecall from .hosts import merge_outputs from .paths import ensure_launcher TURN_HISTORY = 200 +# Droid versions whose PostToolUse drops failed tool calls (#231), as [first, +# past-last): 1.12.0 and 1.12.1 are the versions verified to drop them. 0.233.0 +# still dispatches failures, and a later release may restore the dispatch, so the +# range is bounded rather than open-ended: outside it the log is never read for +# failures, and a failure PostToolUse already folded is never counted twice. +_DROID_DROPS_FAILURES = ((1, 12, 0), (1, 13, 0)) + class LiveController: def __init__(self, ctx, payload): @@ -306,6 +314,16 @@ def user_prompt(self): # outcome is unknown, so it is recorded but does not feed the envelope. self._close_turn(s, stopped_normally=False) s["turn"] = loopguard.TurnGuard(turn_key=self.host.turn_key(self.p)).to_dict() + if self.host.name == "droid": + # The log's calls so far belong to turns already closed: the new turn + # reconciles only what comes after this mark (#231). Only a Droid that drops + # failed calls has its log read here. + path = self._droid_log(s) + try: + s["droid_log_seen"] = len(droid_trace.droid_session_calls(path)) \ + if path else 0 + except OSError: + s.pop("droid_log_seen", None) self._save(s) return merge_outputs(*outputs) if outputs else {} @@ -313,12 +331,64 @@ def stop(self): if self.cfg.loopguard == "off" or self.p.get("stop_hook_active"): return {} s = self._session() + data = s.get("turn") + if data: + g = loopguard.TurnGuard(data=data) + self._reconcile_droid_failures(s, g) + s["turn"] = g.to_dict() summary = self._close_turn(s, stopped_normally=self.host.stopped_normally(self.p)) if summary: self._log("turn", **summary) self._save(s) return {} + def _droid_log(self, s): + """This Droid session's log -- the payload's transcript, else the one the session + state kept from an earlier hook -- when it was written by a Droid whose PostToolUse + drops failed calls (#231); "" otherwise, so other versions never read it.""" + if self.host.name != "droid": + return "" + path = self.host.transcript(self.p) or (s or {}).get("transcript") or "" + if not path or not os.path.exists(path): + return "" + version = droid_trace.droid_version(path) + if version is None or not (_DROID_DROPS_FAILURES[0] <= version < _DROID_DROPS_FAILURES[1]): + return "" + return path + + def _reconcile_droid_failures(self, s, g, thr=None): + """Fold the failed calls of this Droid session that PostToolUse never + delivered (#231): on Droid 1.12.x it fires only for successes, so a failed + call is invisible to the live guard unless the session log is read. Only the + failures are folded -- a success in the log already has its own hook, or is + about to get one. `s["droid_log_seen"]` counts the log's calls already + accounted for, so a failure is folded exactly once across the session's + hooks. Judge-free and envelope-free, with the backstop nulled: the fold + only accumulates the failure signals, and the call that follows (or the + turn's close) decides on them -- a reconcile never spends a nudge or an + abort itself.""" + path = self._droid_log(s) + if not path: + return + try: + calls = droid_trace.droid_session_calls(path) + except OSError: + return + seen = s.get("droid_log_seen") + if not isinstance(seen, int) or seen < 0: + # No turn opened one (a resumed session, or a turn whose UserPromptSubmit + # the plugin never saw): skip what came before rather than pulling an + # old turn's failures into this one. + seen = len(calls) + for name, args, text, ok in calls[seen:]: + if ok: + continue + g.fold(name, args, text, 1, + envelope=None, + thr=dict(thr, backstop_turns=None) if thr is not None else None, + judge=None) + s["droid_log_seen"] = len(calls) + # ---- PostToolUse --------------------------------------------------------------------- def _judge(self, thr, envelope): """The stuck judge, run in the background (`judge.AsyncJudge`): with the guard on, it @@ -368,6 +438,10 @@ def post_tool(self): # agents ran under a turn cap, hence their envelope gate). thr = dict(thr, gate_over_envelope=False, gate_min_turns=max(thr["gate_min_turns"], thr["min_turns"])) + # On Droid 1.12.x PostToolUse fires only for successes, so a failed call + # never reaches this fold: recover the failures the session log shows + # before judging this call, or the judge never wakes on a failure loop. + self._reconcile_droid_failures(s, g, thr) decision = g.fold(name, args, text, code, envelope=envelope, thr=thr, judge=self._judge(thr, envelope), nudge_budget=self.cfg.loopguard_nudges) diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py index efe98b7..1e64ad6 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/fold.py @@ -187,8 +187,10 @@ def _fold_toolprune(ctx, adapter, run_dir, session_id, transcript=None, workdir= stage.catalog_desc = dict(st.get("catalog_desc") or {}) applied = denylist.applied_for(ctx.store, ctx.repo.root, ctx.host.name) kept = set(denylist.kept_for(ctx.store, ctx.repo.root, ctx.host.name)) # given back - # The mask this session actually ran under: none, for one from before the plugin. - stage._exclude_tools = [] if imported else list(applied) + # Read the session's catalog even when it ran under a deny list. The stage skips a masked + # session's catalog, but here the catalog is only ever added to, so a shorter list removes + # nothing, and skipping it would keep out every tool that first appears later. + stage._exclude_tools = [] # A tool that has since become protected (the web tools, from this version on) comes back: # remove the plugin's OWN deny rule for it. Only rules it recorded adding, never one the # person wrote, and only in the direction of giving a tool back. @@ -233,8 +235,8 @@ def _fold_toolprune(ctx, adapter, run_dir, session_id, transcript=None, workdir= doc = {"used_tools": sorted(stage.used_tools), "streaks": stage.tool_unused_streaks, "prompt_streaks": prompt_streaks, "catalog_tools": sorted(stage.catalog_tools), "catalog_desc": stage.catalog_desc, - # A session run under an applied mask parses no catalog (the stage skips it, as the - # masked list is not the full one); the last source still describes the catalog. + # A session with no tool call and no catalog parses none; the last source still + # describes the catalog. "catalog_source": srow.get("untool_catalog_source") or st.get("catalog_source"), "sessions": sessions, "prompts": int(st.get("prompts", 0)) + (prompts or 0), "updated": time.time()} diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py index 5b0b8e4..7a541e5 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/paths.py @@ -23,6 +23,8 @@ HOME_ENV = "TOKENECONOMIZER_HOME" # Names the repository of a session whose directory holds no git metadata, by its remote URL. REPO_ENV = "TOKENECONOMIZER_REPO" +# A flag rather than `os.name` at the call, so the tests can write the Windows launcher anywhere. +_WINDOWS = os.name == "nt" def state_root(env=None): @@ -64,32 +66,45 @@ def ensure_launcher(env=None): 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 + import sys env = os.environ if env is None else env plugin = env.get("TE_PLUGIN_ROOT") target = os.path.join(plugin, "scripts", "te") if plugin else "" if not target or not os.access(target, os.X_OK): return 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)) + head = ("#!/bin/sh\n# Written by the TokenEconomizer plugin at session start: its `te` " + "command line.\n") + body = head + "exec %s \"$@\"\n" % shlex.quote(target) launchers = {path: body} - if os.name == "nt": + if _WINDOWS: import json - import sys - launchers[path + ".json"] = json.dumps({ - "python": sys.executable, - "bootstrap": os.path.join(plugin, "scripts", "te_bootstrap.py"), - }) + "\n" + bootstrap = os.path.join(plugin, "scripts", "te_bootstrap.py") + launchers[path + ".json"] = json.dumps({"python": sys.executable, + "bootstrap": bootstrap}) + "\n" + if sys.executable: + # The shell omp runs commands in cannot `exec` a backslash path, and refuses the + # `cd` inside `$(...)` that `scripts/te` finds its own directory with (#167). So + # `te` runs what te.json names, with forward slashes: the Python the hook runs under + # (not one chosen again by TE_PYTHON at each run) and the package it imported. + core = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + launchers[path] = head + ('[ -n "${TE_CORE_PATH:-}" ] || TE_CORE_PATH=%s\n' + "export TE_CORE_PATH PYTHONUTF8=1\n" + 'exec %s %s cli "$@"\n') % tuple( + shlex.quote(p.replace("\\", "/")) for p in (core, sys.executable, bootstrap)) for launcher, body in launchers.items(): try: - with open(launcher, encoding="utf-8") as fh: + # newline="": a launcher an earlier version wrote with CRLF does not compare equal. + with open(launcher, encoding="utf-8", newline="") 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: + # newline="\n": text mode on Windows would end each line with CRLF, and `sh` would pass + # the trailing "\r" on as an argument. + with open(tmp, "w", encoding="utf-8", newline="\n") as fh: fh.write(body) os.chmod(tmp, 0o700) os.replace(tmp, launcher) diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/repos.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/repos.py index e6a05ff..424f71f 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/repos.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/repos.py @@ -32,6 +32,7 @@ import traceback from ..names import repo_filename +from . import denylist from . import hosts as hosts_mod from .paths import (BY_PATH, BY_REMOTE, RepoId, _slug, digest, home_dir, is_git_entry, normalize_remote, origin_url, repo_identity, state_root) @@ -812,7 +813,8 @@ def ignored_git_entries(cwd, env=None): def listing(root, env=None, current=None): - """One row per state directory: identity, agents and sessions, checkouts, notes.""" + """One row per state directory: identity, agents and sessions, checkouts, what tool pruning + left out where, notes.""" idx = Store(root).read(INDEX) or {} checkouts = {} for path, v in (idx.get("checkouts") or {}).items(): @@ -828,9 +830,14 @@ def listing(root, env=None, current=None): if not os.path.isdir(d): continue doc = Store(d).read("repo.json") or {} - agents, imported, cwds, last = {}, {}, set(), 0.0 + agents, imported, cwds, last, pruned = {}, {}, set(), 0.0, {} for h in _host_dirs(d): st = Store(os.path.join(d, h)) + # What the deny list wrote, per settings file: which checkouts are missing tools, + # without running a command in each one (#219). + by_path = denylist.applied_by_path(st.read(denylist.APPLIED) or {}) + if any(by_path.values()): + pruned[h] = {p: len(t) for p, t in sorted(by_path.items()) if t} sess = _sessions(st) folded = st.read("folded.json") or {} # Sessions imported from the agent's history are counted apart. @@ -855,6 +862,7 @@ def listing(root, env=None, current=None): rows.append({"key": key, "label": doc.get("label") or dir_label(d) or key, "how": doc.get("how", ""), "remote": doc.get("remote", ""), "agents": agents, "imported": imported, "last": last, "state": d, + "pruned": pruned, "checkouts": sorted(checkouts.get(key, [])), "cwds": sorted(cwds), "current": bool(current and current.key == key), "notes": notes}) try: diff --git a/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py b/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py index 3589b30..f9e6d9d 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py +++ b/plugins/tokeneconomizer/tokeneconomizer/plugin/sidecall.py @@ -274,6 +274,16 @@ def claude_no_mcp(cli, cwd): return ["--strict-mcp-config", "--mcp-config", path] +def claude_safe_mode(cli): + """`--safe-mode` when this Claude Code has it: a side call starts without the person's + customizations -- CLAUDE.md, installed plugins and their hooks, skills, output styles -- + which it would otherwise load, pay for on every judge and proposer call, and run its hooks + inside (#162). Auth, model selection and the settings file's `env` still apply (verified on + 2.1.329), so a provider set there is still the one called. Not for the catalog probes, which + measure the person's real session.""" + return ["--safe-mode"] if "--safe-mode" in _claude_help(cli) else [] + + def claude_json(stdout): """The result object of a `claude -p --output-format json` run, {} when there is none. With `"verbose": true` in the person's settings (or `--verbose`), Claude Code prints the whole @@ -296,6 +306,7 @@ def claude_call(prompt, model="haiku", cli=None, timeout=TIMEOUT_S, effort=""): # `--mcp-config` takes several values, so an option follows it, never a bare argument. cmd = ([cli, "-p", "--output-format", "json", "--max-turns", "1", "--tools", ""] + claude_no_mcp(cli, cwd) + ["--model", model or "haiku"] + claude_flags(cli) + + claude_safe_mode(cli) + (["--effort", effort] if effort and "--effort" in _claude_help(cli) else [])) out = subprocess.run(cmd, input=prompt, capture_output=True, encoding="utf-8", errors="replace", timeout=timeout, env=_env(), @@ -346,8 +357,8 @@ def codex_call(prompt, model="", cli="codex", timeout=TIMEOUT_S, effort=""): eff, _ = accounting.effective({ "input_tokens": max(0, inp - cached - cw), "cache_read_input_tokens": cached, "cache_creation_input_tokens": cw, - "output_tokens": int(usage.get("output_tokens") or 0) - + int(usage.get("reasoning_output_tokens") or 0), + # Codex's output_tokens already holds its reasoning_output_tokens. + "output_tokens": int(usage.get("output_tokens") or 0), "model": model or "codex"}) return text, eff @@ -428,10 +439,14 @@ def opencode_call(prompt, model="", cli="opencode", timeout=TIMEOUT_S): env = dict(_env(), OPENCODE_CONFIG_CONTENT=OPENCODE_CONFIG) exe = program(cli) with tempfile.TemporaryDirectory(prefix="te-side-", ignore_cleanup_errors=True) as cwd: + # The message goes on stdin, never on argv: Windows stops a command line at 32,767 + # characters, and the proposer's prompt (eight task digests plus the facts) outgrows + # that -- CreateProcess failed with WinError 206 before a session existed. `opencode + # run` reads the message from stdin when it is given none (opencode 2.3.0). out = subprocess.run([*exe, "run", *opencode_flags(cli), "--format", "json", - *model_args, prompt], - capture_output=True, encoding="utf-8", errors="replace", - timeout=timeout, env=env, cwd=cwd, stdin=subprocess.DEVNULL) + *model_args], + input=prompt, capture_output=True, encoding="utf-8", + errors="replace", timeout=timeout, env=env, cwd=cwd) text, usage, sid = trace.opencode_run_reply(out.stdout) if sid: try: diff --git a/plugins/tokeneconomizer/tokeneconomizer/pricing.py b/plugins/tokeneconomizer/tokeneconomizer/pricing.py index 09ebff0..9e14a3d 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/pricing.py +++ b/plugins/tokeneconomizer/tokeneconomizer/pricing.py @@ -108,6 +108,10 @@ "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), + # Added 2026-11-19 from the same page: gpt-6.2-astra $8.00 in / $0.40 cached / $40 out and + # gpt-6.2-sol $2.00 / $0.10 / $10, so both bill a cache hit at 0.05x input like gpt-6.1-sol. + "gpt-6.2-astra": dict(input=1.0, cache_read=0.05, cache_write=1.25, output=5.0), + "gpt-6.2-sol": 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. diff --git a/plugins/tokeneconomizer/tokeneconomizer/toolprune/tools.py b/plugins/tokeneconomizer/tokeneconomizer/toolprune/tools.py index a90b706..9566f17 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/toolprune/tools.py +++ b/plugins/tokeneconomizer/tokeneconomizer/toolprune/tools.py @@ -44,7 +44,7 @@ # Codex's complete native work surface (fixed; neither schema is removable). "shell", "apply_patch", # Claude Code work-surface names: - "Bash", "Edit", "Write", "Read", "Grep", "Glob", "MultiEdit", + "Bash", "PowerShell", "Edit", "Write", "Read", "Grep", "Glob", "MultiEdit", }) diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py b/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py index f9d0de0..19eed60 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/__init__.py @@ -12,7 +12,9 @@ Stdlib only. """ -from .calls import RTK_PREFIX_RE, call_cwds, load_trajectory, strip_rtk_prefix, tool_usage +from .calls import (RTK_PREFIX_RE, RTK_WORDS, SHELL_TOOLS, TOOL_ROLES, call_cwds, + load_trajectory, parse_tool_role, set_tool_roles, strip_rtk_prefix, + tool_kind, tool_usage) from .catalog import (CODEX_DEFAULT_TOOL_CATALOG, catalog_sources, parse_catalog, parse_catalog_with_source, parse_tool_catalog, parse_tool_catalog_claude, parse_tool_catalog_flat, parse_tool_names_copilot) @@ -31,8 +33,9 @@ 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) + droid_safe_session_id, droid_session_calls, droid_session_header, + droid_session_to_claude, droid_session_usage, droid_sessions, + droid_version) 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, @@ -44,7 +47,8 @@ pi_session_to_claude, pi_session_usage) __all__ = [ - "RTK_PREFIX_RE", "call_cwds", "load_trajectory", "strip_rtk_prefix", "tool_usage", + "RTK_PREFIX_RE", "RTK_WORDS", "SHELL_TOOLS", "TOOL_ROLES", "call_cwds", "load_trajectory", + "parse_tool_role", "set_tool_roles", "strip_rtk_prefix", "tool_kind", "tool_usage", "CODEX_DEFAULT_TOOL_CATALOG", "catalog_sources", "parse_catalog", "parse_catalog_with_source", "parse_tool_catalog", "parse_tool_catalog_claude", "parse_tool_catalog_flat", "parse_tool_names_copilot", diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/calls.py b/plugins/tokeneconomizer/tokeneconomizer/trace/calls.py index b8ce150..dd70354 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/calls.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/calls.py @@ -6,6 +6,7 @@ session are converted into one of these first (`codex.codex_rollout_to_exec`, `pi.pi_session_to_claude`). """ +import fnmatch import os import re @@ -18,8 +19,45 @@ # command's first token -- the micro-skill vocabulary, a test-run detector -- would otherwise # stop seeing a test run, a fetch or a repository query. One definition, so the classifiers # cannot disagree about what counts as the wrapper. `rtk proxy` is rtk's own passthrough (run -# unfiltered, still tracked); a bare `rtk` with no command is left alone. -RTK_PREFIX_RE = re.compile(r"^rtk\s+(?:proxy\s+)?(?=\S)") +# unfiltered, still tracked); a bare `rtk` with no command is left alone. `RTK_WORDS` is the +# wrapper alone, for a classifier that passes over it among other prefixes (`loopguard.turn`). +RTK_WORDS = r"rtk(?:\s+proxy)?" +RTK_PREFIX_RE = re.compile(r"^" + RTK_WORDS + r"\s+(?=\S)") + +# The tools whose `command` argument is shell text, lower-cased: Claude Code's Bash, and its +# PowerShell tool on Windows, Codex's shell, the Copilot CLI's stop_bash. +SHELL_TOOLS = frozenset({"bash", "powershell", "shell", "stop_bash"}) + +# Roles a person can give a tool the mechanisms do not know by name (the `tool_roles` +# setting), such as an MCP server's shell or edit tool, and the built-in tool each role reads +# as. The plugin sets them once per process from its configuration (`set_tool_roles`). +TOOL_ROLES = {"shell": "bash", "edit": "edit", "read": "read"} +_tool_roles = () + + +def parse_tool_role(entry): + """`"mcp__serena__replace_content=edit"` -> `("mcp__serena__replace_content", "edit")`; + None when the entry names no tool or no known role. A tool may be a glob (`mcp__x__*`).""" + pattern, sep, role = str(entry).rpartition("=") + pattern, role = pattern.strip().lower(), role.strip().lower() + return (pattern, role) if sep and pattern and role in TOOL_ROLES else None + + +def set_tool_roles(entries): + """Use these `tool_roles` entries from now on in this process; malformed ones are skipped.""" + global _tool_roles + _tool_roles = tuple(r for r in map(parse_tool_role, entries or ()) if r) + + +def tool_kind(name): + """A tool's name as the mechanisms read it: lower-cased, or, for a tool the person gave a + role, the built-in tool of that role (`bash`, `edit`, `read`). The first matching entry + wins.""" + low = (name or "").lower() + for pattern, role in _tool_roles: + if fnmatch.fnmatchcase(low, pattern): + return TOOL_ROLES[role] + return low def strip_rtk_prefix(command): @@ -41,9 +79,11 @@ def load_trajectory(path): lines = [l.strip() for l in open(path, encoding="utf-8", errors="replace") if l.strip()] if _is_codex_exec(lines): return codex_exec_calls(lines) - if any('"tool_use"' in line or '"type": "assistant"' in line or '"type":"assistant"' in line - for line in lines): - return [c[:4] for c in claude_calls(lines)] + # Copilot can also say "tool_use" in metadata (for example a model's finish reason). + # Recognize actual Claude conversation blocks, not strings anywhere in the event log. + claude = claude_calls(lines) + if claude: + return [c[:4] for c in claude] return copilot_event_calls(lines) diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/codex.py b/plugins/tokeneconomizer/tokeneconomizer/trace/codex.py index 5e34060..6f09fff 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/codex.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/codex.py @@ -244,8 +244,10 @@ def codex_session_meta(rollout_path): def codex_session_usage(rollout_path): """Token breakdown of a Codex session from its last cumulative `token_count`. - Converted as `te_harness.codex.row_usage` converts the exec stream: fresh input is the grand - input total less both cache fields, and reasoning tokens are added to output.""" + Fresh input is the grand input total less both cache fields. Codex's `output_tokens` already + holds the reasoning tokens (its `total_tokens` is input plus output, and its own "tokens used" + adds nothing for reasoning), so output is taken as reported; `reasoning_output_tokens` is kept + as information only.""" total = None requests = 0 for line in _lines(rollout_path): @@ -276,6 +278,6 @@ def codex_session_usage(rollout_path): return {"input_tokens": max(0, inp - cached - cw), "cache_read_input_tokens": cached, "cache_creation_input_tokens": cw, - "output_tokens": int(total.get("output_tokens") or 0) + reasoning, + "output_tokens": int(total.get("output_tokens") or 0), "reasoning_output_tokens": reasoning, "requests": requests, "model": meta.get("model")} diff --git a/plugins/tokeneconomizer/tokeneconomizer/trace/droid.py b/plugins/tokeneconomizer/tokeneconomizer/trace/droid.py index 3160c34..04d6267 100644 --- a/plugins/tokeneconomizer/tokeneconomizer/trace/droid.py +++ b/plugins/tokeneconomizer/tokeneconomizer/trace/droid.py @@ -27,6 +27,8 @@ from datetime import datetime SYSTEM_PREFIXES = (" (1, 12, 1); `2` -> (2, 0, 0)).""" + v = droid_session_header(path).get("version") + if isinstance(v, bool): + return None + if isinstance(v, int): + return (v, 0, 0) + if isinstance(v, str): + m = _VERSION_RE.match(v.strip()) + if m: + return tuple(int(g) if g is not None else 0 for g in m.groups()) + return None + + +def droid_session_calls(path): + """Every tool call of a Droid session log that has its result, in log order: + [(name, args, result_text, success)]. A call whose result is not in the log + yet (still running when the log was read) is left out, not guessed at: its + outcome is unknown, and a later read picks it up once the result lands. + Names are the Claude Code equivalents the mechanism readers already key on.""" + calls, order, results = {}, [], {} + for ev in droid_records(path): + if ev.get("type") != "message": + continue + for b in _droid_content((ev.get("message") or {}).get("content")): + if b.get("type") == "tool_use": + tid = b.get("id") + if not isinstance(tid, str) or tid in calls: + continue + calls[tid] = (claude_tool_name(b.get("name")), + b.get("input") if isinstance(b.get("input"), dict) else {}) + order.append(tid) + elif b.get("type") == "tool_result": + c = b.get("content") + if isinstance(c, list): + c = "\n".join(x.get("text", "") for x in c if isinstance(x, dict)) + results[b.get("tool_use_id")] = (c if isinstance(c, str) else "", + not b.get("is_error", False)) + out = [] + for tid in order: + if tid not in results: + continue + name, args = calls[tid] + text, ok = results[tid] + out.append((name, args, text, ok)) + return out + + def droid_session_cwd(path): """The directory the session started in, or None.""" cwd = droid_session_header(path).get("cwd")