mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
feat(plugins): add headroom-snip Claude Code mod that animates compression (#3980)
## Description Adds `headroom-snip`, a Claude Code plugin that shows what Headroom does to each request while you work. Headroom's savings are mostly invisible from inside Claude Code; this puts them right above the prompt. - **Band above the prompt:** for each new request through the proxy, a scissors animation cuts a bar the size of the original prompt down to what was sent (`21k → 4.1k tok −81%`). It names the compressors that did the cutting (JSON crush, code AST, Kompress text, log squash, cache align, …) and the running total since the session started. When a request goes through unchanged it says why (for example `kept: user message, recent code`). - **`/headroom`:** opens a pane with the per-request log since the session started: bar, what was cut and what was kept, compression latency, biggest snip, all-time total. `/headroom hide` and `/headroom show` toggle the band. - **Status line** running total, and toasts at savings milestones. - If the proxy isn't reachable, the band says so and suggests `headroom wrap claude`. It reads the proxy's existing loopback `GET /stats?cached=1` (`recent_requests`), polling once a second only while a turn runs and for a few seconds after. Requests stamped before the session started are not counted. Under `headroom wrap claude` (which sends `X-Headroom-Project`), only requests the proxy tagged with this session's project count, and the totals are labelled as that project's traffic since the session started (the tag is the launch directory's basename, so other sessions in the same project are included); otherwise they are labelled proxy-wide. There is no per-session request identity at the proxy, so nothing is labelled as a per-session total. No proxy changes; nothing leaves the machine. Proxy URL: `HEADROOM_PROXY_URL`, else `ANTHROPIC_BASE_URL`, else `http://127.0.0.1:8787`. Each candidate must be a loopback URL (http or https on exactly `localhost`, `127.0.0.1` or `[::1]`, no userinfo); anything else is skipped, so the plugin never polls a remote host. ## Spec **API surface:** a Claude Code plugin (`headroom-snip` in `.claude-plugin/marketplace.json`). The `/headroom` command, with `hide` and `show`. Reads the `HEADROOM_PROXY_URL`, `ANTHROPIC_BASE_URL` and `ANTHROPIC_CUSTOM_HEADERS` environment variables. No proxy, CLI or library changes. **Changes to existing behavior:** none. The `headroom` plugin and the Copilot marketplace are untouched. **User stories:** - *Golden path.* Given Claude Code launched with `headroom wrap claude` and the plugin installed, when a turn sends a request the proxy compresses, then within about a second the band animates that request's original → sent tokens and names the compressors, and `/headroom` lists it newest first. - *Edge case: proxy not running.* Given the plugin is installed but nothing answers at the proxy URL, when a turn runs, then the band says Headroom isn't in the loop and suggests `headroom wrap claude`, and nothing else changes. - *Edge case: shared proxy.* Given two clients on one proxy, when the other client sends a request, then a wrapped session leaves it out (different project tag), and an unwrapped session counts it but labels its totals "proxy". - *Edge case: two sessions in one project.* Given two wrapped Claude Code sessions launched from directories with the same name, when either sends a request, then both sessions count it, and the band says "project" and the pane and toasts name the project, never "session". **Failure modes:** proxy down or slow (the band shows the not-running message, and requests are recovered when it comes up); a malformed `/stats` body (ignored); a non-loopback proxy URL (skipped, falls back to the default); a request without a timestamp (counted only if it appears after the first successful poll). **Recovery / resilience:** no state outside Claude Code; running totals live in plugin state and survive a plugin reload. Disable with `claude plugin disable headroom-snip@headroom-marketplace`. **Security considerations:** see Additional Notes. ## Type of Change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `plugins/headroom-snip/`: the plugin (`hooks/register.tsx` for hooks and drawing, `hooks/snip.ts` for parsing, the loopback URL policy, transform labels and animation frames), its state types, tests and README. - `.claude-plugin/marketplace.json`: lists `headroom-snip`, installable with `claude plugin install headroom-snip@headroom-marketplace`. It is **not** added to `.github/plugin/marketplace.json`, because Copilot CLI can't load Claude Code function hooks. - `tests/test_plugin_manifests.py`: the two marketplaces must still match apart from Claude-Code-only plugins. A new test checks each such plugin's manifest name, version and `hooks/hooks.json`. - `scripts/version-sync.py`, `scripts/verify-versions.py`: the new `plugin.json` version is synced and verified with the rest (0.39.1). - `scripts/tests/test_version_sync.py`: fixture and assertion for the new manifest. ## Testing - [x] Unit tests pass (`pytest`): the manifest and version-sync tests touched here - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`): N/A, no changes under `headroom/` - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ pytest -q tests/test_plugin_manifests.py scripts/tests/test_version_sync.py 16 passed, 1 warning in 0.60s $ ruff check tests/test_plugin_manifests.py scripts/ All checks passed! $ ruff format --check tests/test_plugin_manifests.py scripts/ 27 files already formatted $ python scripts/verify-versions.py All versions aligned at 0.39.1 $ claude plugin validate plugins/headroom-snip ✔ Validation passed $ claude plugin test plugins/headroom-snip (pass) proxy url follows the wrapped base url only when it is local (pass) valid loopback urls keep their origin (pass) hosts that only look local are never polled (pass) userinfo, other schemes and junk are refused even on loopback (pass) a remote override falls back to the local base url, not the remote host (pass) transforms read as plain words (pass) the finished bar keeps the sent share and dusts the rest (pass) rows come back oldest first, with their project tags (pass) the session project is read from the wrapped custom headers (pass) a request is this session's by its stamp and project (pass) every milestone a step crosses is announced, lowest first (pass) a request made during a turn is snipped in the band (pass) two new requests in one poll show the newest in the band and newest first in the pane (pass) a proxy that comes up after the session started still counts the session's requests (pass) with a project header, other clients on the proxy are left out (pass) two sessions in one project share a count, and every label says project, not session (pass) one big snip announces each milestone it crosses (pass) polling picks up a request that lands just after the turn, then stops 18 pass 0 fail ``` The plugin tests are a bun-style suite run by `claude plugin test`. They fake the proxy's `/stats` response (newest first, as the proxy sends it) and check what the band and the `/headroom` pane draw: original → sent figures, percentages, compressor labels, totals and their project/proxy label (including two sessions sharing one project tag), newest-first ordering when one poll brings several requests, a proxy that comes up mid-session, filtering by project tag, a toast for each milestone crossed, polling that continues briefly after a turn and then stops, the hide button and the no-proxy message. Each of the four review fixes was checked by restoring the old behaviour: its tests fail. The plugin also type-checks clean under `tsc` against Claude Code's plugin API types (strict, `noUncheckedIndexedAccess`). ## Real Behavior Proof - Environment: macOS, iTerm2, Claude Code 2.1.289, local Headroom proxy - Exact command / steps: `headroom wrap claude --plugin-dir plugins/headroom-snip`, then ran prompts that read large tool output (`ls -la /usr/lib`, `cat package-lock.json`), then ran `/headroom` - Observed result: the band animated the snip for each compressed request with original → sent tokens and compressor labels; `/headroom` listed the requests since the session started - Not tested: Claude desktop app and VS Code surfaces against a live proxy (covered only by the `desktop` surface in the plugin tests); terminals other than iTerm2 ## Runtime Rollout Safety - Rollout-managed feature(s): none. This is an opt-in Claude Code plugin; nothing in the proxy or `headroom` package changes. - Minimum rollout channel: N/A. It reaches only users who run `claude plugin install headroom-snip@headroom-marketplace`. - Stable/default behavior changed: no. Existing installs, the `headroom` plugin and the Copilot marketplace are unchanged. - Kill switch / disable path: `claude plugin disable headroom-snip@headroom-marketplace` (or `uninstall`); `/headroom hide` hides the band. - Unsafe override required: no. - Qualification impact: none on proxy compression or latency. The plugin makes one cached loopback `GET /stats?cached=1` per second while a turn runs. - Rollback path: revert this PR, which removes the plugin and its marketplace entry; installed copies can be uninstalled as above. ## Review Readiness - [x] I performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my own code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [ ] I have updated the CHANGELOG.md if applicable: N/A, release-please generates it from the PR title ## Additional Notes - **Security considerations:** read-only. The plugin only sends `GET` requests to the proxy's existing loopback `/stats` endpoint, which already returns per-request metadata only to loopback callers. Proxy URLs are parsed and must name exactly `localhost`, `127.0.0.1` or `[::1]` over http(s) with no userinfo; look-alike hosts (`localhost.example.com`, `127.0.0.1.example.com`, `localhost@example.com`) and remote overrides are refused, with regression tests. It sends no data elsewhere and changes nothing in the proxy. - Follow-up idea, not in this PR: a pixel-art mascot, and showing when Claude retrieves stashed originals (CCR, `/v1/retrieve/stats`) as visible proof that nothing cut is lost. --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude
JerrettDavis
parent
a63b23fe81
commit
17abee2721
@@ -1,30 +1,49 @@
|
||||
{
|
||||
"name": "headroom-marketplace",
|
||||
"owner": {
|
||||
"name": "Headroom Contributors"
|
||||
},
|
||||
"metadata": {
|
||||
"description": "Headroom marketplace for Claude Code and GitHub Copilot CLI plugins.",
|
||||
"version": "0.40.0"
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "headroom",
|
||||
"source": "./plugins/headroom-agent-hooks",
|
||||
"description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",
|
||||
"version": "0.40.0",
|
||||
"author": {
|
||||
"name": "Headroom Contributors",
|
||||
"url": "https://github.com/headroomlabs-ai/headroom"
|
||||
},
|
||||
"homepage": "https://github.com/headroomlabs-ai/headroom",
|
||||
"repository": "https://github.com/headroomlabs-ai/headroom",
|
||||
"keywords": [
|
||||
"headroom",
|
||||
"hooks",
|
||||
"claude-code",
|
||||
"copilot-cli"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
{
|
||||
"name": "headroom-marketplace",
|
||||
"owner": {
|
||||
"name": "Headroom Contributors"
|
||||
},
|
||||
"metadata": {
|
||||
"description": "Headroom marketplace for Claude Code and GitHub Copilot CLI plugins.",
|
||||
"version": "0.40.0"
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "headroom",
|
||||
"source": "./plugins/headroom-agent-hooks",
|
||||
"description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",
|
||||
"version": "0.40.0",
|
||||
"author": {
|
||||
"name": "Headroom Contributors",
|
||||
"url": "https://github.com/headroomlabs-ai/headroom"
|
||||
},
|
||||
"homepage": "https://github.com/headroomlabs-ai/headroom",
|
||||
"repository": "https://github.com/headroomlabs-ai/headroom",
|
||||
"keywords": [
|
||||
"headroom",
|
||||
"hooks",
|
||||
"claude-code",
|
||||
"copilot-cli"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "headroom-snip",
|
||||
"source": "./plugins/headroom-snip",
|
||||
"description": "Claude Code mod: watch Headroom snip tokens off every request, with an animated band, a /headroom log and a running total.",
|
||||
"version": "0.40.0",
|
||||
"author": {
|
||||
"name": "Headroom Contributors",
|
||||
"url": "https://github.com/headroomlabs-ai/headroom"
|
||||
},
|
||||
"homepage": "https://github.com/headroomlabs-ai/headroom",
|
||||
"repository": "https://github.com/headroomlabs-ai/headroom",
|
||||
"keywords": [
|
||||
"headroom",
|
||||
"claude-code",
|
||||
"tokens",
|
||||
"compression",
|
||||
"mod"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "headroom-snip",
|
||||
"version": "0.40.0",
|
||||
"description": "Watch Headroom snip tokens off every Claude Code request: an animated band, a /headroom log and a running total.",
|
||||
"author": {
|
||||
"name": "Headroom Contributors",
|
||||
"url": "https://github.com/headroomlabs-ai/headroom"
|
||||
},
|
||||
"homepage": "https://github.com/headroomlabs-ai/headroom",
|
||||
"repository": "https://github.com/headroomlabs-ai/headroom",
|
||||
"keywords": [
|
||||
"headroom",
|
||||
"claude-code",
|
||||
"tokens",
|
||||
"compression",
|
||||
"mod"
|
||||
],
|
||||
"types": "./types/index.d.ts"
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# Written by Claude Code when it loads the mod
|
||||
.claude-plugin/types/
|
||||
@@ -0,0 +1,82 @@
|
||||
# headroom-snip
|
||||
|
||||
A Claude Code mod that shows what Headroom does to each request, live. When a
|
||||
request goes through the proxy, a pair of scissors runs along a bar the size of
|
||||
the original prompt, cuts it down to what was actually sent, and the token
|
||||
count drops as it goes:
|
||||
|
||||
```
|
||||
✂ headroom 21k → 16k tok ━━━━━━━━━━━━━━━━━━━━━━━✂⡀⠄⠂⠁⢀⠈⠐⠠ −81%
|
||||
✂ headroom 21k → 7.6k tok ━━━━━━━━━━━✂⠈⠐⠠⡀⠄⠂⠁⢀⠈⠐⠠⡀⠄⠂······ −81%
|
||||
✂ headroom 21k → 4.1k tok ━━━━━━·························· −81%
|
||||
JSON crush ×2 · Kompress text · cache align project 184k saved (62%) over 23 req ≈ 307 pages details hide
|
||||
```
|
||||
|
||||
## What it shows
|
||||
|
||||
- **The band above the prompt.** The latest request: original → sent tokens,
|
||||
the snip animation, and the percentage cut. Below that, which compressors did
|
||||
the cutting (`JSON crush`, `code AST`, `Kompress text`, `log squash`,
|
||||
`cache align`, ...) and the running total since the session started. A request sent unchanged says why,
|
||||
for example `kept: user message, recent code` or `nothing worth a snip`.
|
||||
- **`/headroom`.** Opens a pane with the requests since the session started: one bar per
|
||||
request, what was cut and what was protected, how long compression took, the
|
||||
biggest snip so far, and an all-time total.
|
||||
`/headroom hide` and `/headroom show` toggle the band.
|
||||
- **The status line.** `✂ 184k tok saved · 62%`.
|
||||
- **Milestone toasts** at 10k, 50k, 100k, 250k, 500k, 1M and 5M tokens saved.
|
||||
- **No proxy?** If nothing answers, the band says so and suggests
|
||||
`headroom wrap claude`.
|
||||
|
||||
## How it works
|
||||
|
||||
While a turn runs, the mod polls the proxy's loopback `GET /stats?cached=1`
|
||||
once a second. It reads the `recent_requests` tail (per-request token counts
|
||||
and `transforms_applied`), and keeps polling for a few seconds after the turn
|
||||
ends. Requests stamped before the session started count as history: they
|
||||
aren't animated or added to the totals, even if the proxy only comes up later.
|
||||
Nothing leaves your machine.
|
||||
|
||||
The proxy can't tell Claude Code sessions apart, so the totals are never
|
||||
per session. What they cover depends on how Claude Code reaches the proxy:
|
||||
|
||||
- **Through `headroom wrap claude`:** each request carries an
|
||||
`X-Headroom-Project` header naming the launch directory (its basename, so
|
||||
two directories with the same name share a tag). The mod counts every
|
||||
request with this session's tag, including other sessions in the same
|
||||
project, and leaves other projects out. The proxy only reports tags for its
|
||||
last ten requests, so a request it can't attribute is left out rather than
|
||||
guessed. The band says "project" and `/headroom` names the project.
|
||||
- **Any other way:** there is no tag, so the totals cover every client on the
|
||||
proxy since this session started. The band says "proxy" and `/headroom` says
|
||||
so.
|
||||
|
||||
It finds the proxy in this order:
|
||||
|
||||
1. `HEADROOM_PROXY_URL`
|
||||
2. `ANTHROPIC_BASE_URL` (as `headroom wrap claude` sets it)
|
||||
3. `http://127.0.0.1:8787`
|
||||
|
||||
Only loopback URLs are used: `http` or `https` on exactly `localhost`, `127.0.0.1`
|
||||
or `[::1]`, with no user or password. A value that isn't one (a remote proxy, or a
|
||||
host like `localhost.example.com`) is skipped, so the mod never polls a remote host.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
claude plugin marketplace add headroomlabs-ai/headroom
|
||||
claude plugin install headroom-snip@headroom-marketplace
|
||||
```
|
||||
|
||||
Or, from a checkout: `claude --plugin-dir plugins/headroom-snip`.
|
||||
|
||||
## Develop
|
||||
|
||||
```bash
|
||||
claude plugin validate plugins/headroom-snip
|
||||
claude plugin test plugins/headroom-snip # tests/snip.test.tsx
|
||||
tsc -p plugins/headroom-snip # after Claude Code has loaded it once
|
||||
```
|
||||
|
||||
`hooks/snip.ts` holds the pure parts (parsing, transform labels, the animation
|
||||
frames) and `hooks/register.tsx` holds the hooks and drawing.
|
||||
@@ -0,0 +1 @@
|
||||
{ "modules": ["./register.tsx"] }
|
||||
@@ -0,0 +1,336 @@
|
||||
import { atom, read, update } from 'claude-code'
|
||||
import type { EngineInterface, Register, Timer } from 'claude-code'
|
||||
|
||||
import type { Anim, Proxy, Snip, Totals } from '../types'
|
||||
import {
|
||||
FRAMES,
|
||||
FRAME_MS,
|
||||
addToTotals,
|
||||
bar,
|
||||
counter,
|
||||
crossed,
|
||||
explain,
|
||||
fmt,
|
||||
isOwn,
|
||||
ownProject,
|
||||
pages,
|
||||
parseRecent,
|
||||
proxyUrl,
|
||||
} from './snip'
|
||||
import type { Tone } from './snip'
|
||||
|
||||
const PANE = 'headroom-snip'
|
||||
const POLL_MS = 1000
|
||||
const TAIL_TICKS = 4
|
||||
|
||||
const feed = atom({ plugin: 'headroom-snip', key: 'feed' } as const, [])
|
||||
const totals = atom({ plugin: 'headroom-snip', key: 'totals' } as const, {
|
||||
original: 0,
|
||||
optimized: 0,
|
||||
saved: 0,
|
||||
requests: 0,
|
||||
biggest: null,
|
||||
})
|
||||
const anim = atom({ plugin: 'headroom-snip', key: 'anim' } as const, null)
|
||||
const proxy = atom({ plugin: 'headroom-snip', key: 'proxy' } as const, { url: '', isUp: null, project: null })
|
||||
// When this session started, in $.clock time; requests stamped earlier are history. Kept across reloads.
|
||||
const startedAt = atom({ plugin: 'headroom-snip', key: 'startedAt' } as const, null)
|
||||
const isHidden = atom({ plugin: 'headroom-snip', key: 'isHidden' } as const, false)
|
||||
|
||||
const TONE: Record<Tone, { color?: string; dimColor?: boolean; bold?: boolean }> = {
|
||||
kept: { color: '#4ade80' },
|
||||
doomed: { color: '#f59e0b' },
|
||||
blade: { color: '#f472b6', bold: true },
|
||||
crumb: { color: '#a8a29e' },
|
||||
gone: { dimColor: true },
|
||||
}
|
||||
|
||||
const pct = (t: Pick<Totals, 'saved' | 'original'>) =>
|
||||
t.original > 0 ? Math.round((t.saved / t.original) * 100) : 0
|
||||
|
||||
// The proxy tags requests by project (the launch directory's name), not by session, so the totals are
|
||||
// the project's traffic since this session started, or the whole proxy's when there is no tag.
|
||||
const scope = (project: string | null) => (project ? 'project' : 'proxy')
|
||||
|
||||
// The module's own bookkeeping; a reload starts it over while $.state keeps the drawing's values.
|
||||
const live = {
|
||||
seen: new Set<string>(),
|
||||
url: proxyUrl(),
|
||||
project: null as string | null,
|
||||
poller: undefined as Timer | undefined,
|
||||
animTimer: undefined as Timer | undefined,
|
||||
tail: 0,
|
||||
// Set once a poll has succeeded: a request with no usable timestamp counts only if it shows up after that.
|
||||
isBaselined: false,
|
||||
isPolling: false,
|
||||
}
|
||||
|
||||
async function setProxy($: EngineInterface, next: Proxy) {
|
||||
const now = await read($, proxy)
|
||||
if (now.isUp !== next.isUp || now.url !== next.url || now.project !== next.project) {
|
||||
await update($, proxy, () => next)
|
||||
}
|
||||
}
|
||||
|
||||
async function snipAnimation($: EngineInterface, id: string) {
|
||||
live.animTimer?.cancel()
|
||||
let frame = 0
|
||||
await update($, anim, (): Anim => ({ id, frame }))
|
||||
live.animTimer = $.clock.every(FRAME_MS, () => {
|
||||
frame += 1
|
||||
if (frame >= FRAMES) live.animTimer?.cancel()
|
||||
void update($, anim, (): Anim => ({ id, frame }))
|
||||
})
|
||||
}
|
||||
|
||||
async function land($: EngineInterface, fresh: Snip[]) {
|
||||
const before = (await read($, totals)).saved
|
||||
await update($, feed, list => [...list, ...fresh].slice(-50))
|
||||
const after = await update($, totals, t => addToTotals(t, fresh))
|
||||
$.ui.status(`✂ ${fmt(after.saved)} tok saved · ${pct(after)}%`)
|
||||
|
||||
const where = live.project
|
||||
? `in ${live.project} since this session started`
|
||||
: 'on this proxy since this session started'
|
||||
for (const milestone of crossed(before, after.saved)) {
|
||||
$.ui.toast(`✂ ${fmt(milestone)} tokens snipped ${where}: ${pages(milestone)} Claude didn't have to reread`)
|
||||
}
|
||||
|
||||
const added = fresh.reduce((n, s) => n + s.saved, 0)
|
||||
const lifetime = Number((await $.store.get('lifetimeSaved')) ?? 0)
|
||||
await $.store.set('lifetimeSaved', lifetime + added)
|
||||
|
||||
const showcase = [...fresh].reverse().find(s => s.saved > 0) ?? fresh[fresh.length - 1]
|
||||
if (showcase && showcase.saved > 0) await snipAnimation($, showcase.id)
|
||||
}
|
||||
|
||||
async function poll($: EngineInterface) {
|
||||
if (live.isPolling) return
|
||||
live.isPolling = true
|
||||
try {
|
||||
const res = await $.http.fetch(`${live.url}/stats?cached=1`)
|
||||
if (!res.ok) {
|
||||
await setProxy($, { url: live.url, isUp: false, project: live.project })
|
||||
return
|
||||
}
|
||||
await setProxy($, { url: live.url, isUp: true, project: live.project })
|
||||
for (const s of await read($, feed)) live.seen.add(s.id)
|
||||
const since = (await read($, startedAt)) ?? 0
|
||||
const unseen = parseRecent(res.text).filter(s => !live.seen.has(s.id))
|
||||
unseen.forEach(s => live.seen.add(s.id))
|
||||
// A request stamped before the session started is history, however late the first poll lands.
|
||||
const fresh = unseen.filter(s => isOwn(s, since, live.project) ?? live.isBaselined)
|
||||
live.isBaselined = true
|
||||
if (fresh.length > 0) await land($, fresh)
|
||||
} catch {
|
||||
await setProxy($, { url: live.url, isUp: false, project: live.project })
|
||||
} finally {
|
||||
live.isPolling = false
|
||||
}
|
||||
}
|
||||
|
||||
function keepPolling($: EngineInterface) {
|
||||
live.tail = Number.POSITIVE_INFINITY
|
||||
live.poller ??= $.clock.every(POLL_MS, () => {
|
||||
live.tail -= 1
|
||||
if (live.tail <= 0) {
|
||||
live.poller?.cancel()
|
||||
live.poller = undefined
|
||||
}
|
||||
void poll($)
|
||||
})
|
||||
}
|
||||
|
||||
export const register: Register = on => {
|
||||
on('session.start', async ($, e, next) => {
|
||||
live.url = proxyUrl(await $.env.get('HEADROOM_PROXY_URL'), await $.env.get('ANTHROPIC_BASE_URL'))
|
||||
live.project = ownProject(await $.env.get('ANTHROPIC_CUSTOM_HEADERS'))
|
||||
const now = await $.clock.now()
|
||||
await update($, startedAt, at => at ?? now)
|
||||
await $.command.register({
|
||||
name: 'headroom',
|
||||
description: 'Show what Headroom snipped from each request (add "hide" or "show" for the band)',
|
||||
})
|
||||
void poll($)
|
||||
|
||||
return next(e)
|
||||
})
|
||||
|
||||
on('turn.start', async ($, e, next) => {
|
||||
keepPolling($)
|
||||
|
||||
return next(e)
|
||||
})
|
||||
|
||||
on('turn.complete', async ($, e, next) => {
|
||||
live.tail = TAIL_TICKS
|
||||
void poll($)
|
||||
|
||||
return next(e)
|
||||
})
|
||||
|
||||
on('command.run', { command: 'headroom' }, async ($, e) => {
|
||||
const arg = e.args.trim().toLowerCase()
|
||||
if (arg === 'hide' || arg === 'show') {
|
||||
await update($, isHidden, () => arg === 'hide')
|
||||
return { text: `Headroom snip band ${arg === 'hide' ? 'hidden' : 'shown'}.` }
|
||||
}
|
||||
await poll($)
|
||||
await $.ui.open({ id: PANE, title: '✂ Headroom' })
|
||||
|
||||
return { text: 'Opened the Headroom snip log.' }
|
||||
})
|
||||
|
||||
on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
|
||||
const [list, sum, now, px, hidden] = await Promise.all([
|
||||
read($, feed),
|
||||
read($, totals),
|
||||
read($, anim),
|
||||
read($, proxy),
|
||||
read($, isHidden),
|
||||
])
|
||||
if (e.props.hasSurvey || hidden) return next(e)
|
||||
|
||||
const { Box, Button, Text } = $.ui.resolve(e)
|
||||
const columns = e.props.bodyColumns ?? e.viewport?.columns ?? 80
|
||||
const hide = <Button key="hide" label="hide" plain onPress={() => update($, isHidden, () => true)} />
|
||||
|
||||
if (px.isUp === false) {
|
||||
return (
|
||||
<Box>
|
||||
<Text color="#f472b6">✂ </Text>
|
||||
<Text dimColor wrap="truncate-end">
|
||||
headroom isn't in the loop: nothing at {px.url}. Run `headroom wrap claude` to start snipping.{' '}
|
||||
</Text>
|
||||
{hide}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
const last = list[list.length - 1]
|
||||
if (!last) return next(e)
|
||||
|
||||
const frame = now && now.id === last.id ? now.frame : FRAMES
|
||||
const width = Math.max(10, Math.min(40, columns - 46))
|
||||
const { cuts, kept } = explain(last.transforms)
|
||||
const isPassThrough = last.saved <= 0
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Box>
|
||||
<Text color="#f472b6" bold>
|
||||
✂ headroom{' '}
|
||||
</Text>
|
||||
{isPassThrough ? (
|
||||
<Text dimColor wrap="truncate-end">
|
||||
{fmt(last.original)} tok sent as-is ({kept.length > 0 ? `kept: ${kept.join(', ')}` : 'nothing worth a snip'})
|
||||
</Text>
|
||||
) : (
|
||||
<Box>
|
||||
<Text>
|
||||
{fmt(last.original)} → <Text bold>{fmt(counter(last.original, last.optimized, frame))}</Text> tok{' '}
|
||||
</Text>
|
||||
{bar(width, last.original, last.optimized, frame).map((seg, i) => (
|
||||
<Text key={`b${i}`} {...TONE[seg.tone]}>
|
||||
{seg.text}
|
||||
</Text>
|
||||
))}
|
||||
<Text color="#4ade80" bold>
|
||||
{' '}
|
||||
−{Math.round(last.percent)}%
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor wrap="truncate-end">
|
||||
{' '}
|
||||
{cuts.length > 0 ? `${cuts.slice(0, 3).join(' · ')} ` : ''}{scope(px.project)} {fmt(sum.saved)} saved ({pct(sum)}%) over{' '}
|
||||
{sum.requests} req ≈ {pages(sum.saved)}{' '}
|
||||
</Text>
|
||||
<Button key="details" label="details" plain onPress={() => $.ui.open({ id: PANE, title: '✂ Headroom' })} />
|
||||
<Text dimColor> </Text>
|
||||
{hide}
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
})
|
||||
|
||||
on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
|
||||
const [list, sum, px, hidden] = await Promise.all([read($, feed), read($, totals), read($, proxy), read($, isHidden)])
|
||||
const lifetime = Number((await $.store.get('lifetimeSaved')) ?? 0)
|
||||
const { Box, Button, Text } = $.ui.resolve(e)
|
||||
const columns = e.props.bodyColumns ?? e.viewport?.columns ?? 60
|
||||
const room = Math.max(1, Math.floor(((e.viewport?.rows ?? 24) - 9) / 2))
|
||||
const width = Math.max(8, Math.min(24, columns - 34))
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text>
|
||||
<Text color="#f472b6" bold>
|
||||
✂ {fmt(sum.saved)}
|
||||
</Text>{' '}
|
||||
tokens snipped {px.project ? `in ${px.project}` : 'on this proxy'} since this session started ({pct(sum)}% of {fmt(sum.original)}) over{' '}
|
||||
{sum.requests} requests
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
≈ {pages(sum.saved)} Claude didn't have to reread · {fmt(lifetime)} all-time
|
||||
</Text>
|
||||
{sum.biggest && (
|
||||
<Text dimColor wrap="truncate-end">
|
||||
biggest snip: {fmt(sum.biggest.saved)} tok (−{Math.round(sum.biggest.percent)}%)
|
||||
{explain(sum.biggest.transforms).cuts.length > 0 ? ` by ${explain(sum.biggest.transforms).cuts.join(', ')}` : ''}
|
||||
</Text>
|
||||
)}
|
||||
<Text dimColor>{px.isUp === false ? `proxy unreachable at ${px.url}` : `proxy ${px.url}`}</Text>
|
||||
<Text dimColor wrap="truncate-end">
|
||||
{px.project
|
||||
? `counting every request tagged ${px.project}, other sessions in that project included`
|
||||
: 'counting every client on this proxy (`headroom wrap claude` tags requests by project)'}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
{list.length === 0 && <Text dimColor>No requests through Headroom yet. Send a prompt.</Text>}
|
||||
{list
|
||||
.slice(-room)
|
||||
.reverse()
|
||||
.map(s => {
|
||||
const { cuts, kept } = explain(s.transforms)
|
||||
return (
|
||||
<Box key={s.id} flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>{(s.at.split('T')[1] ?? s.at).slice(0, 8).padEnd(9)}</Text>
|
||||
{bar(width, s.original, s.optimized, FRAMES).map((seg, i) => (
|
||||
<Text key={`b${i}`} {...TONE[seg.tone]}>
|
||||
{seg.text}
|
||||
</Text>
|
||||
))}
|
||||
<Text>
|
||||
{' '}
|
||||
{fmt(s.original)}→{fmt(s.optimized)}
|
||||
</Text>
|
||||
<Text color={s.saved > 0 ? '#4ade80' : undefined} dimColor={s.saved <= 0}>
|
||||
{' '}
|
||||
−{Math.round(s.percent)}%
|
||||
</Text>
|
||||
</Box>
|
||||
<Text dimColor wrap="truncate-end">
|
||||
{' '}
|
||||
{cuts.length > 0 ? cuts.join(' · ') : 'sent as-is'}
|
||||
{kept.length > 0 ? ` (kept: ${kept.join(', ')})` : ''}
|
||||
{s.latencyMs !== null ? ` ${Math.round(s.latencyMs)}ms` : ''}
|
||||
</Text>
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
<Text> </Text>
|
||||
<Box>
|
||||
<Button
|
||||
key="band"
|
||||
label={hidden ? 'show band' : 'hide band'}
|
||||
onPress={() => update($, isHidden, h => !h)}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import type { Snip, Totals } from '../types'
|
||||
|
||||
export const FRAMES = 24
|
||||
export const FRAME_MS = 45
|
||||
export const TOKENS_PER_PAGE = 600
|
||||
export const MILESTONES = [10_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 5_000_000]
|
||||
|
||||
const DEFAULT_PROXY = 'http://127.0.0.1:8787'
|
||||
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
||||
|
||||
/** The origin of `raw` when it is an http(s) URL on a loopback host with no userinfo, else undefined. */
|
||||
export function loopbackOrigin(raw?: string): string | undefined {
|
||||
if (!raw) return undefined
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(raw)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
const isHttp = url.protocol === 'http:' || url.protocol === 'https:'
|
||||
if (!isHttp || url.username || url.password || !LOOPBACK_HOSTS.has(url.hostname.toLowerCase())) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return url.origin
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the Headroom proxy listens: the override, then the wrapped base URL, then the default port.
|
||||
* Each candidate must be a loopback URL; one that is not is skipped, so the mod never polls a remote host.
|
||||
*/
|
||||
export function proxyUrl(override?: string, baseUrl?: string): string {
|
||||
return loopbackOrigin(override) ?? loopbackOrigin(baseUrl) ?? DEFAULT_PROXY
|
||||
}
|
||||
|
||||
type RawRequest = {
|
||||
request_id?: string | null
|
||||
timestamp?: string | null
|
||||
model?: string | null
|
||||
input_tokens_original?: number | null
|
||||
input_tokens_optimized?: number | null
|
||||
tokens_saved?: number | null
|
||||
savings_percent?: number | null
|
||||
transforms_applied?: string[] | null
|
||||
optimization_latency_ms?: number | null
|
||||
}
|
||||
|
||||
type RawLog = { request_id?: string | null; tags?: Record<string, unknown> | null }
|
||||
|
||||
/** Request id → the proxy's project tag, from the raw `request_logs` tail a loopback `/stats` carries. */
|
||||
function projectsById(logs: unknown): Map<string, string | null> {
|
||||
const byId = new Map<string, string | null>()
|
||||
if (!Array.isArray(logs)) return byId
|
||||
for (const log of logs as RawLog[]) {
|
||||
if (!log?.request_id) continue
|
||||
const project = log.tags?.project
|
||||
byId.set(String(log.request_id), typeof project === 'string' && project.trim() ? project.trim() : null)
|
||||
}
|
||||
|
||||
return byId
|
||||
}
|
||||
|
||||
/** The per-request rows of a loopback `/stats` payload, oldest first. */
|
||||
export function parseRecent(text: string): Snip[] {
|
||||
let body: { recent_requests?: RawRequest[]; request_logs?: unknown }
|
||||
try {
|
||||
body = JSON.parse(text)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
// The proxy lists recent_requests newest first.
|
||||
const rows = Array.isArray(body?.recent_requests) ? [...body.recent_requests].reverse() : []
|
||||
const projects = projectsById(body?.request_logs)
|
||||
|
||||
return rows.flatMap(row => {
|
||||
const original = row.input_tokens_original
|
||||
const optimized = row.input_tokens_optimized
|
||||
if (typeof original !== 'number' || typeof optimized !== 'number' || !row.request_id) {
|
||||
return []
|
||||
}
|
||||
const saved = Math.max(0, row.tokens_saved ?? original - optimized)
|
||||
const percent = original > 0 ? (saved / original) * 100 : 0
|
||||
|
||||
return [
|
||||
{
|
||||
id: String(row.request_id),
|
||||
at: row.timestamp ?? '',
|
||||
model: row.model ?? '',
|
||||
original,
|
||||
optimized,
|
||||
saved,
|
||||
percent,
|
||||
transforms: Array.isArray(row.transforms_applied) ? row.transforms_applied : [],
|
||||
latencyMs: typeof row.optimization_latency_ms === 'number' ? row.optimization_latency_ms : null,
|
||||
...(projects.has(String(row.request_id)) ? { project: projects.get(String(row.request_id)) ?? null } : {}),
|
||||
},
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
type Kind = 'cut' | 'kept'
|
||||
|
||||
function describe(transform: string): { kind: Kind; label: string } | null {
|
||||
const t = transform.toLowerCase()
|
||||
if (t.startsWith('router:protected:')) {
|
||||
return { kind: 'kept', label: t.slice('router:protected:'.length).replace(/_/g, ' ') }
|
||||
}
|
||||
if (t.startsWith('router:excluded')) return { kind: 'kept', label: 'excluded tool' }
|
||||
if (t.startsWith('netcost:skip')) return { kind: 'kept', label: 'not worth a cut' }
|
||||
if (t.startsWith('router:netcost')) return null
|
||||
if (t.startsWith('smart:') || t.includes('smart_crush') || t.includes('json')) return { kind: 'cut', label: 'JSON crush' }
|
||||
if (t.startsWith('kompress') || t.includes('kompress')) return { kind: 'cut', label: 'Kompress text' }
|
||||
if (t.includes('cache_breakpoint') || t.includes('cache_align') || t.includes('dynamic_elements')) {
|
||||
return { kind: 'cut', label: 'cache align' }
|
||||
}
|
||||
if (t.startsWith('read_maturation')) return { kind: 'cut', label: 'stale reads' }
|
||||
if (t.includes('whitespace')) return { kind: 'cut', label: 'whitespace' }
|
||||
if (t.includes('code')) return { kind: 'cut', label: 'code AST' }
|
||||
if (t.includes('log')) return { kind: 'cut', label: 'log squash' }
|
||||
if (t.includes('search') || t.includes('grep')) return { kind: 'cut', label: 'search trim' }
|
||||
if (t.includes('diff')) return { kind: 'cut', label: 'diff trim' }
|
||||
if (t.includes('html')) return { kind: 'cut', label: 'HTML strip' }
|
||||
if (t.includes('text')) return { kind: 'cut', label: 'text trim' }
|
||||
if (t === 'processed_content_blocks') return null
|
||||
|
||||
return { kind: 'cut', label: (t.split(':')[0] ?? t).replace(/_/g, ' ') }
|
||||
}
|
||||
|
||||
/** Friendly names for what Headroom did ("JSON crush ×2") and what it left alone on purpose. */
|
||||
export function explain(transforms: readonly string[]): { cuts: string[]; kept: string[] } {
|
||||
const counts = { cut: new Map<string, number>(), kept: new Map<string, number>() }
|
||||
for (const one of transforms) {
|
||||
const d = describe(one)
|
||||
if (d) counts[d.kind].set(d.label, (counts[d.kind].get(d.label) ?? 0) + 1)
|
||||
}
|
||||
const list = (m: Map<string, number>) =>
|
||||
[...m.entries()].sort((a, b) => b[1] - a[1]).map(([label, n]) => (n > 1 ? `${label} ×${n}` : label))
|
||||
|
||||
return { cuts: list(counts.cut), kept: list(counts.kept) }
|
||||
}
|
||||
|
||||
export function fmt(n: number): string {
|
||||
const abs = Math.abs(n)
|
||||
if (abs >= 1_000_000) return `${(n / 1_000_000).toFixed(abs >= 10_000_000 ? 0 : 1)}M`
|
||||
if (abs >= 10_000) return `${Math.round(n / 1000)}k`
|
||||
if (abs >= 1000) return `${(n / 1000).toFixed(1)}k`
|
||||
|
||||
return String(Math.round(n))
|
||||
}
|
||||
|
||||
export function pages(tokens: number): string {
|
||||
const p = tokens / TOKENS_PER_PAGE
|
||||
if (p < 1) return 'less than a page'
|
||||
|
||||
return `${p < 10 ? p.toFixed(1) : Math.round(p)} pages`
|
||||
}
|
||||
|
||||
export function addToTotals(totals: Totals, snips: readonly Snip[]): Totals {
|
||||
return snips.reduce<Totals>(
|
||||
(t, s) => ({
|
||||
original: t.original + s.original,
|
||||
optimized: t.optimized + s.optimized,
|
||||
saved: t.saved + s.saved,
|
||||
requests: t.requests + 1,
|
||||
biggest: !t.biggest || s.saved > t.biggest.saved ? s : t.biggest,
|
||||
}),
|
||||
totals,
|
||||
)
|
||||
}
|
||||
|
||||
/** Every milestone a step from `before` to `after` saved tokens crosses, lowest first. */
|
||||
export function crossed(before: number, after: number): number[] {
|
||||
return MILESTONES.filter(m => before < m && after >= m)
|
||||
}
|
||||
|
||||
/** The X-Headroom-Project this session sends, read from ANTHROPIC_CUSTOM_HEADERS as `headroom wrap claude` sets it. */
|
||||
export function ownProject(customHeaders?: string): string | null {
|
||||
for (const line of (customHeaders ?? '').split(/\r?\n/)) {
|
||||
const colon = line.indexOf(':')
|
||||
if (colon < 0 || line.slice(0, colon).trim().toLowerCase() !== 'x-headroom-project') continue
|
||||
const raw = line.slice(colon + 1).trim()
|
||||
let name = raw
|
||||
try {
|
||||
name = decodeURIComponent(raw)
|
||||
} catch {
|
||||
// A value that is not percent-encoded is used as written.
|
||||
}
|
||||
|
||||
return name.trim() || null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request belongs to this session: stamped at or after `startedAt` and, when the session
|
||||
* sends a project, tagged with exactly that project. A row whose tag is unknown (outside the proxy's
|
||||
* tagged log tail) is not counted then. Undefined when the request carries no usable timestamp.
|
||||
*/
|
||||
export function isOwn(snip: Snip, startedAt: number, project: string | null): boolean | undefined {
|
||||
if (project !== null && snip.project !== project) return false
|
||||
const at = Date.parse(snip.at)
|
||||
if (!Number.isFinite(at)) return undefined
|
||||
|
||||
return at >= startedAt
|
||||
}
|
||||
|
||||
export type Tone = 'kept' | 'doomed' | 'blade' | 'crumb' | 'gone'
|
||||
export type Segment = { tone: Tone; text: string }
|
||||
|
||||
const CRUMBS = ['⠁', '⠂', '⠄', '⡀', '⠠', '⠐', '⠈', '⢀']
|
||||
|
||||
const ease = (x: number) => 1 - Math.pow(1 - x, 3)
|
||||
|
||||
/**
|
||||
* One frame of the snip: the bar is the request as it arrived, `width` cells;
|
||||
* the blade travels from the right end to where the kept part ends, the cut
|
||||
* part crumbles behind it, and at `frame >= FRAMES` only dust is left.
|
||||
*/
|
||||
export function bar(width: number, original: number, optimized: number, frame: number): Segment[] {
|
||||
const w = Math.max(4, Math.floor(width))
|
||||
const ratio = original > 0 ? Math.min(1, Math.max(0, optimized / original)) : 1
|
||||
const kept = Math.max(original > 0 && optimized > 0 ? 1 : 0, Math.round(w * ratio))
|
||||
const p = ease(Math.min(1, Math.max(0, frame / FRAMES)))
|
||||
const done = frame >= FRAMES
|
||||
const blade = done ? -1 : Math.min(w - 1, Math.round(w - (w - kept) * p))
|
||||
const cells: Segment[] = []
|
||||
|
||||
for (let i = 0; i < w; i++) {
|
||||
if (i < kept) cells.push({ tone: 'kept', text: '━' })
|
||||
else if (done) cells.push({ tone: 'gone', text: '·' })
|
||||
else if (i < blade) cells.push({ tone: 'doomed', text: '━' })
|
||||
else if (i === blade) cells.push({ tone: 'blade', text: '✂' })
|
||||
else {
|
||||
const fallen = frame - Math.round(((w - i) / Math.max(1, w - kept)) * FRAMES * 0.6)
|
||||
cells.push(fallen > 6 ? { tone: 'gone', text: '·' } : { tone: 'crumb', text: CRUMBS[(i * 7 + frame) % CRUMBS.length] ?? '·' })
|
||||
}
|
||||
}
|
||||
|
||||
return cells.reduce<Segment[]>((runs, c) => {
|
||||
const last = runs[runs.length - 1]
|
||||
if (last && last.tone === c.tone) last.text += c.text
|
||||
else runs.push({ ...c })
|
||||
|
||||
return runs
|
||||
}, [])
|
||||
}
|
||||
|
||||
/** The token count shown while the blade travels: from the original down to what was sent. */
|
||||
export function counter(original: number, optimized: number, frame: number): number {
|
||||
const p = ease(Math.min(1, Math.max(0, frame / FRAMES)))
|
||||
|
||||
return Math.round(original - (original - optimized) * p)
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
import { expect, mock, test } from 'claude-code/testing'
|
||||
import type { On } from 'claude-code'
|
||||
|
||||
import { bar, crossed, explain, FRAMES, isOwn, ownProject, parseRecent, proxyUrl } from '../hooks/snip'
|
||||
|
||||
// Session start in the tests; the proxy stamps requests in UTC ISO 8601.
|
||||
const T0 = Date.parse('2026-10-04T12:00:00+00:00')
|
||||
const stamp = (offsetSeconds: number) => new Date(T0 + offsetSeconds * 1000).toISOString().replace('Z', '+00:00')
|
||||
|
||||
const row = (id: string, original: number, optimized: number, transforms: string[], at = 5) => ({
|
||||
request_id: id,
|
||||
timestamp: stamp(at),
|
||||
model: 'claude-sonnet',
|
||||
input_tokens_original: original,
|
||||
input_tokens_optimized: optimized,
|
||||
tokens_saved: original - optimized,
|
||||
transforms_applied: transforms,
|
||||
})
|
||||
|
||||
test('proxy url follows the wrapped base url only when it is local', async () => {
|
||||
expect(proxyUrl(undefined, 'http://127.0.0.1:9999/v1')).toBe('http://127.0.0.1:9999')
|
||||
expect(proxyUrl(undefined, 'https://api.anthropic.com')).toBe('http://127.0.0.1:8787')
|
||||
expect(proxyUrl('http://localhost:1234', 'http://127.0.0.1:9999')).toBe('http://localhost:1234')
|
||||
})
|
||||
|
||||
test('valid loopback urls keep their origin', async () => {
|
||||
expect(proxyUrl(undefined, 'http://localhost:8787')).toBe('http://localhost:8787')
|
||||
expect(proxyUrl(undefined, 'HTTP://LOCALHOST:8787/v1')).toBe('http://localhost:8787')
|
||||
expect(proxyUrl(undefined, 'https://127.0.0.1:8443/p/my-project')).toBe('https://127.0.0.1:8443')
|
||||
expect(proxyUrl(undefined, 'http://[::1]:8787/v1')).toBe('http://[::1]:8787')
|
||||
expect(proxyUrl('http://[::1]:9000', undefined)).toBe('http://[::1]:9000')
|
||||
})
|
||||
|
||||
test('hosts that only look local are never polled', async () => {
|
||||
const remote = [
|
||||
'https://localhost.attacker.example/v1',
|
||||
'http://127.0.0.1.attacker.example/v1',
|
||||
'http://localhost@attacker.example/v1',
|
||||
'http://127.0.0.1:8787@attacker.example',
|
||||
'http://attacker.example/?localhost',
|
||||
'http://attacker.example#127.0.0.1',
|
||||
'http://[::1].attacker.example',
|
||||
'http://localhost:8787.attacker.example',
|
||||
]
|
||||
for (const url of remote) {
|
||||
expect(proxyUrl(undefined, url)).toBe('http://127.0.0.1:8787')
|
||||
expect(proxyUrl(url, undefined)).toBe('http://127.0.0.1:8787')
|
||||
}
|
||||
})
|
||||
|
||||
test('userinfo, other schemes and junk are refused even on loopback', async () => {
|
||||
for (const url of [
|
||||
'http://user:pass@127.0.0.1:8787',
|
||||
'http://user@localhost:8787',
|
||||
'ftp://127.0.0.1:8787',
|
||||
'file:///tmp/sock',
|
||||
'javascript:alert(1)',
|
||||
'127.0.0.1:8787',
|
||||
'not a url',
|
||||
'',
|
||||
]) {
|
||||
expect(proxyUrl(url, undefined)).toBe('http://127.0.0.1:8787')
|
||||
}
|
||||
})
|
||||
|
||||
test('a remote override falls back to the local base url, not the remote host', async () => {
|
||||
expect(proxyUrl('https://headroom.example.com', 'http://127.0.0.1:9999/v1')).toBe('http://127.0.0.1:9999')
|
||||
})
|
||||
|
||||
test('transforms read as plain words', async () => {
|
||||
const { cuts, kept } = explain(['smart:array', 'smart:dict', 'router:protected:user_message', 'inserted_2_cache_breakpoints'])
|
||||
expect(cuts).toEqual(['JSON crush ×2', 'cache align'])
|
||||
expect(kept).toEqual(['user message'])
|
||||
})
|
||||
|
||||
test('the finished bar keeps the sent share and dusts the rest', async () => {
|
||||
const done = bar(10, 1000, 300, FRAMES)
|
||||
expect(done).toEqual([
|
||||
{ tone: 'kept', text: '━━━' },
|
||||
{ tone: 'gone', text: '·······' },
|
||||
])
|
||||
const mid = bar(10, 1000, 300, FRAMES / 4)
|
||||
expect(mid.some(s => s.tone === 'blade')).toBe(true)
|
||||
expect(parseRecent('not json')).toEqual([])
|
||||
})
|
||||
|
||||
test('rows come back oldest first, with their project tags', async () => {
|
||||
const text = JSON.stringify({
|
||||
recent_requests: [row('new', 3000, 1000, [], 9), row('old', 2000, 1000, [], 1), row('bare', 100, 100, [], 2)],
|
||||
request_logs: [
|
||||
{ request_id: 'old', tags: { project: 'headroom' } },
|
||||
{ request_id: 'bare', tags: {} },
|
||||
],
|
||||
})
|
||||
const rows = parseRecent(text)
|
||||
expect(rows.map(r => r.id)).toEqual(['bare', 'old', 'new'])
|
||||
expect(rows.map(r => r.project)).toEqual([null, 'headroom', undefined])
|
||||
})
|
||||
|
||||
test('the session project is read from the wrapped custom headers', async () => {
|
||||
expect(ownProject('X-Other: 1\nX-Headroom-Project: my%20app\nX-Headroom-Cwd: /x')).toBe('my app')
|
||||
expect(ownProject('x-headroom-project:headroom')).toBe('headroom')
|
||||
expect(ownProject('X-Headroom-Project: 100%')).toBe('100%')
|
||||
expect(ownProject(undefined)).toBe(null)
|
||||
expect(ownProject('X-Headroom-Project: ')).toBe(null)
|
||||
})
|
||||
|
||||
test('a request is this session\'s by its stamp and project', async () => {
|
||||
const snip = parseRecent(JSON.stringify({ recent_requests: [row('a', 10, 5, [], 3)] }))[0]!
|
||||
expect(isOwn(snip, T0, null)).toBe(true)
|
||||
expect(isOwn(snip, T0 + 60_000, null)).toBe(false)
|
||||
expect(isOwn({ ...snip, project: 'other' }, T0, 'mine')).toBe(false)
|
||||
expect(isOwn({ ...snip, project: 'mine' }, T0, 'mine')).toBe(true)
|
||||
// Logged without a project while this session sends one: another, unwrapped client.
|
||||
expect(isOwn({ ...snip, project: null }, T0, 'mine')).toBe(false)
|
||||
expect(isOwn({ ...snip, project: 'mine' }, T0, null)).toBe(true)
|
||||
// No tag known for the row (outside the proxy's tagged log tail): not counted for a tagged session.
|
||||
expect(isOwn(snip, T0, 'mine')).toBe(false)
|
||||
expect(isOwn(snip, T0, null)).toBe(true)
|
||||
// Stamped before the session started, however slightly: history.
|
||||
expect(isOwn({ ...snip, at: stamp(-0.5) }, T0, null)).toBe(false)
|
||||
expect(isOwn({ ...snip, at: stamp(0) }, T0, null)).toBe(true)
|
||||
expect(isOwn({ ...snip, at: '' }, T0, null)).toBeUndefined()
|
||||
})
|
||||
|
||||
test('every milestone a step crosses is announced, lowest first', async () => {
|
||||
expect(crossed(0, 70_000)).toEqual([10_000, 50_000])
|
||||
expect(crossed(9_000, 9_500)).toEqual([])
|
||||
expect(crossed(10_000, 10_001)).toEqual([])
|
||||
})
|
||||
|
||||
type Stage = {
|
||||
rows?: () => unknown[]
|
||||
logs?: () => unknown[]
|
||||
env?: Record<string, string>
|
||||
isDown?: () => boolean
|
||||
}
|
||||
|
||||
const stage = (on: On, { rows = () => [], logs = () => [], env = {}, isDown = () => false }: Stage) => {
|
||||
const clock = mock.clock(on, { now: T0 })
|
||||
const seen = { fetches: 0, toasts: [] as string[] }
|
||||
mock.store(on)
|
||||
mock.env(on, env)
|
||||
on('http.fetch', () => {
|
||||
seen.fetches += 1
|
||||
if (isDown()) throw new Error('ECONNREFUSED')
|
||||
// The proxy lists recent_requests newest first.
|
||||
const text = JSON.stringify({ recent_requests: [...rows()].reverse(), request_logs: logs() })
|
||||
return { value: { status: 200, ok: true, headers: {}, text } }
|
||||
})
|
||||
on('session.start', (_$, e) => ({ cwd: e.cwd }))
|
||||
on('turn.start', (_$, e) => ({ turnId: e.turnId }))
|
||||
on('turn.complete', () => ({ text: '' }))
|
||||
on('command.register', (_$, e) => ({ value: { command: e.name } }))
|
||||
on('ui.open', () => ({ value: undefined as never }))
|
||||
on('ui.status', () => ({ value: undefined }))
|
||||
on('ui.toast', (_$, e) => {
|
||||
seen.toasts.push(e.text)
|
||||
return { value: undefined }
|
||||
})
|
||||
on('ui.render', ($, e) => {
|
||||
const { Box } = $.ui.resolve(e)
|
||||
return <Box />
|
||||
})
|
||||
|
||||
return { clock, seen }
|
||||
}
|
||||
|
||||
const START = { cwd: '/w', surface: 'terminal', isInteractive: true } as never
|
||||
const TURN_DONE = { answer: '', durationMs: 1, isAborted: false, turnId: 't1', reason: 'answer' } as never
|
||||
|
||||
const BAND = {
|
||||
component: 'AbovePrompt',
|
||||
props: { hasSurvey: false, isWorking: false, maxRows: 10, bodyColumns: 100 } as never,
|
||||
} as const
|
||||
|
||||
const PANE = {
|
||||
component: 'Pane',
|
||||
requestId: 'headroom-snip',
|
||||
props: { title: '✂ Headroom', isFocused: false, bodyColumns: 80, placement: 'dock' } as never,
|
||||
viewport: { columns: 80, rows: 40 },
|
||||
} as const
|
||||
|
||||
const settleSnip = (clock: { advance: (ms: number) => Promise<void> }) => clock.advance(1000 + 45 * (FRAMES + 2))
|
||||
|
||||
test('a request made during a turn is snipped in the band', async ($, on) => {
|
||||
let rows: unknown[] = [row('old', 5000, 5000, [], -30)]
|
||||
const { clock } = stage(on, { rows: () => rows })
|
||||
|
||||
await $.session.start(START)
|
||||
await clock.settle()
|
||||
rows = [...rows, row('r1', 20_000, 4_000, ['smart:array', 'kompress:tool:0.40'])]
|
||||
await $.turn.start({ text: 'hi', turnId: 't1' })
|
||||
await settleSnip(clock)
|
||||
|
||||
for (const surface of ['terminal', 'desktop'] as const) {
|
||||
const ui = await $.ui.mount({ plugin: 'headroom-snip', surface, ...BAND })
|
||||
expect(await ui.find({ text: /20k → 4\.0k/ })).toBeDefined()
|
||||
expect(await ui.find({ text: /−80%/ })).toBeDefined()
|
||||
expect(await ui.find({ text: /JSON crush · Kompress text/ })).toBeDefined()
|
||||
// No project header, so the total is labelled proxy-wide; the pre-session request is not in it.
|
||||
expect(await ui.find({ text: /proxy 16k saved \(80%\) over 1 req/ })).toBeDefined()
|
||||
await ui.press({ key: 'hide' })
|
||||
expect(await ui.find({ text: /headroom/ })).toBeUndefined()
|
||||
await ui.unmount()
|
||||
await $.command.run({ command: 'headroom', args: 'show' } as never)
|
||||
}
|
||||
})
|
||||
|
||||
test('two new requests in one poll show the newest in the band and newest first in the pane', async ($, on) => {
|
||||
let rows: unknown[] = []
|
||||
const { clock } = stage(on, { rows: () => rows })
|
||||
|
||||
await $.session.start(START)
|
||||
await clock.settle()
|
||||
rows = [row('first', 10_000, 9_000, [], 5), row('second', 30_000, 3_000, ['smart:array'], 6)]
|
||||
await $.turn.start({ text: 'hi', turnId: 't1' })
|
||||
await settleSnip(clock)
|
||||
|
||||
const band = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...BAND })
|
||||
expect(await band.find({ text: /30k → 3\.0k/ })).toBeDefined()
|
||||
expect(await band.find({ text: /10k → 9\.0k/ })).toBeUndefined()
|
||||
await band.unmount()
|
||||
|
||||
const pane = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...PANE })
|
||||
const lines = (await pane.findAll({ type: 'Text', text: /→/ })).map(t => t.text)
|
||||
const newest = lines.findIndex(t => /30k→3\.0k/.test(t))
|
||||
const oldest = lines.findIndex(t => /10k→9\.0k/.test(t))
|
||||
expect(newest).toBeGreaterThanOrEqual(0)
|
||||
expect(oldest).toBeGreaterThan(newest)
|
||||
expect(await pane.find({ text: /28k\b|28\.0k|29k/ })).toBeDefined()
|
||||
expect(await pane.find({ text: /over 2 requests/ })).toBeDefined()
|
||||
expect(await pane.find({ text: /counting every client on this proxy/ })).toBeDefined()
|
||||
await pane.unmount()
|
||||
})
|
||||
|
||||
test('a proxy that comes up after the session started still counts the session\'s requests', async ($, on) => {
|
||||
let isDown = true
|
||||
let rows: unknown[] = []
|
||||
const { clock } = stage(on, { rows: () => rows, isDown: () => isDown })
|
||||
|
||||
await $.session.start(START)
|
||||
await clock.settle()
|
||||
const down = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...BAND })
|
||||
expect(await down.find({ text: /headroom wrap claude/ })).toBeDefined()
|
||||
await down.unmount()
|
||||
|
||||
// The proxy starts mid-turn; its first successful poll already holds an in-session request
|
||||
// alongside one it served before this session.
|
||||
await $.turn.start({ text: 'hi', turnId: 't1' })
|
||||
await clock.advance(1000)
|
||||
isDown = false
|
||||
rows = [row('before', 8_000, 2_000, [], -120), row('during', 12_000, 3_000, ['smart:array'], 2)]
|
||||
await settleSnip(clock)
|
||||
|
||||
const ui = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...BAND })
|
||||
expect(await ui.find({ text: /12k → 3\.0k/ })).toBeDefined()
|
||||
expect(await ui.find({ text: /proxy 9\.0k saved \(75%\) over 1 req/ })).toBeDefined()
|
||||
await ui.unmount()
|
||||
})
|
||||
|
||||
test('with a project header, other clients on the proxy are left out', async ($, on) => {
|
||||
let rows: unknown[] = []
|
||||
let logs: unknown[] = []
|
||||
const { clock } = stage(on, {
|
||||
rows: () => rows,
|
||||
logs: () => logs,
|
||||
env: { ANTHROPIC_CUSTOM_HEADERS: 'X-Headroom-Project: headroom\nX-Headroom-Cwd: /w' },
|
||||
})
|
||||
|
||||
await $.session.start(START)
|
||||
await clock.settle()
|
||||
rows = [
|
||||
row('untagged', 50_000, 5_000, ['smart:array'], 2),
|
||||
row('mine', 20_000, 4_000, ['smart:array'], 3),
|
||||
row('theirs', 40_000, 4_000, ['smart:array'], 4),
|
||||
]
|
||||
// 'untagged' fell outside the proxy's ten-row tagged log tail, so its project is unknown.
|
||||
logs = [
|
||||
{ request_id: 'mine', tags: { project: 'headroom' } },
|
||||
{ request_id: 'theirs', tags: { project: 'other-app' } },
|
||||
]
|
||||
await $.turn.start({ text: 'hi', turnId: 't1' })
|
||||
await settleSnip(clock)
|
||||
|
||||
const band = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...BAND })
|
||||
expect(await band.find({ text: /20k → 4\.0k/ })).toBeDefined()
|
||||
expect(await band.find({ text: /project 16k saved \(80%\) over 1 req/ })).toBeDefined()
|
||||
expect(await band.find({ text: /session/ })).toBeUndefined()
|
||||
await band.unmount()
|
||||
|
||||
const pane = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...PANE })
|
||||
expect(await pane.find({ text: /tokens snipped in headroom since this session started/ })).toBeDefined()
|
||||
expect(await pane.find({ text: /counting every request tagged headroom, other sessions in that project included/ })).toBeDefined()
|
||||
expect(await pane.find({ text: /40k→4\.0k/ })).toBeUndefined()
|
||||
expect(await pane.find({ text: /50k→5\.0k/ })).toBeUndefined()
|
||||
await pane.unmount()
|
||||
})
|
||||
|
||||
test('two sessions in one project share a count, and every label says project, not session', async ($, on) => {
|
||||
let rows: unknown[] = []
|
||||
let logs: unknown[] = []
|
||||
const { clock, seen } = stage(on, {
|
||||
rows: () => rows,
|
||||
logs: () => logs,
|
||||
env: { ANTHROPIC_CUSTOM_HEADERS: 'X-Headroom-Project: headroom' },
|
||||
})
|
||||
|
||||
await $.session.start(START)
|
||||
await clock.settle()
|
||||
// 'this-session' and 'other-session' come from two Claude Code sessions launched in directories
|
||||
// named headroom; the proxy tags both the same, so both count.
|
||||
rows = [row('this-session', 40_000, 10_000, ['smart:array'], 3), row('other-session', 30_000, 6_000, ['smart:array'], 4)]
|
||||
logs = [
|
||||
{ request_id: 'this-session', tags: { project: 'headroom' } },
|
||||
{ request_id: 'other-session', tags: { project: 'headroom' } },
|
||||
]
|
||||
await $.turn.start({ text: 'hi', turnId: 't1' })
|
||||
await settleSnip(clock)
|
||||
|
||||
const band = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...BAND })
|
||||
expect(await band.find({ text: /project 54k saved \(77%\) over 2 req/ })).toBeDefined()
|
||||
expect(await band.find({ text: /session/ })).toBeUndefined()
|
||||
await band.unmount()
|
||||
|
||||
const pane = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...PANE })
|
||||
expect(await pane.find({ text: /tokens snipped in headroom since this session started/ })).toBeDefined()
|
||||
expect(await pane.find({ text: /over 2 requests/ })).toBeDefined()
|
||||
await pane.unmount()
|
||||
|
||||
const milestones = seen.toasts.filter(t => /tokens snipped/.test(t))
|
||||
expect(milestones).toEqual([
|
||||
expect.stringMatching(/^✂ 10k tokens snipped in headroom since this session started/),
|
||||
expect.stringMatching(/^✂ 50k tokens snipped in headroom since this session started/),
|
||||
])
|
||||
})
|
||||
|
||||
test('one big snip announces each milestone it crosses', async ($, on) => {
|
||||
let rows: unknown[] = []
|
||||
const { clock, seen } = stage(on, { rows: () => rows })
|
||||
|
||||
await $.session.start(START)
|
||||
await clock.settle()
|
||||
rows = [row('huge', 90_000, 20_000, ['smart:array'])]
|
||||
await $.turn.start({ text: 'hi', turnId: 't1' })
|
||||
await settleSnip(clock)
|
||||
|
||||
const milestones = seen.toasts.filter(t => /tokens snipped/.test(t))
|
||||
expect(milestones.length).toBe(2)
|
||||
expect(milestones[0]).toMatch(/^✂ 10k tokens snipped/)
|
||||
expect(milestones[1]).toMatch(/^✂ 50k tokens snipped/)
|
||||
})
|
||||
|
||||
test('polling picks up a request that lands just after the turn, then stops', async ($, on) => {
|
||||
let rows: unknown[] = []
|
||||
const { clock, seen } = stage(on, { rows: () => rows })
|
||||
|
||||
await $.session.start(START)
|
||||
await clock.settle()
|
||||
await $.turn.start({ text: 'hi', turnId: 't1' })
|
||||
await clock.advance(2000)
|
||||
await $.turn.complete(TURN_DONE)
|
||||
rows = [row('late', 6_000, 1_500, ['smart:array'])]
|
||||
await settleSnip(clock)
|
||||
|
||||
const ui = await $.ui.mount({ plugin: 'headroom-snip', surface: 'terminal', ...BAND })
|
||||
expect(await ui.find({ text: /6\.0k → 1\.5k/ })).toBeDefined()
|
||||
await ui.unmount()
|
||||
|
||||
// The tail runs out four seconds after the turn; after that nothing polls.
|
||||
await clock.advance(5000)
|
||||
const before = seen.fetches
|
||||
await clock.advance(10_000)
|
||||
expect(seen.fetches).toBe(before)
|
||||
})
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./.claude-plugin/types/tsconfig.json"
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
export type Snip = {
|
||||
id: string
|
||||
at: string
|
||||
model: string
|
||||
original: number
|
||||
optimized: number
|
||||
saved: number
|
||||
percent: number
|
||||
transforms: string[]
|
||||
latencyMs: number | null
|
||||
/** The proxy's project tag for the request: a name, null when logged without one, absent when unknown. */
|
||||
project?: string | null
|
||||
}
|
||||
|
||||
export type Totals = {
|
||||
original: number
|
||||
optimized: number
|
||||
saved: number
|
||||
requests: number
|
||||
biggest: Snip | null
|
||||
}
|
||||
|
||||
export type Anim = { id: string; frame: number }
|
||||
|
||||
/** `project` is the X-Headroom-Project this session sends; null means the counts are proxy-wide. */
|
||||
export type Proxy = { url: string; isUp: boolean | null; project: string | null }
|
||||
|
||||
declare module 'claude-code' {
|
||||
interface PluginState {
|
||||
'headroom-snip': {
|
||||
feed: Snip[]
|
||||
totals: Totals
|
||||
anim: Anim | null
|
||||
proxy: Proxy
|
||||
isHidden: boolean
|
||||
startedAt: number | null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ def temp_project(tmp_path: Path) -> dict[str, Path]:
|
||||
agent_hooks_claude.mkdir(parents=True)
|
||||
agent_hooks_github = plugins / "headroom-agent-hooks" / ".github" / "plugin"
|
||||
agent_hooks_github.mkdir(parents=True)
|
||||
snip_claude = plugins / "headroom-snip" / ".claude-plugin"
|
||||
snip_claude.mkdir(parents=True)
|
||||
sdk = root / "sdk"
|
||||
typescript = sdk / "typescript"
|
||||
typescript.mkdir(parents=True)
|
||||
@@ -89,6 +91,9 @@ def temp_project(tmp_path: Path) -> dict[str, Path]:
|
||||
github_plugin = agent_hooks_github / "plugin.json"
|
||||
github_plugin.write_text(json.dumps({"name": "headroom-agent-hooks", "version": "0.1.0"}))
|
||||
|
||||
snip_plugin = snip_claude / "plugin.json"
|
||||
snip_plugin.write_text(json.dumps({"name": "headroom-snip", "version": "0.1.0"}))
|
||||
|
||||
# sdk/typescript/package.json
|
||||
typescript_pkg = typescript / "package.json"
|
||||
typescript_pkg.write_text(json.dumps({"name": "test", "version": "0.5.25"}))
|
||||
@@ -116,6 +121,7 @@ def temp_project(tmp_path: Path) -> dict[str, Path]:
|
||||
"repo_claude_marketplace": repo_claude_marketplace,
|
||||
"repo_github_marketplace": repo_github_marketplace,
|
||||
"claude_plugin": claude_plugin,
|
||||
"snip_plugin": snip_plugin,
|
||||
"github_plugin": github_plugin,
|
||||
"typescript_pkg": typescript_pkg,
|
||||
"server_json": server_json,
|
||||
@@ -344,6 +350,7 @@ def test_plugin_manifests_only_leaves_package_versions_unchanged(
|
||||
assert json.loads(temp_project["opencode_pkg"].read_text())["version"] == "0.5.25"
|
||||
assert json.loads(temp_project["typescript_pkg"].read_text())["version"] == "0.5.25"
|
||||
assert json.loads(temp_project["claude_plugin"].read_text())["version"] == "0.8.0"
|
||||
assert json.loads(temp_project["snip_plugin"].read_text())["version"] == "0.8.0"
|
||||
assert (
|
||||
json.loads(temp_project["repo_github_marketplace"].read_text())["metadata"]["version"]
|
||||
== "0.8.0"
|
||||
|
||||
@@ -45,6 +45,9 @@ def main() -> None:
|
||||
"plugins/headroom-agent-hooks/.claude-plugin/plugin.json": _read_json_version(
|
||||
ROOT / "plugins/headroom-agent-hooks/.claude-plugin/plugin.json"
|
||||
),
|
||||
"plugins/headroom-snip/.claude-plugin/plugin.json": _read_json_version(
|
||||
ROOT / "plugins/headroom-snip/.claude-plugin/plugin.json"
|
||||
),
|
||||
"plugins/headroom-agent-hooks/.github/plugin/plugin.json": _read_json_version(
|
||||
ROOT / "plugins/headroom-agent-hooks/.github/plugin/plugin.json"
|
||||
),
|
||||
|
||||
@@ -107,6 +107,9 @@ def update_plugin_versions(root: Path, version: str) -> None:
|
||||
root / "plugins" / "headroom-agent-hooks" / ".github" / "plugin" / "plugin.json",
|
||||
version,
|
||||
)
|
||||
update_plugin_manifest(
|
||||
root / "plugins" / "headroom-snip" / ".claude-plugin" / "plugin.json", version
|
||||
)
|
||||
|
||||
|
||||
def update_openclaw_package_json(file_path: Path, version: str) -> None:
|
||||
|
||||
@@ -10,10 +10,32 @@ def _load_json(relative_path: str) -> object:
|
||||
return json.loads((REPO_ROOT / relative_path).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
# Plugins built on Claude Code's function hooks, which Copilot CLI cannot load.
|
||||
CLAUDE_CODE_ONLY = {"headroom-snip"}
|
||||
|
||||
|
||||
def test_marketplace_manifests_match() -> None:
|
||||
assert _load_json(".claude-plugin/marketplace.json") == _load_json(
|
||||
".github/plugin/marketplace.json"
|
||||
)
|
||||
claude = _load_json(".claude-plugin/marketplace.json")
|
||||
assert isinstance(claude, dict)
|
||||
shared = {
|
||||
**claude,
|
||||
"plugins": [p for p in claude["plugins"] if p["name"] not in CLAUDE_CODE_ONLY],
|
||||
}
|
||||
assert shared == _load_json(".github/plugin/marketplace.json")
|
||||
|
||||
|
||||
def test_claude_code_only_plugins_are_listed_and_versioned() -> None:
|
||||
marketplace = _load_json(".claude-plugin/marketplace.json")
|
||||
assert isinstance(marketplace, dict)
|
||||
for entry in marketplace["plugins"]:
|
||||
if entry["name"] not in CLAUDE_CODE_ONLY:
|
||||
continue
|
||||
plugin_root = (REPO_ROOT / entry["source"]).resolve()
|
||||
manifest = _load_json(f"{entry['source']}/.claude-plugin/plugin.json")
|
||||
assert isinstance(manifest, dict)
|
||||
assert manifest["name"] == entry["name"]
|
||||
assert manifest["version"] == entry["version"] == marketplace["metadata"]["version"]
|
||||
assert (plugin_root / "hooks" / "hooks.json").is_file()
|
||||
|
||||
|
||||
def test_plugin_manifests_share_core_metadata() -> None:
|
||||
|
||||
Reference in New Issue
Block a user