Files
magpie/internal/claudetui/tap.js
T
qiqllandggbdpq b7631300ec claudetui: a successful interactive turn tells its account's allowance
Since the interactive mode replaced -p for Claude subscription turns
(43966a53, e5f66f8a, 10-31), a turn that succeeded told no
rate_limit_event, so NoteClaudeLimits never ran and the Usage page's
5h/7d figures moved only on a manual refresh (/usage). Only a turn that
ended in a <synthetic> API error told one, from its transcript row.

What changed:
- tap.js, when a main-class reply opens, also copies its
  anthropic-ratelimit-unified-* response headers into the {s, open}
  line as "h". It only reads them; the request to Anthropic is sent as
  Claude Code made it.
- tap.go (rateLimitInfo) turns them into the rate_limit_info -p tells
  (Claude Code 2.1.291): status plus unifiedWindows five_hour, seven_day,
  seven_day_overage_included (5h, 7d, 7d_oi), each only when both its
  utilization and reset are numbers, the reset rounded to a second.
- A streamed reply tells it just before its message_start, as -p does,
  so the bridge keeps it before the reply begins. A reply whose message
  was told whole from the transcript, or that never began one, keeps it
  for the turn's end (tap.settle). Only the latest is told: a kept
  reading from an older reply is never told after a later reply's
  (toldOf), whether the older one ended before or after the later one
  began, since NoteClaudeLimits keeps the last it hears.
- transcript.go: a <synthetic> API error settles the tap first, then
  tells its own rate_limit_info, so the error's reading is the newest.
- docs/subsystems/claude-subscription-bridge.md says all of this.
  The gateway is unchanged: it already turns a rate_limit_event into
  NoteClaudeLimits and limitHeaders.

Run at this head (base origin/main 6c201095):
- gofmt -l on the changed Go files: nothing
- go vet ./internal/claudetui/, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: clean
- go test -count=1 ./internal/claudetui/: ok (62s)
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway/ -run
  'Claude|Tap|TUI': ok (60s)

Broken by hand:
- tap.go, tap.js and transcript.go at 6c201095 with the new tests: all of
  TestTapTellsReplyLimits, TestTapLimitsOfMessageToldWhole,
  TestTapErrorLimitsLast, TestShimTellsTapLimits and
  TestTapKeptLimitsNotAfterNewer (both subtests) red.
- keepLimits without `n > t.toldOf`: TestTapKeptLimitsNotAfterNewer/
  ended_after red (told 0.42 then 0.3). message_start without dropping an
  older kept reading: /ended_before red the same way.

Not tried: a turn on a real claude.ai account, so the headers were not
checked against a captured reply; Windows and WSL; the full go test
./... suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Review: chosen over #5012, which reads the same headers but emits a
rate_limit_event the moment its line arrives. That event can land while an
unstreamed message is pending, and the bridge settles that message early.
This one tells the limits just before message_start, keeps them for a cut
stream's end, and never tells an older reply's limits after a newer one's.
ddnio's real setup-token run on #5012 shows Bun's response headers are
readable there, the same thing this reads.
Run at the pushed head on mote, go1.26.8: go test -tags nogui -count=1
./internal/claudetui/ ok (83s).
Broken by hand: with the limits before message_start turned off,
TestTapTellsReplyLimits, TestShimTellsTapLimits and
TestTapKeptLimitsNotAfterNewer are red.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:54:00 +08:00

165 lines
6.0 KiB
JavaScript

// magpie's tap on Claude Code's stream (internal/claudetui/tap.go). Claude
// Code, a Bun program, loads this before itself (BUN_OPTIONS --preload).
// Its requests to Anthropic go through Bun.FetchSession: this makes that
// a FetchSession whose fetch is the real one's, the request, connection
// and TLS untouched, and copies the reply of each of the main turn's
// requests (x-claude-code-request-class: main), as it streams, to the
// file MAGPIE_CLAUDE_TAP names: a JSON line an event, and the reply's
// anthropic-ratelimit-unified-* headers as it opens. Claude Code reads
// its own copy of the stream as before.
//
// MAGPIE_CLAUDE_GUARD names a file of the bridge's holding the
// CLAUDE_CODE_EXTRA_BODY a turn of the client's gave (its safeguards).
// Claude Code reads that variable as it builds each request, but only
// from its own environment, which nothing outside can change once it
// runs: each request to /v1/messages is given the file's safeguards, as
// Claude Code would have put them there had the variable said so, and
// the variable is set to it for the requests after. The file says it was
// seen (<file>.live) at the first request it could be put in.
(() => {
const file = process.env.MAGPIE_CLAUDE_TAP;
const guard = process.env.MAGPIE_CLAUDE_GUARD;
delete process.env.MAGPIE_CLAUDE_GUARD;
if (!file) return;
// none of it is handed on to what Claude Code runs, nor says it is here
delete process.env.MAGPIE_CLAUDE_TAP;
const ours = /(^|\s)--preload(=|\s+)\S*magpie-claude-tap-\S*/;
const opts = (process.env.BUN_OPTIONS || "").replace(ours, "").trim();
if (opts) process.env.BUN_OPTIONS = opts;
else delete process.env.BUN_OPTIONS;
const argv = process.execArgv;
for (let i = argv.length - 1; i >= 0; i--) {
if (!/magpie-claude-tap-/.test(argv[i])) continue;
if (argv[i].startsWith("--preload=")) argv.splice(i, 1);
else if (argv[i - 1] === "--preload") argv.splice(--i, 2);
}
const fs = require("fs");
let fd;
try {
fd = fs.openSync(file, "a");
} catch {
return;
}
const put = (v) => {
try {
fs.writeSync(fd, JSON.stringify(v) + "\n");
} catch {}
};
const Real = globalThis.Bun && Bun.FetchSession;
if (typeof Real !== "function") {
put({ tap: "none" });
return;
}
let streams = 0;
let live = false;
// body is a request's body with the guard file's safeguards: the same
// bytes when they are what it has, or when it has none to replace (a
// request Claude Code builds without the extra body)
const guarded = (body) => {
if (!guard || typeof body !== "string" || body.indexOf('"safeguards"') < 0) return body;
let extra, now;
try {
extra = fs.readFileSync(guard, "utf8");
now = JSON.parse(extra);
} catch {
return body;
}
if (!now || typeof now !== "object" || !("safeguards" in now)) return body;
let req;
try {
req = JSON.parse(body);
} catch {
return body;
}
if (!req || typeof req !== "object" || !("safeguards" in req)) return body;
if (!live) {
live = true;
try {
fs.writeFileSync(guard + ".live", "");
} catch {}
}
if (process.env.CLAUDE_CODE_EXTRA_BODY !== extra) process.env.CLAUDE_CODE_EXTRA_BODY = extra;
if (JSON.stringify(req.safeguards) === JSON.stringify(now.safeguards)) return body;
req.safeguards = now.safeguards;
put({ guard: "set" });
return JSON.stringify(req);
};
// read tells each event of stream s, then its end: cut when it broke
// off, as a dropped connection or Claude Code's own Esc ends it
const read = async (s, body) => {
const dec = new TextDecoder();
let buf = "";
const event = (text) => {
const data = text
.split("\n")
.filter((l) => l.startsWith("data:"))
.map((l) => l.slice(5).replace(/^ /, ""))
.join("\n");
if (!data) return;
let e;
try {
e = JSON.parse(data);
} catch {
return;
}
if (e && e.type !== "ping") put({ s, e });
};
try {
for await (const chunk of body) {
buf = (buf + dec.decode(chunk, { stream: true })).replace(/\r\n?/g, "\n");
let i;
while ((i = buf.indexOf("\n\n")) >= 0) {
event(buf.slice(0, i));
buf = buf.slice(i + 2);
}
}
if (buf.trim()) event(buf);
put({ s, end: "done" });
} catch (err) {
put({ s, end: "cut" });
}
};
class FetchSession extends Real {
async fetch(input, init) {
try {
const url = String((input && input.url) || input);
if (init && /\/v1\/messages(\?|$)/.test(url)) {
const body = guarded(init.body);
if (body !== init.body) init = { ...init, body };
}
} catch {}
const res = await super.fetch(input, init);
try {
const url = String((input && input.url) || input);
const headers = new Headers((init && init.headers) || (input && input.headers) || undefined);
if (
headers.get("x-claude-code-request-class") === "main" &&
/\/v1\/messages(\?|$)/.test(url) &&
res.body &&
/^text\/event-stream/.test(res.headers.get("content-type") || "")
) {
const [theirs, mine] = res.body.tee();
Object.defineProperty(res, "body", { value: theirs, configurable: true });
// told before Claude Code has the reply, so the helper knows a
// stream is coming before any of its messages
const s = ++streams;
// with the account's allowance as Anthropic tells it on the
// reply, which -p tells in its rate_limit_event
const h = {};
res.headers.forEach((v, k) => {
if (/^anthropic-ratelimit-unified-/i.test(k)) h[k.toLowerCase()] = v;
});
put(Object.keys(h).length ? { s, open: true, h } : { s, open: true });
read(s, mine);
}
} catch {}
return res;
}
}
try {
Bun.FetchSession = FetchSession;
} catch {}
put({ tap: Bun.FetchSession === FetchSession ? "on" : "none" });
})();