Repository navigation
feat(pi): add a Pi package that routes Anthropic through context-guru - #977
Conversation
Add pi-package/, a Pi package with one extension and a controller script. /context-guru setup asks once, starts the proxy as a user service (launchd or systemd --user), then sets providers.anthropic.baseUrl in ~/.pi/agent/models.json. Nothing runs per session start or per request: the extension only tags routed requests with Pi's session id, stops Pi's own cache warming while the proxy keep-alive is on, and posts session end and compaction signals. Uninstall and a reset hatch outside the package undo only what context-guru wrote. Presets and cache strategies match the Claude Code plugin, and a test keeps the strategies in step. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 29c71687b1f6 |
blocking |
Verdict: blocking
Findings
- pi-package/extensions/context-guru.ts:210 — a bare
/context-gurunever runsstatus; it reports an unknown subcommand.- What fails: the user types
/context-guruwith no arguments. The code means to default tostatus, but"".trim().split(/\s+/)returns[""], not[]. Destructuring defaults apply only toundefined, sosubis the empty string. The switch falls todefaultand the user seesUnknown subcommand . Use one of: setup, status, …(with an empty name). - Proof:
node -e 'const [sub="status"]="".split(/\s+/); console.log(sub)'prints an empty line.args.trim()of""is"", and"".split(/\s+/)is[""]. - Fix: filter empties before the switch, for example
const [sub = "status", value = ""] = args.trim().split(/\s+/).filter(Boolean);. Add a test for the dispatch of a bare command; the current tests cover only the pure helpers, which is why this slipped through.
- What fails: the user types
Non-blocking
- pi-package/extensions/context-guru.ts:231 —
update --installre-downloads the release binary with the 180 s default timeout, whilesetupallows 300 s for the same download (line 147). On a slow link the update dies where setup succeeds. - pi-package/scripts/pi_plugin.py:404 — the port in
install.jsonis sticky forever. If another app takes the recorded port while the proxy is down,setupandconfigurefail at the health check on every retry, and the only recovery isuninstall. - pi-package/extensions/context-guru.ts:184-192 —
configureandupdaterestart the proxy without any confirmation when Pi has no UI. The README says "Restarts the proxy after a yes".setuphandles print mode correctly ("no answer is a no"); these two commands do not. - pi-package/scripts/pi_plugin.py:119-123 —
facts(detail=error)printsstr(exception)on onekey=valueline. An exception whose text contains a newline breaks the one-fact-per-line protocol, andparseFactsin the extension then shows fragments. - pi-package/scripts/reset.sh:38-40 —
read -r answerunderset -eexits the script silently when stdin is closed (noresult=line, exit status 1). The README tells the user to run it from a normal shell, so this is an edge case.
What I checked
- Read the full diff (10 new files, 1514 lines) and the code around each assumption the package makes about the rest of the repo.
- Proxy surface, all confirmed present and matching:
POST /anthropic/v1/messages,GET /healthz,POST /signal,POST /tool-defer/probe,GET /stats(returnspresetandrequests), flags--listen,--config,--dashboard,--dashboard-db,--version(printscontext-guru-proxy <version> (commit …), soout[1]is the version). - Config rendering:
preset: off/conservative/medium/high/xhigh/ultrahighall exist inconfig/config.go; everycache:key written byrender_configexists in the strict loader;preset: offparses as the string "off" (existing tests use it); an absentcache:section leaves the keep-alive off, so strategynoneis correct. - Signals:
endKindmaps toprompt_input_exit,clear,resume,other— all in the proxy's closed kind set;SessionStart compactmatches. Local mode needs no auth token on/signal(tenants == nilresolves the static tenant). The extension's 128-char id regex matchessession.MaxExplicitLen; the same id is used for the header and the signal, so both scope to the same key. - Strategy parity: the four names and the seven cache keys match
context-guru-plugin/scripts/settings.py(the Python test enforces this at run time). - Release download: archive name and
checksums.txtmatch.goreleaser.yaml(context-guru_<version>_<os>_<arch>.tar.gz, sha256, wrapped in a directory — the extractor matches on basename, so that is handled); the checksum is enforced before install; the tar member is read withextractfile, so no path traversal; minimum version 0.4.0 is below the current release line (v0.6.8). - Ordering and undo: proxy starts before the route is written and the route is removed before the service stops;
models_route.restoreputs back only keys that still hold our URL; a foreignbaseUrlmakes setup refuse. - Rules: the PR adds no component, states its data dependence (metadata only) and its behavior change (none for existing users);
pi-packagedoes not importproxyor any library package, so the host boundary holds. - Tests read in full: Python tests sandbox HOME/XDG state and mock the service; the Go wrapper skips cleanly when python3 or Node 22.18+ is missing.
- Not verifiable in this repo: the Pi SDK surface (
before_provider_headers,cache_warming_decision,session_compact,session_shutdownreasons,pi.exec,ctx.ui.*,registerCommand) and Pi'sbaseUrlsemantics. No Pi package or types are vendored. The PR body discloses that no real Pi session was tested end to end; keep that gap in mind when the follow-up OpenAI route lands.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 29c71687b1f6 |
approve |
Verdict: approve
The PR adds pi-package/: a Pi extension, a Python controller, a models.json route helper,
a reset hatch, and a Go test wrapper. I read all 10 files in full. I found no defect I can
prove. The package's claims against the proxy all check out (details below).
Findings
None.
Non-blocking
pi-package/extensions/context-guru.ts:110— the bare/context-gurudefault is dead code.
args.trim().split(/\s+/)on""yields[""], sosubis"", notundefined. The
sub = "status"default never applies. A bare/context-guruprints
"Unknown subcommand . Use one of: …" instead of runningstatus. Cosmetic: the message
lists the valid subcommands. Fix:const [sub0] = …; const sub = sub0 || "status".pi-package/extensions/context-guru.ts:353— print mode runsuninstall,updateand
configurewith no confirmation.setuprefuses in print mode ("no answer is a no"),
butuninstallremoves the route, the service and the binary without a yes. Typing the
command is intent, so this is a design choice — but it is the opposite of setup's rule.
Say so in the README, or gate the destructive commands the same way.pi-package/scripts/models_route.py:541— the backup file is dead.installwrites
models.json.before-context-guruwhen no routing record exists. No code reads it;
restoreworks fromrouting.json. Remove it, or say in the README that it is for humans.- Python and TypeScript disagree on a trailing slash. The TS
isRoutedstrips trailing
slashes (context-guru.ts:167); the Pythonis_routed/conflictscompare the exact
string (models_route.py:505). A user who adds a trailing slash to our URL reads as
"not routed" in/context-guru statusand as a foreign conflict on re-setup. pi-package/scripts/pi_plugin.py:722—healthytrusts any 200 from/healthz.
Setup reuses the recorded port without re-checking that our service owns it. A local
process that squats the port and answers/healthzwith 200 would receive Pi's traffic.
Low probability, bounded by the port range walk at first install.- The event wiring has no test. The Node tests cover only the pure helpers
(isRouted,parseFacts,endKind,readInstall). The header stamping, the signal
posts, and the cache-warming stop are untested. The Pi API
(@earendil-works/pi-coding-agent) is not vendored, so I could not check event names,
ctxshapes, or whetherpi.execrejects on a non-zero exit. The code is internally
consistent (it treats non-zero exits as non-throwing), but only a real Pi install proves it. docs/data-dependence.mdwas not touched. The keep-alive row says "the plugin turns
keep-alive on by default". The Pi package also defaults to a spending strategy (auto).
The README's Data section discloses what the package sends, so this is a wording gap,
not a data gap.
What I checked
- Every changed line of all 10 new files, plus the code around each claim they make.
- Proxy endpoints the package calls, all present:
POST /signal(proxy/proxy.go:593): the closed event set acceptsSessionEnd/
SessionStart;endKind's kinds (prompt_input_exit,clear,resume,other) and
the compact mapping are all inlifecycleKinds(proxy/clientsignal.go:112).
Single-tenant mode authenticates the loopback caller with no token
(proxy/tenancy.go:764).POST /tool-defer/probereturns 202 (proxy/proxy.go:595,clientsignal.go:281).GET /healthz(proxy.go:596),GET /stats(servespresetandrequests,
metrics/metrics.go:660,712),/dashboard/(proxy.go:615).x-context-guru-sessionis read on every non-Bob route (proxy/proxy.go:743), and the
extension's id regex matches the proxy'ssafeExplicitcharset, so the header session
and the signal session key the same id.
- Config the package writes: every
cache:key inSTRATEGIESexists in
config/config.go, and the values pass its validation (3540 < 3600, pings within caps).
The strategy dicts matchcontext-guru-plugin/scripts/settings.pyline for line
(DEFAULT_STRATEGYis"auto", so the parity test's key lookup works;settings.pyhas
a__main__guard, sorunpy.run_pathis safe). The presets
off…ultrahighall exist inconfig.go. Keep-alive is off by default in the loader, so
strategynone(nocache:keys) really is off. - Release download: the archive name matches
.goreleaser.yaml
(context-guru_<version>_<os>_<arch>.tar.gz,checksums.txt, wrapped directory); the
checksum parser handles both spacing forms; extraction is by member name into a temp file,
so a crafted archive path cannot traverse. - The Go wrapper is safe for CI: test-only packages already exist
(context-guru-plugin/,internal/boundary/), sogo build ./.../go vet ./...in
ci.yamlare unaffected. The Python tests sandboxHOME,XDG_*and
PI_CODING_AGENT_DIR, start no service, and open no network; the Node test skips on Node
older than 22.18. - models.json handling: a foreign
baseUrlis refused before any write (both in plan
and after consent); broken JSON raises instead of being overwritten;restoreputs back
only keys that still hold our URL, keeps user-added keys, and removes only entries the
installer created; re-install keeps the first record'sprevious. - CLI flags
--listen,--config,--dashboard,--dashboard-dbexist in
cmd/context-guru-proxy/main.go. - Unverified, by nature: the Pi extension API itself (event names,
ctxshapes,
pi.execsemantics,ui.confirm/select). It is a peer dependency that is not in this
repo. See the non-blocking note above.
Round-1 review fixes for the Pi package: - A bare /context-guru now runs status. An empty split gave an empty subcommand, which fell through to "Unknown subcommand". - configure, update and uninstall need an interactive yes, like setup. Print mode changes nothing. - update --install gets the same 300 s timeout as setup. - setup takes a new port when another program holds the recorded one. - A fact never spans two lines, so an error text cannot fake a fact. - models.json URLs compare without a trailing slash, as in the extension. - The reset hatch reads a closed stdin as a no instead of exiting. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Round 1: replies to both reviewsFixed in Reviewer 1, blocking
Non-blocking (both reviewers)
|
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | 18b60bc9fea0 |
approve |
Verdict: approve
Findings
None. My round-1 finding is fixed, and the fix commit introduces no new defect.
Status of earlier findings
- Mine, blocking (bare
/context-gururan "Unknown subcommand"): fixed.parseArgs(extensions/context-guru.ts:61-64) filters empty words before the destructuring default, so""and" "givestatus. A Node test covers"", spaces, one word and two words. I re-checked the logic:"".split(/\s+/)is[""],.filter(Boolean)gives[], and the default now applies. - Non-blocking,
update --install180 s timeout: fixed. Now 300 s, the same as setup (extensions/context-guru.ts:244). - Non-blocking, sticky recorded port: fixed.
choose_port(scripts/pi_plugin.py:152-158) keeps the recorded port only while our proxy answers there or nothing holds it. Tested with mocks.configurestill uses the recorded port as it is, butsetupnow recovers with a new port, so uninstall is no longer the only way out. - Non-blocking, no yes in print mode for
configure/update/uninstall: fixed. Oneagree()gate (extensions/context-guru.ts:190-199), the same rule as setup. Print mode changes nothing and says why. The README states the rule. - Non-blocking, a newline in a fact value: fixed.
facts()joins lines and strips\r(scripts/pi_plugin.py:123). Tested, including a value that starts withresult=— it can no longer fake a fact. - Non-blocking,
reset.shexits on closed stdin: fixed.read -r answer || truewithanswer=preset (scripts/reset.sh:39-40). Closed stdin now printsresult=cancelledand exits 0. Tested withstdin=DEVNULL. - Reviewer 2, trailing-slash disagreement between Python and TypeScript: fixed.
_same(scripts/models_route.py:54-56) strips trailing slashes inis_routed,conflictsandrestore. Tested. - Reviewer 2, dead backup file: rejected, and I accept the reason. The copy is for a person; uninstall works from the routing record. A code comment and the README now say so.
- Reviewer 2,
healthytrusts any 200: rejected, and I accept the reason. A program that squats a loopback port and answers/healthzwith 200 is on the user's own machine, the same threat model as the Claude Code and Codex plugins.choose_portalso narrows the window: the port is kept only while our proxy or no one holds it. - Reviewer 2, no test of the event wiring: rejected, and I accept the reason. The Pi SDK is a peer dependency, not in this repo. The extension is type-checked against
@earendil-works/pi-coding-agent1.5.0, and the PR body keeps the missing end-to-end run disclosed. - Reviewer 2,
docs/data-dependence.mdnot touched: rejected, and I accept the reason. The keep-alive row describes the feature for every host. The PR states its data dependence, and the package README says the default strategy spends quota.
Non-blocking
choose_porttests the port with a bind andstart_servicebinds it again a moment later. Another program could take the port in between. The window is milliseconds and the failure path is the health check, so I see no action needed.
What I checked
- Last review: round 1, 29c7168, 2026-11-09T16:03:37Z.
- New commits read: 1 —
18b60bc9"fix(pi): run status on a bare command and ask before every change". - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
- New items since my last review: reviewer 2's round-1 review (7 non-blocking notes, each checked against the code above); the author's reply comment (each fix verified in the diff, each rejection checked for a sound reason); the fix commit (every changed hunk read, plus the code around it).
- The fix diff touches 7 files, all inside
pi-package/. I read each hunk and the surrounding code:parseArgsandagreein the extension,choose_portand the one-linefactschange in the controller,_samein the route helper and its three call sites, thereset.shstdin fix, the README additions, and the 5 new tests (4 Python, 1 Node). - Re-ran the round-1 reasoning on the changed paths: the consent rules now cover all four writing commands;
configurestill restarts only after a yes; the trailing-slash change cannot make a foreign gateway read as ours, because_samecompares the full URL, not just the host. - The rejections I accepted: each names a reason I could check against the code (backup-file comment at scripts/models_route.py:107, README note; loopback threat model; SDK peer dependency; host-generic data-dependence row).
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.319 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | 18b60bc9fea0 |
approve |
Verdict: approve
The fix commit 18b60bc9 addresses every round-1 finding. I checked each fix in the
code. All are correct. Two rejections have reasons I accept. One new rough edge came out
of the port fix; it is non-blocking.
Round-1 findings
Mine (all non-blocking):
- Bare
/context-gurudefault is dead code — fixed.parseArgs
(context-guru.ts:61) filters empty words, so""gives[]and thesub = "status"
default applies. Tested for"", spaces, one word, two words. - Print mode runs
uninstall/update/configurewith no yes — fixed. Oneagree()
gate (context-guru.ts:190) covers all three, with setup's rule: no dialog, no change.
The README says so. - Backup file is dead — rejected, with a reason I accept. It is a copy for a person.
A code comment (models_route.py:107) and the README now say uninstall uses the routing
record only. - Trailing-slash disagreement — fixed.
_same(models_route.py:54) compares without
trailing slashes inis_routed,conflictsandrestore. Tested. healthytrusts any 200 on/healthz— rejected, with a reason I accept. A program
that can bind a loopback port on the user's machine is already local code; the proxy and
the other client plugins have the same exposure.choose_portalso narrows the window:
the port is kept only while our proxy answers it or nothing holds it.- No test of the event wiring — deferred, reasonably. The Pi API is a peer dependency.
The author type-checked the extension strict against Pi 1.5.0. An end-to-end run in Pi
stays open, as the PR body discloses. docs/data-dependence.mduntouched — rejected, with a reason I accept. The
keep-alive row describes the feature's data dependence, which does not change. The
package README states that the default strategyautospends quota.
Reviewer 1's blocking finding (bare command): fixed, see item 1. I checked the fix
myself: "".trim().split(/\s+/).filter(Boolean) is [], so both destructuring defaults
apply, and the handler now calls parseArgs.
Reviewer 1's non-blocking items: the timeout (fixed to 300 s), the sticky port
(fixed for setup, see below), print mode (fixed), the newline in facts (fixed),
reset.sh closed stdin (fixed). All verified in the diff.
Findings
None.
Non-blocking
pi-package/scripts/pi_plugin.py:423— the port fix creates a refuse-on-our-own-route
corner. When another program holds the recorded port,choose_portreturns a new port.
conflictsthen sees our own old-port URL in models.json as foreign, and setup refuses
withbase_url_already_set(pi_plugin.py:447). The user must remove the baseUrl by
hand, or run the reset hatch — which the refusal message does not name. Reachable only
when a squatter sits on the exact recorded port, and the old behavior (health-check
failure on every retry) was no better. Fix later: when the clash URL is one of our own
recordedbase_urls, treat it as ours and rewrite the route to the new port.configurestill uses the recorded port (pi_plugin.pyunchanged). On a squatted
port it reportsnot_appliedand changes nothing. This is fail-safe, and configure
cannot move the port without rewriting the models.json route, which is setup's job.
Recovery is the reset hatch plus setup.
What I checked
- Last review: round 1, 29c7168, 2026-11-09T16:05:06Z.
- New commits read: 1 —
18b60bc9"fix(pi): run status on a bare command and ask before
every change". Full diff read (git diff 29c71687..HEAD), plus each changed file around
the changes:setup/choose_port/factsinpi_plugin.py,_samein
models_route.py,parseArgs/agreeincontext-guru.ts,reset.sh, both test
files, the README. - Read in full: 2 reviews, 1 comment, 0 inline comments (from
.review-in-reviews.txt,
.review-in-comments.txt,.review-in-inline.txt). - New items since my last review: reviewer 1's round-1 review (16:03:37Z, read now; its
blocking finding overlaps my bare-command note), the author's reply comment (16:07:07Z),
and the fix commit (16:06:33Z). Each checked above. - Each fix traced in the code:
parseArgs:filter(Boolean)before destructuring; bare and space-only input reach
thestatusdefault; the handler uses it; tests cover four input shapes.agree: all three write paths gate on it; print mode prints "needs an interactive
yes, so nothing changed" and returns false;setupkeeps its own print-mode refusal.facts:" ".join(str(value).split("\n")).replace("\r", " ")keeps one fact per
line, so an error text can no longer forge aresult=fact; test asserts the exact
output.choose_port: keeps the recorded port when healthy or free; takes a new one
otherwise; tested with mocks for all three branches._same: applied tois_routed,conflictsandrestore; None still means absent,
so an unset baseUrl is not "ours"; test covers the trailing-slash case.reset.sh:read -r answer || truewithanswer=preset; closed stdin yields
result=cancelled, exit 0; tested withstdin=DEVNULL.update --installtimeout is now 300 s, the same as setup.
- New tests checked for CI safety: all still run in the sandboxed temp HOME, mock the
service, and open no network.
Pi's setup now routes the openai provider to /openai/v1, as well as anthropic. A route URL counts as ours only for the provider it was written for. An Anthropic-only install gets OpenAI only after the user runs /context-guru setup again and says yes. Behavior change: Pi users of this package (new in #977). With cache strategy auto, 1-ping or 2-ping, the proxy also pings OpenAI GPT-5.6+ sessions after 28 minutes idle. This uses the user's OpenAI quota; the consent question says so. Off: /context-guru cache-strategy none stops all pings; /context-guru uninstall removes both routes. Owner's yes, 2026-11-10, in the integrator session: "yes". Data dependence: metadata only, as #977 (session id header, session end and compaction events). Reviews: 2 offload reviews (GLM), round 2, both approve at 33633c0. After #977 merged, the branch was rebased onto main as 95a72a7; the #982-only patch is unchanged (patch-id 860502d6b543 before and after). DCO: both commits are signed off. The DCO app still reported the old stacked range; the owner approved merging past that stale result, 2026-11-10, in the integrator session ("yes u may"). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Summary
Adds
pi-package/, a Pi package that routes Pi's Anthropic models through a local context-guru proxy. It is the Pi counterpart of the Claude Code plugin. OpenAI follows in a stacked PR.Data dependence: metadata only. The extension sends the proxy Pi's session id (a header) and session end and compaction events (id, event, reason). It adds no component, so
docs/data-dependence.mddoes not change.Behavior change: none for existing users. This is a new, opt-in package.
What changed
/context-guru setupasks one question. On yes it:context-guru-proxyonPATH);systemd --useron Linux);providers.anthropic.baseUrlin~/.pi/agent/models.json.A failed start writes no route.
models.json, and the service is up before Pi starts. The extension makes no network call on session start or on a request.x-context-guru-session: <Pi session id>to routed requests, so the proxy keeps one session across a compaction;noneleaves Pi's warming as it is);/signal, fire and forget./context-guru status | preset | cache-strategy | update | uninstall.presetandcache-strategyrestart the proxy after a yes.uninstall, and a reset hatch copied out of the package to~/.local/state/context-guru-pi/context-guru-reset. Both remove the route first and touch only what context-guru wrote. AbaseUrlthe user changed after setup stays.models.jsonalready sends Anthropic elsewhere (a gateway), setup refuses and changes nothing.How it was tested
scripts/test_pi_plugin.py), in a temp HOME: route install and restore, refusal of a broken or foreignmodels.json, no route when the proxy does not come up, consent required, reset hatch, strategy parity with the Claude Code plugin. They pass on macOS (Python 3.13) and on the eval box (Python 3.9).tests/context-guru.test.ts) for the extension's pure helpers. Pass on Node 22.18.@earendil-works/pi-coding-agent1.5.0 (tsc --noEmit, strict).ultrahigh/auto,off/none,medium/2-ping,high/1-ping) and reports the right preset./signalreturns 204 for the extension's end and compaction bodies.go vetandgofmtare clean on the eval box.pi_test.goruns both test sets fromgo test ./.... It skips the Node tests when Node is older than 22.18.Not tested yet: a real Pi session end to end. Pi 1.5.0 needs Node 22.19 and this laptop has 22.18. The service install (launchd and systemd) is also not run, because it changes the machine.
Open questions
pi install git:has no subfolder syntax, so this version installs from a local clone. Publish to npm later, or add a rootpackage.jsonwith apimanifest?[A-Za-z0-9._:-]{1,128}). This depends on Pi keeping that format.🤖 Generated with Claude Code