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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ Start `codex`, choose **Trust and continue** for the folder, then at **Hooks nee
choose **Trust all and continue**. The hooks take effect from your next Codex session, so quit
(`/exit`), start `codex` again, and check with `$tokeneconomizer:status`.

**GitHub Copilot in VS Code**

See [VS Code setup on Windows](plugin/README.md#github-copilot-in-vs-code) for project hooks
with the **Copilot** session target, without GitHub CLI or standalone Copilot CLI.

**Copilot CLI**

```sh
Expand Down
92 changes: 92 additions & 0 deletions plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,98 @@ codex plugin add tokeneconomizer@tokeneconomizer

To update it, rebuild the bundle and run `codex plugin add tokeneconomizer@tokeneconomizer` again.

## GitHub Copilot in VS Code

On Windows, use project [hooks](https://code.visualstudio.com/docs/agent-customization/hooks)
with **Copilot** selected as the chat session target. This setup needs Python >= 3.10,
PowerShell 7, and Copilot signed in inside VS Code; neither `gh` nor `copilot` is required.
It enables model-free micro-skills only. The older **Local** session target uses a different hook format.

**1. Clone TokenEconomizer**, or use your existing checkout:

```powershell
git clone https://github.com/microsoft/TokenEconomizer.git C:/dev/TokenEconomizer
```

**2. Configure your project.** In PowerShell 7, edit the first two paths and run this block.
Keep the checkout in place: the hooks reference it directly. Use this setup once per project;
do not also enable the packaged TokenEconomizer plugin there.

```powershell
$teRoot = (Resolve-Path 'C:/dev/TokenEconomizer').Path
$projectRoot = (Resolve-Path 'C:/work/my-project').Path
$pythonExe = (Get-Command python -CommandType Application |
Where-Object Source -NotLike '*WindowsApps*' | Select-Object -First 1).Source
if (-not $pythonExe) { throw 'Set $pythonExe to a real Python 3.10+ executable' }
& $pythonExe --version # Must be a real Python 3.10+ installation.

$bootstrap = Join-Path $teRoot 'plugin/scripts/te_bootstrap.py'
$teState = Join-Path $projectRoot '.te-vscode-state'
$hookDir = Join-Path $projectRoot '.github/hooks'
$hookFile = Join-Path $hookDir 'tokeneconomizer-vscode.json'
if (Test-Path -LiteralPath $hookFile) {
throw "TokenEconomizer hooks already exist: $hookFile"
}

$previousTeState = $env:TOKENECONOMIZER_HOME
try {
$env:TOKENECONOMIZER_HOME = $teState
& $pythonExe $bootstrap cli --host copilot --cwd $projectRoot config set `
microskills=envfacts toolprune=off loopguard=off repomap=off history_import=off
if ($LASTEXITCODE -ne 0) { throw 'Could not configure TokenEconomizer' }
} finally {
$env:TOKENECONOMIZER_HOME = $previousTeState
}

$quotedPython = "'" + $pythonExe.Replace("'", "''") + "'"
$quotedBootstrap = "'" + $bootstrap.Replace("'", "''") + "'"
$command = "& $quotedPython $quotedBootstrap hook --host copilot"
$hooks = [ordered]@{}
foreach ($event in @('SessionStart', 'UserPromptSubmit', 'PostToolUse',
'PostToolUseFailure', 'Stop', 'SessionEnd')) {
$hooks[$event] = @(@{
type = 'command'
powershell = $command
timeoutSec = 60
env = @{ TOKENECONOMIZER_HOME = $teState; PYTHONUTF8 = '1' }
})
}
New-Item -ItemType Directory -Path $hookDir -Force | Out-Null
@{ version = 1; hooks = $hooks } | ConvertTo-Json -Depth 8 |
Set-Content -LiteralPath $hookFile -Encoding utf8NoBOM
```

Add `/.te-vscode-state/` and `/.github/hooks/tokeneconomizer-vscode.json` to the project's
local Git excludes (normally `.git/info/exclude`). They contain local state and absolute paths.

**3. Check it.** Open that project in VS Code, select the **Copilot** session target and
**Agent**, then open **Chat: Open Customizations** > **Hooks** to check the workspace hooks.
Start a new chat and ask Copilot to read a project file. In the same PowerShell terminal:

```powershell
$previousTeState = $env:TOKENECONOMIZER_HOME
try {
$env:TOKENECONOMIZER_HOME = $teState
& $pythonExe $bootstrap cli --host copilot --cwd $projectRoot status --explain
} finally {
$env:TOKENECONOMIZER_HOME = $previousTeState
}
```

Check for a session record under `.te-vscode-state/repos/<project-key>/copilot/sessions/`.
After saving your work and closing that project's VS Code window, its record should eventually
show `folded: true`. For hook errors, check `.te-vscode-state/errors.log`.

Tested with VS Code 1.146.0 and the Copilot session target. Hooks, transcript processing, and
context injection were verified; natural fact learning still needs validation. Model-based
proposals, loop guard, and tool pruning stay disabled. This hook setup does not install slash commands.

**Update.** Update the clone and start a new chat. If its path or the Python path changes,
remove the hook file and repeat step 2.

**Uninstall.** Remove only `.github/hooks/tokeneconomizer-vscode.json` and start a fresh chat.
Keep `.te-vscode-state/` if you want to retain the learned state.

## Copilot CLI

**1. Install.**
Expand Down
27 changes: 27 additions & 0 deletions tests/test_trace_copilot_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Copilot metadata must not make its event stream look like a Claude transcript."""
import json

from tokeneconomizer.trace import call_cwds, load_trajectory, tool_usage


def test_copilot_tool_use_finish_reason_preserves_calls(tmp_path):
path = tmp_path / "events.jsonl"
events = [
{"type": "session.start", "data": {"context": {"cwd": str(tmp_path)}}},
{"type": "assistant.turn_end", "data": {"finishReason": "tool_use"}},
{"type": "tool.execution_start", "data": {
"toolCallId": "read-1", "toolName": "view", "arguments": {"path": "fixture.txt"}}},
{"type": "tool.execution_complete", "data": {
"toolCallId": "read-1", "success": True, "result": {"content": "amber"}}},
{"type": "tool.execution_start", "data": {
"toolCallId": "read-2", "toolName": "view", "arguments": {"path": "missing.txt"}}},
{"type": "tool.execution_complete", "data": {
"toolCallId": "read-2", "success": False, "result": {"content": "Path does not exist"}}},
]
path.write_text("\n".join(json.dumps(event) for event in events), encoding="utf-8")
assert load_trajectory(path) == [
("view", {"path": "fixture.txt"}, "amber", True),
("view", {"path": "missing.txt"}, "Path does not exist", False),
]
assert tool_usage(path) == {"view": 2}
assert call_cwds(path) == [str(tmp_path), str(tmp_path)]
8 changes: 5 additions & 3 deletions tokeneconomizer/trace/calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,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)


Expand Down