Files
magpie/internal/claudetui/tap.js
T
Suge8 543eb39b94 gateway, claudetui: an interactive run asked another effort goes on in its run, the conversation read from the cache
#5584 (Suge8, magpie 0.1.3216, Claude Code 2.1.318, Pi on Opus 5.5,
interactive mode): a turn asking another effort than the one before let
the run go ("its effort is set at its start, and the next turn asks
another"), and a new Claude Code was told the conversation from a
transcript: 72,416 tokens written to the cache on a 108-message
conversation, 178,309 on a 148-message one (first token after 94.4s).

-p runs take a new level by apply_flag_settings (#502). The interactive
mode can't, as measured on the real 2.1.318 (Haiku 5.5, tmux, magpie's
own arguments):
- typing `/effort high` keeps the cache (55,310 read before, 55,400
  after), but saves the level as the default for new sessions:
  modelSettings.<model>.effortLevel in the settings.json of the
  account's folder, the user's own ~/.claude for Claude Code's own
  sign-in, even with --setting-sources ''. Only `max` is session-only.
- a --settings file rewritten (effortLevel, or modelSettings.<model>)
  changes nothing: the request stays at medium, with or without
  --effort. Claude Code pins the file's content as it starts.
- after `/effort max`, the one field of its requests that changes is
  output_config.effort.

Fix:
- Every interactive run has the guard file (guard.json, {} with no
  safeguards); guardBody writes its safeguards and, once the run was
  told another level than its --effort (ownEffort), "effort" beside
  them. setSafeguards and the new setTUIEffort both write it from the
  run's state (tellGuard, under settingsMu).
- tap.js asks each main request (x-claude-code-request-class: main) at
  the file's effort in output_config.effort, and leaves Claude Code's
  other requests as they were; CLAUDE_CODE_EXTRA_BODY gets the file
  without "effort". It writes guard.json.live at the first main request
  as well as the first one carrying safeguards.
- resume: an interactive run asked another effort calls setTUIEffort.
  A run with no .live (no tap), or a turn asking Claude Code's own
  level ("") of a run started at another, is let go as before, the log
  saying which.
- A level the model refuses (real 2.1.318 on claude-haiku-4-5 through
  such a rewrite: "API Error: 400 This model does not support the
  effort parameter.") fails the turn as a run started at it would; the
  existing path (ended, !ok) lets the run go, and the turn asked again
  starts a Claude Code at that --effort.
- docs/subsystems/claude-subscription-bridge.md says so.

Run at this tree (base 9e6687e3):
- New: TestTapAsksTheGuardFilesEffort (bun and node),
  TestClaudeTUIEffortChangeGoesOnInItsRun,
  TestClaudeTUIEffortChangeWithoutTapStartsAnew,
  TestClaudeTUIEffortRefusedStartsAnew: ok; with the guard tests,
  -race -count=3: ok.
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...; go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- go test -tags nogui ./... (Go 1.26.8, go.mod's; sandbox HOME):
  everything ok but TestPluginSOCKSProxy (#2207, Bun 1.4.4 here) and
  TestLaneLimitRoutes (#5150, reads the running gateway; ok alone).
- The built binary, `magpie serve` on 127.0.0.1:34251 in a sandbox HOME,
  XDG dirs and TMPDIR, Claude Code 2.1.318 signed in from a copy of the
  access token (no refresh token), three turns of one conversation on
  claude-haiku-5-5 at medium, high, medium (~20K tokens of history):
  one Claude Code pid for all three, no "its effort is set at its
  start"; the requests as sent (a read-only preload under the tap) asked
  medium, high, medium; usage read/written 795/19,413, 19,869/384,
  20,228/71. ~/.claude/settings.json byte for byte unchanged.

Broken by hand:
- resume's old abortFor back: the three gateway tests red ("started 2
  runs, want one at medium"; the log's reason; the refused turn
  answered 200).
- tap.js not asking the effort: TestTapAsksTheGuardFilesEffort red
  ("request 1 was sent … medium").

Not tried: Opus and Sonnet through the interactive mode (Haiku 5.5
only); whether Anthropic thinks harder at the rewritten level (the
request asks it, the reply doesn't tell); a Claude Code in WSL.
2026-11-10 18:57:44 +08:00

194 lines
7.4 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.
//
// The file's effort, beside the extra body, is the level the run was told
// since it started (#5584): each main request asks it in
// output_config.effort, in place of the --effort Claude Code started
// with. The interactive mode takes another level only from a person
// typing /effort, which saves it as the user's default for new sessions;
// a --settings file is read once, as Claude Code starts.
(() => {
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 and effort:
// 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). The
// effort goes in the main turn's requests (main) alone, never in what
// Claude Code asks beside them (titles, summaries, its classifiers).
const guarded = (body, main) => {
if (!guard || typeof body !== "string") return body;
const carries = body.indexOf('"safeguards"') >= 0;
if (!carries && !main) return body;
let text, now;
try {
text = fs.readFileSync(guard, "utf8");
now = JSON.parse(text);
} catch {
return body;
}
if (!now || typeof now !== "object") return body;
// the file is the extra body Claude Code is to send, and the effort
// beside it, which is no field of a request
const { effort, ...extra } = now;
const level = main && typeof effort === "string" ? effort : "";
const safeguards = carries && "safeguards" in extra;
if (!safeguards && !main) return body;
let req;
try {
req = JSON.parse(body);
} catch {
return body;
}
if (!req || typeof req !== "object") return body;
if (safeguards && !("safeguards" in req)) return body;
if (!live) {
live = true;
try {
fs.writeFileSync(guard + ".live", "");
} catch {}
}
let changed = false;
if (safeguards) {
const env = effort === undefined ? text : JSON.stringify(extra);
if (process.env.CLAUDE_CODE_EXTRA_BODY !== env) process.env.CLAUDE_CODE_EXTRA_BODY = env;
if (JSON.stringify(req.safeguards) !== JSON.stringify(extra.safeguards)) {
req.safeguards = extra.safeguards;
changed = true;
put({ guard: "set" });
}
}
if (level && !(req.output_config && req.output_config.effort === level)) {
req.output_config = { ...(req.output_config || {}), effort: level };
changed = true;
}
return changed ? JSON.stringify(req) : body;
};
// 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 headers = new Headers(init.headers || (input && input.headers) || undefined);
const body = guarded(init.body, headers.get("x-claude-code-request-class") === "main");
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" });
})();