pi-claude-relay 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.md +130 -2
- package/extensions/claude-relay.ts +12 -0
- package/package.json +51 -4
- package/src/claude-process.ts +123 -0
- package/src/config.ts +19 -0
- package/src/footer-color.ts +39 -0
- package/src/mcp-host.ts +205 -0
- package/src/provider.ts +165 -0
- package/src/rate-limit.ts +143 -0
- package/src/register.ts +120 -0
- package/src/session.ts +573 -0
- package/src/settings.ts +109 -0
- package/src/stats.ts +77 -0
- package/src/sync.ts +185 -0
- package/src/tool-schema.ts +82 -0
- package/src/turn.ts +215 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## 0.1.0
|
|
6
|
+
|
|
7
|
+
First release.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Relay of Pi's built-in `anthropic` provider through the official `claude` CLI (stream-json). Models keep their normal ids; Pi's model catalog and auth are untouched.
|
|
12
|
+
- One long-lived `claude` process per Pi session, so several sessions and subagents run in parallel without sharing state. No orphan processes on session end or Pi exit.
|
|
13
|
+
- Per-space login: `claude` gets only the Anthropic credential Pi resolves for the current Pi space (OAuth token or API key) and keeps its state in `<agent home>/claude-relay`. The shared `~/.claude` login and inherited `ANTHROPIC_*`, `CLAUDE_CODE_*` and `CLAUDE_CONFIG_DIR` variables are never used. A space without an Anthropic login fails with a `/login` hint.
|
|
14
|
+
- Pi tools served to Claude through a per-session loopback MCP server with parked tool calls. Top-level `anyOf`/`oneOf`/`allOf` tool schemas are flattened into one object schema.
|
|
15
|
+
- Prompt-cache preservation:
|
|
16
|
+
- Abort sends `claude` an `interrupt` instead of killing it; the next message continues on the same process.
|
|
17
|
+
- A replaced process (credential refresh, effort, tool-set or model change, crash) resumes `claude`'s own session with `--resume`, keeping the cache and the structured history. A flattened transcript replay is the fallback for a diverged history (compaction, branch switch, edited history), a pending tool call, a changed system prompt, or a failed resume.
|
|
18
|
+
- Pi's idle cache-warming requests are answered locally, and one-off requests (compaction, summaries) use a throwaway process that is closed when they finish.
|
|
19
|
+
- Thinking levels map to `claude --effort`; thinking blocks reach Pi with their summarized text (`--thinking-display summarized`).
|
|
20
|
+
- `/claude-relay stats`: turns, cache hit rate, `claude` process starts, restarts by reason, resumed restarts, cache-warm requests answered locally and one-off requests. `PI_CLAUDE_RELAY_DEBUG_LOG=<file>` appends one JSON line per turn (no prompt text, credentials or MCP URL).
|
|
21
|
+
- Cost per response computed from the reported tokens with Pi's own model rates (`calculateCost`), including 1 h cache writes, so Pi's cost footer and usage stats work.
|
|
22
|
+
- Footer status from session start with the relay and the space's login; Claude usage windows with a reset countdown, colored through Pi's theme (`warning` above 70 %, `error` above 90 %).
|
|
23
|
+
- Claude rate-limit events exposed as `anthropic-ratelimit-unified-*` response headers and notifications; limit errors are worded so Pi's retry logic recognizes them.
|
|
24
|
+
- `/claude-relay notify [warning|limit] [on|off]`: two independent switches for the usage pop-ups, saved per Pi space.
|
|
25
|
+
- Actionable errors when the `claude` CLI is missing or older than 2.1.330.
|
|
26
|
+
- `PI_CLAUDE_RELAY=off` to fall back to Pi's direct Anthropic streaming; `PI_CLAUDE_RELAY_CLAUDE_BIN` to choose the `claude` binary.
|
|
27
|
+
|
|
28
|
+
### Security
|
|
29
|
+
|
|
30
|
+
- The system prompt and the MCP config (with its secret URL) reach `claude` through `0600` files in a private temp directory, never through the command line.
|
|
31
|
+
- The loopback MCP server checks its path token in constant time, rejects foreign `Host` headers and any `Origin` header, caps request bodies, and never throws on malformed input.
|
|
32
|
+
- Tool calls for tools Pi did not offer are rejected; malformed `claude` output fails the turn instead of crashing Pi.
|
|
33
|
+
- The credential and the MCP URL are redacted from `claude` error text.
|
|
34
|
+
- A replayed transcript escapes its envelope, so tool output cannot pose as a user turn.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 jals1212
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,131 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ⎍ pi-claude-relay
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
A Pi (`@earendil-works/pi-coding-agent`) extension that relays Pi's built-in `anthropic` provider through the official Claude Code CLI (`claude -p`, stream-json). Every model request is made by the `claude` binary itself, with the Anthropic login of the Pi space it runs in; Pi's tools are served to Claude over a private, per-session local MCP server.
|
|
6
|
+
|
|
7
|
+
You keep choosing models exactly as before: `claude-opus-5-5`, `anthropic/claude-sonnet-5-5`, no relay prefix.
|
|
8
|
+
|
|
9
|
+
## Why
|
|
10
|
+
|
|
11
|
+
Pi's direct OAuth path to Anthropic can fail intermittently with:
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
Error: 429 {"type":"error","error":{"type":"rate_limit_error","message":"Error"}, ...}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
while `claude -p` on the same account keeps working. The relay routes Pi's Anthropic traffic through the official client instead of imitating it: it never copies Claude Code headers or identity into Pi's own HTTP calls.
|
|
18
|
+
|
|
19
|
+
> **Account notice.** With a subscription login, the relay hands the Pi space's Anthropic OAuth token to the `claude` CLI so that a third-party harness (Pi) drives it. Anthropic's terms may restrict using a Claude subscription outside Claude Code and Claude.ai. Read them and decide for yourself; an API-key login is not affected.
|
|
20
|
+
|
|
21
|
+
## Requirements
|
|
22
|
+
|
|
23
|
+
- Node.js 22.18 or later.
|
|
24
|
+
- Pi (`@earendil-works/pi-coding-agent`).
|
|
25
|
+
- The `claude` CLI (Claude Code 2.1.330 or later) on `PATH`. You do not need to log in to it: the relay never uses `~/.claude` or its login.
|
|
26
|
+
- Each Pi space signed in to Anthropic with its own login (`/login` → Anthropic in that space). That login is the credential `claude` uses, so every space can use a different account. A space without an Anthropic login fails with a message telling you to run `/login`.
|
|
27
|
+
|
|
28
|
+
No environment variables are needed.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
pi install npm:pi-claude-relay # from npm
|
|
34
|
+
pi install /path/to/pi-claude-relay # local checkout
|
|
35
|
+
pi -e /path/to/pi-claude-relay/extensions/claude-relay.ts # one run only
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Install it in every Pi space that should use it.
|
|
39
|
+
|
|
40
|
+
## Usage
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pi --model claude-sonnet-5-5
|
|
44
|
+
pi --model anthropic/claude-opus-5-5:high
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Thinking levels map to `claude --effort`, and Claude's thinking reaches Pi as summarized thinking blocks (`--thinking-display summarized`; `claude` streams them without text otherwise); tool calls, aborts, multi-turn sessions, and several Pi sessions at once work as with the direct provider. What does not carry over is listed under [Limitations](#limitations).
|
|
48
|
+
|
|
49
|
+
## Configuration
|
|
50
|
+
|
|
51
|
+
| Variable | Effect |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `PI_CLAUDE_RELAY=off` (or `0`, `false`) | Disable the relay; Pi streams Anthropic directly again. |
|
|
54
|
+
| `PI_CLAUDE_RELAY_CLAUDE_BIN` | Path to the `claude` binary (default: `claude` on `PATH`). |
|
|
55
|
+
| `PI_CLAUDE_RELAY_DEBUG_LOG` | File to append one JSON line per settled turn to (see [Prompt-cache stats](#prompt-cache-stats)). |
|
|
56
|
+
|
|
57
|
+
All are optional. Which login is used is never configured: it is the Anthropic login of the Pi space.
|
|
58
|
+
|
|
59
|
+
### Notifications
|
|
60
|
+
|
|
61
|
+
The relay shows two pop-ups when Claude's quota changes: a **warning** when you approach a limit (`Claude usage warning…`) and an error when the **limit** is reached (`Claude usage limit reached…`). Each can be switched off on its own with the `/claude-relay` command in Pi (both are on by default):
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
/claude-relay notify # show the current state
|
|
65
|
+
/claude-relay notify warning off # mute the approaching-limit warning
|
|
66
|
+
/claude-relay notify limit off # mute the limit-reached error
|
|
67
|
+
/claude-relay notify warning on # turn it back on
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The state is saved per Pi space in `<agent home>/claude-relay-settings.json` (`{ "notify": { "warning": true, "limit": true } }`); a missing or unreadable file means both on. Only the pop-ups are affected: the footer status and Pi's automatic retries stay the same.
|
|
71
|
+
|
|
72
|
+
### Prompt-cache stats
|
|
73
|
+
|
|
74
|
+
`/claude-relay stats` shows how well the relay keeps Anthropic's prompt cache warm in this Pi process (counters start at zero when Pi starts):
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
Claude relay stats: 12 turns · cache hit 91%
|
|
78
|
+
process starts: 1 · restarts: 2 (abort 1, model 1) · resumed: 2
|
|
79
|
+
cache warm requests answered locally: 3 · one-off requests: 1
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- **cache hit** = cache-read tokens ÷ (input + cache-read + cache-write tokens), over the turns of your Pi sessions.
|
|
83
|
+
- **process starts** are first `claude` processes of a Pi session; **restarts** replaced a process that held a warm cache, with the reason: `model`, `system-prompt`, `tools`, `effort`, `credential`, `history` (compaction, branch switch, edited history), `missing-tool-call`, `other`, or a process lost outside the planner: `abort`, `error`, `exit`.
|
|
84
|
+
- **resumed** (shown only when above zero) counts the restarts that continued `claude`'s own session with `--resume` instead of replaying a flattened transcript (see [How it works](#how-it-works)); it is a subset of the restarts.
|
|
85
|
+
- **cache warm requests** are Pi's idle cache-warming requests, answered locally without reaching `claude`; **one-off requests** are turns of throwaway sessions (compaction and summaries), which are kept out of the other figures.
|
|
86
|
+
|
|
87
|
+
Set `PI_CLAUDE_RELAY_DEBUG_LOG=/path/to/file` to also append one JSON line per settled turn (`t`, `session` = first 8 hex of the sha256 of the Pi session id, `plan`, `reason`, `stopReason`, `usage`, `systemPromptHash`, `toolsHash`, `messages`). The file is created with mode `0600` and never contains prompt text, tool arguments, credentials or the MCP URL; write errors are ignored.
|
|
88
|
+
|
|
89
|
+
## How it works
|
|
90
|
+
|
|
91
|
+
- **One `claude` process per Pi session**, kept alive across turns and keyed by Pi's session id, so parallel sessions and subagents never share state. Requests for a session id Pi never announced (compaction, summaries, other one-off calls) run in a throwaway process that is closed when the request ends.
|
|
92
|
+
- **Per-space login.** Pi resolves the space's Anthropic credential and the relay hands it to `claude` for that process only: a subscription (OAuth) token as `CLAUDE_CODE_OAUTH_TOKEN`, an API key as `ANTHROPIC_API_KEY`. Every inherited `ANTHROPIC_*`, `CLAUDE_CODE_*` and `CLAUDE_CONFIG_DIR` is dropped, and `claude` keeps its state in `<agent home>/claude-relay` (private, `0700`) inside the space. A changed credential (token refresh, other login) restarts `claude` (see *Restarts keep the cache* below).
|
|
93
|
+
- **Pi tools through MCP.** Each session hosts an MCP server on `127.0.0.1` with a random port and path token. When Claude calls a tool, the relay hands the call to Pi and parks the MCP request until Pi returns the result on its next request; Claude then continues in the same process.
|
|
94
|
+
- **Isolation.** `claude` runs with no built-in tools (`--tools ""`), `--strict-mcp-config`, `--setting-sources ""`, and Pi's system prompt, so `CLAUDE.md`, hooks, plugins, and user settings stay out. The system prompt and MCP config are passed through `0600` files in a private temp directory, never on the command line.
|
|
95
|
+
- **Abort interrupts instead of killing.** When you abort a turn, Pi's turn ends at once, parked tool calls fail with an aborted error, and the relay sends `claude` an `interrupt` control request. The process stays alive with its prompt cache; your next message waits (up to 5 s) for `claude` to confirm the interrupted turn and is then a plain message on the same process. If `claude` does not confirm in time it is killed and restarted as below.
|
|
96
|
+
- **Restarts keep the cache.** The first `claude` process of a Pi session is started with `--session-id <uuid>` and session persistence on, and the relay tracks the session id `claude` reports. When a process has to be replaced (credential refresh, effort, tool-set or model change, a crash, an unconfirmed interrupt) and Pi's history has not diverged from what `claude` already has, the new process is started with `--resume <session id>` and receives only the new message: Anthropic's prompt cache and the structured history survive. A resumed session whose turn fails is not resumed again: the next attempt replays the transcript. The relay falls back to replaying a flattened transcript in a fresh session only when the history diverged (compaction, branch switch, edited history), a tool call was pending, no session id is known, the system prompt changed (`claude` keeps the system prompt a session started with, so a changed one cannot be applied on resume), or the resumed process fails to start (one fallback, in the same request). One-off requests (compaction and summaries) never persist or resume a session.
|
|
97
|
+
- **Pi's transcript is the source of truth.** The relay never reads Claude Code session files; they only let a replaced process pick up where the previous one stopped.
|
|
98
|
+
- **Footer status.** From session start the footer shows the relay and the space's login (`✓ Claude relay · subscription`, `✓ Claude relay · API key`, or `✗ Claude relay · no Anthropic login in this space (/login)`). Footer colors follow Pi's theme: the `✓` lines stay uncolored, the `✗` line is `error`; when no theme is available the footer is plain text. Hosts that draw extension statuses in their own panel (Gentle Shell's INTEGRATIONS panel, for example) may show these lines without the colors.
|
|
99
|
+
- **Rate limits.** Claude's `rate_limit_event` is exposed to Pi as `anthropic-ratelimit-unified-*` response headers, shown in the footer (`Claude 5h 16% · 7d 15%`, each window colored by its utilization like Pi's own context-usage footer: `error` above 90 %, `warning` above 70 %, otherwise `success`; `Claude limit reached · …` is `error`, and the `resets in …` part of a warning is `warning`), and limit errors are worded so Pi's retry logic recognizes them.
|
|
100
|
+
- **Tool schemas.** Top-level `anyOf`/`oneOf`/`allOf` tool schemas are flattened into one object schema that Claude accepts.
|
|
101
|
+
|
|
102
|
+
## Limitations
|
|
103
|
+
|
|
104
|
+
- Request options Pi's direct provider honors are ignored, because `claude` decides them: `maxTokens`, `temperature`, custom headers, `cacheRetention`, and a custom Anthropic `baseUrl` or gateway (requests always go to Anthropic).
|
|
105
|
+
- Cost is computed from the tokens `claude` reports with Pi's own rates for the model (1 h cache writes included), so Pi's footer and stats show it. With a subscription login it is the API-price equivalent, not what you pay; tokens `claude` adds that it does not report are not counted.
|
|
106
|
+
- A flattened transcript replay (see [How it works](#how-it-works)) loses the prompt cache of the conversation and replaces images in the history with `[image]`. Plain Pi keeps its system prompt stable, so this happens only after compaction, a branch switch or edited history; an extension that changes the system prompt during a session (for example once after the first turn) adds one replay per change.
|
|
107
|
+
- While a Pi session lives, `claude`'s transcript files stay on disk inside the space, in `<agent home>/claude-relay/projects/<project>/<session id>.jsonl` (they hold the conversation, including the system prompt). They are deleted when the Pi session closes and when Pi exits; a Pi that crashes or is killed leaves them behind, and the relay removes transcripts untouched for 7 days the next time it starts. Other state `claude` keeps in that folder (settings caches, policy files) is not removed.
|
|
108
|
+
- Requires the `claude` CLI; usage is billed to the space's Anthropic login (subscription plan or API key), like any Claude Code use.
|
|
109
|
+
- Thinking text is the summary the API returns for `--thinking-display summarized`, not the full reasoning.
|
|
110
|
+
- In single-shot print mode (`pi -p`) Pi exits before Claude's post-message rate-limit event, so the footer only updates in interactive and multi-turn sessions.
|
|
111
|
+
|
|
112
|
+
## Alternatives
|
|
113
|
+
|
|
114
|
+
Other Pi packages also bring Claude to Pi; they take different routes:
|
|
115
|
+
|
|
116
|
+
- [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) drives Claude through the Claude Agent SDK as a separate provider (models carry the provider prefix), starts a query per request and resumes Claude Code's on-disk sessions, and uses the shared `~/.claude` login and settings.
|
|
117
|
+
- [`pi-claude-oauth-adapter`](https://www.npmjs.com/package/pi-claude-oauth-adapter) keeps Pi calling the Anthropic API directly with a subscription token, presenting the requests as Claude Code.
|
|
118
|
+
|
|
119
|
+
`pi-claude-oauth-adapter` and pi-claude-relay both take over Pi's `anthropic` provider, so install only one of them in a Pi space: with both, whichever registers last handles every request.
|
|
120
|
+
|
|
121
|
+
pi-claude-relay differs in that the official `claude` CLI makes every request (no Claude Code identity in Pi's own calls), Pi's built-in `anthropic` provider and model ids stay as they are, each Pi space uses its own login with no environment variables, one long-lived process per Pi session keeps the prompt cache warm, and Pi's transcript stays the source of truth.
|
|
122
|
+
|
|
123
|
+
## Development
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
npm test
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// pi-claude-relay: relays Pi's built-in `anthropic` provider through the official `claude` CLI.
|
|
2
|
+
// Set PI_CLAUDE_RELAY=off to use Pi's direct Anthropic streaming instead.
|
|
3
|
+
import { getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import * as piAi from "@earendil-works/pi-ai";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { adoptProvider, registerRelay } from "../src/register.ts";
|
|
7
|
+
|
|
8
|
+
export default function (pi: ExtensionAPI) {
|
|
9
|
+
const provider = registerRelay(pi, { piAi: piAi as any, configDir: join(getAgentDir(), "claude-relay"), settingsFile: join(getAgentDir(), "claude-relay-settings.json") });
|
|
10
|
+
// Pi runs this factory again on every /reload and /new: close the previous provider's claude processes and keep one exit listener.
|
|
11
|
+
adoptProvider(provider);
|
|
12
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-claude-relay",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Pi extension that relays Pi's built-in Anthropic provider through the official Claude Code CLI (`claude -p` stream-json), with Pi tools served over a per-session local MCP server.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "jals1212",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/jals1212/pi-claude-relay.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/jals1212/pi-claude-relay#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/jals1212/pi-claude-relay/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"pi-package",
|
|
17
|
+
"pi",
|
|
18
|
+
"claude",
|
|
19
|
+
"provider"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"pi": {
|
|
23
|
+
"extensions": [
|
|
24
|
+
"./extensions/claude-relay.ts"
|
|
25
|
+
],
|
|
26
|
+
"image": "https://raw.githubusercontent.com/jals1212/pi-claude-relay/main/assets/preview.png"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"src",
|
|
30
|
+
"extensions",
|
|
31
|
+
"README.md",
|
|
32
|
+
"CHANGELOG.md",
|
|
33
|
+
"LICENSE"
|
|
34
|
+
],
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=22.18"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "node --test \"tests/*.test.ts\""
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@earendil-works/pi-ai": "*",
|
|
43
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
44
|
+
},
|
|
45
|
+
"peerDependenciesMeta": {
|
|
46
|
+
"@earendil-works/pi-ai": {
|
|
47
|
+
"optional": true
|
|
48
|
+
},
|
|
49
|
+
"@earendil-works/pi-coding-agent": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Spawns the official `claude` binary in stream-json mode.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { mkdirSync, chmodSync, mkdtempSync, writeFileSync, rmSync, lstatSync, readdirSync, unlinkSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { mcpConfig, buildClaudeArgs, buildChildEnv, SESSION_ID_PATTERN, type ClaudeProc, type SpawnOptions } from "./session.ts";
|
|
7
|
+
import { createLineReader } from "./sync.ts";
|
|
8
|
+
|
|
9
|
+
const STDERR_KEEP = 8192;
|
|
10
|
+
|
|
11
|
+
/** Writes the system prompt and MCP config to a fresh 0700 directory with 0600 files; returns their paths and a cleanup. */
|
|
12
|
+
function writeLaunchFiles(opts: SpawnOptions) {
|
|
13
|
+
const dir = mkdtempSync(join(tmpdir(), "pi-claude-relay-"));
|
|
14
|
+
const cleanup = () => rmSync(dir, { recursive: true, force: true });
|
|
15
|
+
const systemPromptFile = join(dir, "system-prompt.txt");
|
|
16
|
+
const mcpConfigFile = join(dir, "mcp.json");
|
|
17
|
+
try {
|
|
18
|
+
writeFileSync(systemPromptFile, opts.systemPrompt, { mode: 0o600 });
|
|
19
|
+
writeFileSync(mcpConfigFile, JSON.stringify(mcpConfig(opts.mcpUrl)), { mode: 0o600 });
|
|
20
|
+
} catch (e) { cleanup(); throw e; }
|
|
21
|
+
return { systemPromptFile, mcpConfigFile, cleanup };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Best-effort removal of claude's transcript files for these session ids: `<configDir>/projects/<project>/<id>.jsonl`.
|
|
26
|
+
* Only UUID ids are used, only regular files directly inside real project directories are unlinked, and nothing reached through a
|
|
27
|
+
* symlink is touched (the `projects` directory, a project directory or a transcript file), so it can never leave `configDir`.
|
|
28
|
+
*/
|
|
29
|
+
export function removeSessionTranscripts(configDir: string, sessionIds: string[]): void {
|
|
30
|
+
const ids = sessionIds.filter((id) => typeof id === "string" && SESSION_ID_PATTERN.test(id));
|
|
31
|
+
if (!ids.length) return;
|
|
32
|
+
try {
|
|
33
|
+
const projects = join(configDir, "projects");
|
|
34
|
+
if (!lstatSync(projects).isDirectory()) return;
|
|
35
|
+
for (const entry of readdirSync(projects, { withFileTypes: true })) {
|
|
36
|
+
if (!entry.isDirectory()) continue; // a Dirent of a symlink is not a directory
|
|
37
|
+
for (const id of ids) {
|
|
38
|
+
const file = join(projects, entry.name, `${id}.jsonl`);
|
|
39
|
+
try { if (lstatSync(file).isFile()) unlinkSync(file); } catch { /* missing or busy */ }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
} catch { /* no projects directory yet, or unreadable: nothing to remove */ }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Removes session transcripts not touched for `maxAgeMs` (left behind by a Pi that crashed or was killed). Same confinement as
|
|
47
|
+
* `removeSessionTranscripts`: only regular `<uuid>.jsonl` files directly under real `projects/<dir>/` directories; never throws.
|
|
48
|
+
*/
|
|
49
|
+
export function sweepStaleTranscripts(configDir: string, maxAgeMs: number, now = Date.now()): void {
|
|
50
|
+
try {
|
|
51
|
+
const projects = join(configDir, "projects");
|
|
52
|
+
if (!lstatSync(projects).isDirectory()) return;
|
|
53
|
+
for (const entry of readdirSync(projects, { withFileTypes: true })) {
|
|
54
|
+
if (!entry.isDirectory()) continue;
|
|
55
|
+
for (const file of readdirSync(join(projects, entry.name), { withFileTypes: true })) {
|
|
56
|
+
if (!file.isFile() || !file.name.endsWith(".jsonl") || !SESSION_ID_PATTERN.test(file.name.slice(0, -".jsonl".length))) continue;
|
|
57
|
+
const path = join(projects, entry.name, file.name);
|
|
58
|
+
try { if (now - lstatSync(path).mtimeMs > maxAgeMs) unlinkSync(path); } catch { /* missing or busy */ }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
} catch { /* no projects directory yet, or unreadable */ }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function spawnClaude(opts: SpawnOptions, bin = process.env.PI_CLAUDE_RELAY_CLAUDE_BIN || "claude", configDir: string): ClaudeProc {
|
|
65
|
+
mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
66
|
+
chmodSync(configDir, 0o700); // an existing dir may be looser
|
|
67
|
+
const files = writeLaunchFiles(opts);
|
|
68
|
+
let child: ReturnType<typeof spawn>;
|
|
69
|
+
try {
|
|
70
|
+
const args = buildClaudeArgs({ model: opts.model, effort: opts.effort, toolNames: opts.toolNames, systemPromptFile: files.systemPromptFile, mcpConfigFile: files.mcpConfigFile, sessionId: opts.sessionId, resume: opts.resume });
|
|
71
|
+
child = spawn(bin, args, { cwd: opts.cwd, env: buildChildEnv(process.env, opts.credential, configDir), stdio: ["pipe", "pipe", "pipe"] });
|
|
72
|
+
} catch (e) { files.cleanup(); throw e; }
|
|
73
|
+
let stderr = "";
|
|
74
|
+
let lineCb: (v: any) => void = () => {};
|
|
75
|
+
let exitCb: (code: number | null, stderr: string) => void = () => {};
|
|
76
|
+
let exited = false;
|
|
77
|
+
const finish = (code: number | null, extra = "") => {
|
|
78
|
+
files.cleanup();
|
|
79
|
+
if (exited) return;
|
|
80
|
+
exited = true;
|
|
81
|
+
try { exitCb(code, stderr + extra); } catch { /* a throwing consumer must not become an uncaught exception */ }
|
|
82
|
+
};
|
|
83
|
+
const gone = new Promise<void>((resolve) => { child.once("exit", () => resolve()); child.once("error", () => resolve()); });
|
|
84
|
+
const terminate = (hard = false) => {
|
|
85
|
+
try { child.stdin.end(); } catch { /* already closed */ }
|
|
86
|
+
if (hard) { child.kill("SIGKILL"); return; }
|
|
87
|
+
child.kill("SIGTERM");
|
|
88
|
+
setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); }, 3000).unref();
|
|
89
|
+
};
|
|
90
|
+
/** A failure in a consumer or the reader: stop claude and report it through onExit so the session fails the turn. */
|
|
91
|
+
let failed = false;
|
|
92
|
+
const fatal = (what: string, e: unknown) => {
|
|
93
|
+
if (failed || exited) return;
|
|
94
|
+
failed = true;
|
|
95
|
+
const text = e instanceof Error ? e.message : String(e);
|
|
96
|
+
finish(null, `\n${what}: ${text}`);
|
|
97
|
+
terminate();
|
|
98
|
+
};
|
|
99
|
+
child.stdout.setEncoding("utf8");
|
|
100
|
+
const read = createLineReader(
|
|
101
|
+
(v) => { try { lineCb(v); } catch (e) { fatal("claude output handler failed", e); } },
|
|
102
|
+
undefined,
|
|
103
|
+
(message) => fatal("claude output rejected", message),
|
|
104
|
+
);
|
|
105
|
+
child.stdout.on("data", (d: string) => { if (failed) return; try { read(d); } catch (e) { fatal("claude output reader failed", e); } });
|
|
106
|
+
child.stderr.setEncoding("utf8");
|
|
107
|
+
child.stderr.on("data", (d: string) => { stderr = (stderr + d).slice(-STDERR_KEEP); });
|
|
108
|
+
child.stdin.on("error", () => {}); // EPIPE after exit is reported through `exit`
|
|
109
|
+
child.on("error", (e) => finish(null, `\n${e.message}`));
|
|
110
|
+
child.on("exit", (code) => finish(code));
|
|
111
|
+
return {
|
|
112
|
+
write(value) { if (!exited && child.stdin.writable) child.stdin.write(JSON.stringify(value) + "\n"); },
|
|
113
|
+
onLine(cb) { lineCb = cb; },
|
|
114
|
+
onExit(cb) { exitCb = cb; },
|
|
115
|
+
gone,
|
|
116
|
+
kill(hard) {
|
|
117
|
+
if (exited) { if (hard && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); return; }
|
|
118
|
+
exited = true; // a deliberate kill is not an unexpected exit
|
|
119
|
+
files.cleanup(); // claude reads both files at startup
|
|
120
|
+
terminate(hard);
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The relay takes over Pi's built-in Anthropic provider: only its streaming is replaced.
|
|
2
|
+
// Pi's own model catalog and auth stay untouched, so models keep their normal ids
|
|
3
|
+
// (`claude-opus-5-5`, `anthropic/claude-sonnet-5-5`).
|
|
4
|
+
export const PROVIDER = "anthropic";
|
|
5
|
+
// Pi routes a model to the extension's streamSimple when `model.api === config.api`.
|
|
6
|
+
// Every model in Pi's Anthropic catalog uses this api (pi-ai providers/data/anthropic.json).
|
|
7
|
+
export const API = "anthropic-messages";
|
|
8
|
+
export const OPT_OUT_ENV = "PI_CLAUDE_RELAY";
|
|
9
|
+
|
|
10
|
+
/** `PI_CLAUDE_RELAY=off|0|false` disables the relay so Pi streams Anthropic directly. */
|
|
11
|
+
export function relayEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
12
|
+
const v = env[OPT_OUT_ENV]?.trim().toLowerCase();
|
|
13
|
+
return !(v === "off" || v === "0" || v === "false");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Legacy ProviderConfig for pi.registerProvider(PROVIDER, ...): no `models`, no auth fields. */
|
|
17
|
+
export function providerConfig(streamSimple: (...args: any[]) => any) {
|
|
18
|
+
return { api: API, streamSimple };
|
|
19
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Footer status colors through Pi's theme. Text is built as segments so the plain string stays testable and
|
|
2
|
+
// identical to the uncolored footer; ANSI codes only ever come from Pi's own `theme.fg`.
|
|
3
|
+
|
|
4
|
+
/** Theme tokens the relay uses (all exist in Pi's `ThemeColor`). */
|
|
5
|
+
export type FooterColor = "success" | "warning" | "error" | "dim";
|
|
6
|
+
export interface Segment { text: string; color?: FooterColor }
|
|
7
|
+
export interface ThemeLike { fg(color: FooterColor, text: string): string }
|
|
8
|
+
|
|
9
|
+
export const plain = (segments: Segment[]): string => segments.map((s) => s.text).join("");
|
|
10
|
+
|
|
11
|
+
/** Same thresholds as Pi's own footer for context usage: > 90 % error, > 70 % warning. `fraction` is 0..1. */
|
|
12
|
+
export function utilizationColor(fraction: number): FooterColor {
|
|
13
|
+
return fraction > 0.9 ? "error" : fraction > 0.7 ? "warning" : "success";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Colors the segments with `theme`; any problem (no theme, no `fg`, a throwing or non-string `fg`) yields the plain text. */
|
|
17
|
+
export function paint(segments: Segment[], theme?: ThemeLike): string {
|
|
18
|
+
if (!theme || typeof theme.fg !== "function") return plain(segments);
|
|
19
|
+
try {
|
|
20
|
+
return segments.map((s) => {
|
|
21
|
+
if (!s.color) return s.text;
|
|
22
|
+
const out = theme.fg(s.color, s.text);
|
|
23
|
+
if (typeof out !== "string") throw new TypeError("theme.fg returned a non-string");
|
|
24
|
+
return out;
|
|
25
|
+
}).join("");
|
|
26
|
+
} catch {
|
|
27
|
+
return plain(segments);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Pi's theme from an extension context (`ctx.ui.theme`); undefined when unavailable or when reading it throws. */
|
|
32
|
+
export function themeOf(ctx: { ui?: { theme?: unknown } } | undefined): ThemeLike | undefined {
|
|
33
|
+
try {
|
|
34
|
+
const theme = ctx?.ui?.theme as ThemeLike | undefined;
|
|
35
|
+
return theme && typeof theme.fg === "function" ? theme : undefined;
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|