Commit Graph
9 Commits
Author SHA1 Message Date
yetone 9a92fd099b claude: a long auto mode classifier keeps its cache marks as claude -p (#5585, #5655)
With Claude Code's interactive mode on, the classifier was pasted into a
new run each call with none of its marks: Claude Code marks only the last
block of what it is pasted, and the classifier's tail changes every call,
so each call read only Claude Code's own prompt and wrote the whole
transcript again (126K and 132K a call at 1h's 2x in iamnil's rows).
Desktop's header-less classifier lost its marks at parse time
(e5f66f8a6); an opted-in one lost them when pasted.

There is no honest way to make the interactive Claude Code put a mark
mid-message: rewriting its body in tap.js would make the request unlike
Claude Code's and can pass the four-mark limit. So a classifier whose
marks keep 64KB or more of history (marksPrintAt, keptByPrint) runs as
claude -p, which keeps the marks (DISABLE_PROMPT_CACHING, the client's
marks in the first message, the tail through CLAUDE_CODE_EXTRA_BODY).
-p counts about 2x a token; with S Claude Code's prompt, M the marked
transcript and D the new part, interactive ~ 0.1S + 2M a call and -p ~
2(0.1(S+M) + 2D), which meet at M ~ 15-20K tokens. A shorter classifier
and every other request stay interactive; claudePrint names it
"cache-marks". No entrypoint, system prompt or identity text changes.

Run:
- TestClaudeTUIClassifierKeepsLongMarksAsPrint (with and without the
  header; a short classifier as control) is red with keptByPrint forced
  false (the old routing) and green with the fix.
- On mote at 70c10074c: go test -tags nogui -run
  'Claude|Classifier|AutoMode|Cache' ./internal/gateway ok; go vet
  ./internal/gateway for darwin, linux and windows ok; gofmt clean.
- Real account (one Max account, sandbox HOME, its keychain item copied
  to the sandbox's service name and deleted after; port 3481; Claude
  Code 2.1.316; claude-haiku-4-5), two classifier-shaped calls sharing a
  ~244KB prefix, interactive mode on:
    before (4ab1191bc): call 1 read 0 wrote 49,838; call 2 read 0 wrote 49,865
    after:              call 1 read 0 wrote 49,763; call 2 read 49,748 wrote 42
  The gateway logged both after-runs as claude -p with the reason.

Not tried: Claude Desktop's real classifier (the body was built to its
shape), Sonnet, Windows/WSL. Full suite not run at push; queued on mote
under the suite lock.

Reported-by: jerrychoi
Reported-by: iamnil (Discord)
2026-11-08 11:39:44 +08:00
yetone dca338f3a3 gateway: a relayed Claude run keeps its cache as long as the request's own marks ask (Linka)
v0.1.3247 (dbc74414b) gave a bridge run the prompt-cache TTL of the
user's pick, but read it only on the machine the relay runs on: its env,
settings.json's env, then promptCacheTtl. A Docker magpie has none of
them, so it fell back to 1h while the Mac it serves was set to 5m. The
Mac's pick reaches the remote only as the cache marks its Claude Code
puts on the request.

A new run's TTL is now picked by runTTLFor:
1. FORCE_PROMPT_CACHING_5M on this computer: 5m, as Claude Code does.
2. The request's own marks: the longest TTL on its tools, system,
   messages or the request itself (askedCacheTTL, Request.askedTTL).
3. claudeRunTTL: this computer's CLAUDE_CODE_PROMPT_CACHE_TTL or
   promptCacheTtl.
4. 1h, only for a request with no marks (Chat, Responses clients).

The run started from a saved transcript (replaySession) follows it too.
Warmup and usage runs have no request and keep claudeRunTTL
(cleanClaudeEnv). Linka's FORCE_PROMPT_CACHING_5M=1 workaround keeps
working. Docs: claude-subscription-bridge.md.

Tests: four new cases in TestClaudeRunKeepsTheUsersCacheTTL (the child's
env and the first message's marks): client 5m with nothing set here;
client 5m over this computer's 1h; client 1h over its 5m; forced 5m over
client 1h. New TestAskedCacheTTL with bodies shaped like Claude Code's
(billing line, marked system blocks, the last message marked).

Run on mote: go vet ./internal/gateway for darwin, linux and windows;
gofmt clean; go test -count=1 -timeout 45m ./internal/gateway: ok (958.9s), at base 578053d6a.
Broken by hand: startRun back on claudeRunTTL(os.Environ()), three of
the four new cases red (client 5m, 5m over 1h, 1h over 5m); the forced
case passes on the old code too, as it should.

Not tried: a real request through a real Docker magpie. Linka's other
ask, a settings UI for the remote's built-in Claude Code and the Agents
page not detecting it, is not addressed here.

Reported-by: Linka
2026-11-07 23:25:10 +08:00
yetone dbc74414bb claude: a relayed run keeps its prompt cache as long as the user picked, not always an hour
linkaww (Discord #feedback, server v0.1.3237 in Docker, Claude Code
2.1.319) set the Agents page's prompt cache for the main conversation and
subagents to 5 minutes, and settings.json had "5m", but 237 of 241
relayed requests since 11-01 wrote an hour's cache. cleanClaudeEnv took
CLAUDE_CODE_PROMPT_CACHE_TTL out of the run's environment and put back
"1h" every time (17363b7e3, #626), for every run, warm-up and model test
the bridge starts, -p and the interactive helper alike. Claude Code reads
the variable before the setting, and a saved account's Claude Code reads
its own folder's settings.json anyway, so the pick never reached it.

The hour was pinned because magpie marks the caller's instructions (or
the history's last whole chunk) in the run's first message, and
Anthropic refuses a 1h mark after a 5m one. That reasoning stays: the
run's lifetime and magpie's mark are now one value.

- claudeRunTTL resolves the user's pick as Claude Code 2.1.316 does:
  FORCE_PROMPT_CACHING_5M, then CLAUDE_CODE_PROMPT_CACHE_TTL (in magpie's
  environment or settings.json's env), then settings.json's
  promptCacheTtl. Nothing set (or a value Claude Code doesn't take) is
  an hour, as before.
- cleanClaudeEnvTTL gives the run that value; FORCE_PROMPT_CACHING_5M
  is now blocked too, since it is folded into the value (before, a user
  with it set got a 5m Claude Code under magpie's 1h mark).
- Request.cacheTTL / runMark: magpie's mark in the first message has
  the same lifetime.
- cachePrefix.ttl: a run going on from a saved session keeps the
  lifetime it started with, so an old 1h mark never sits under a newer
  5m pick (an older session with none is an hour's). A replayed session
  has no marks and takes the pick.
- The incoming request's ttl is not followed for ordinary requests:
  Claude Code 2.1.316 sends ttl "5m" explicitly as its default for a
  non-subscription endpoint (MTe: {ttl:"5m",reason:"default"}), so a
  5m mark can't tell a pick from the default, and following it would
  turn the hour off for everyone. Opted-in client marks
  (X-Magpie-Cache-Marks) already run with Claude Code's caching off and
  are unchanged.

Run (mote, at this tree on origin/main 9ed0f1fa4):
- go test ./internal/gateway/ (-count=1, 45m): ok, 980s.
- go vet ./internal/gateway/ on darwin, GOOS=linux, GOOS=windows: ok.
- gofmt -l internal/: clean.
- TestClaudeRunKeepsTheUsersCacheTTL: six cases (nothing picked, Agents
  page 5m and 1h, settings.json env, magpie's env, forced 5m) through the
  bridge with a scripted Claude Code that logs its environment and the
  first message it is told.

Broken by hand:
- "CLAUDE_CODE_PROMPT_CACHE_TTL=1h" put back in cleanClaudeEnvTTL: four
  of the six cases red (each 5m pick).
- runMark always 1h: the same four red on the first message's mark.

Not tried: a real Claude subscription request with 5m picked (no real
run, so the cache_creation split was not read from Anthropic); Docker
web mode; Windows and Linux runs of the test (it uses a shell script and
skips on Windows). The full go test ./... runs under the suite lock on
mote after the push. Idle runs are still kept an hour (idleLongest); with
5m picked that only holds the process longer. Branch sessions (cut
copies) carry no lifetime and take the hour, which is always a valid
order.

Reported-by: linkaww
2026-11-07 20:44:51 +08:00
yetone 498b6419ff claude: a turn Anthropic refuses in the interactive mode as a third-party app's is asked again as claude -p, and the agent's prompt is remembered
Raven (Discord #general): Cindy with Pi as its engine, routed through
group/auto to a Claude subscription, failed every turn with "Anthropic
refused an interactive-mode turn on claude-opus-5-5 as a third-party
app's", and the message told them to turn the interactive mode off in
Settings, which makes every request of every agent run as -p (about twice
the plan count).

Now, with the interactive mode on:
- a refusal carrying "Third-party apps now draw from your extra usage",
  met before a byte of the reply reached the client (stream head, or a
  whole reply with no parts), is asked again once as claude -p
  (redoAsPrint); the client sees only the -p answer;
- the agent's system prompt (sha256 of its first 2KB, billing header
  dropped, so Pi's trailing <cwd> doesn't change it) is remembered for
  12h, and its next turns go straight to -p (wantTUI, req.tuiRefused,
  clientCache.print) while every other agent stays interactive;
- a refusal after the reply had begun (keepalive sent, or text said) is
  not redone, so nothing is spent twice; the prompt is still remembered
  and the message now says magpie runs its next turns as -p: ask again;
- a -p run that is refused too fails as before ("run as claude -p"),
  once, no loop;
- the setting is untouched; with it off (claudePrintMode) everything is
  -p as before. The run is the real claude binary, nothing else changed
  in what is sent.

This reverses the #4503 call (fbbdf6e05, v0.1.2754: no automatic -p redo)
and the 10-31/11-01 "nothing ever runs as -p with the interactive mode
on", for this refusal only. The switch's foot, the Settings text (en, zh,
zh-TW, ja, de) and docs/subsystems/claude-subscription-bridge.md say so.

Run (mote, at this head rebased on 1100ed649):
- go test -run 'ThirdParty|TUIRefusal|ClaudeTUI|ClaudeSubscription|ClaudePrint'
  ./internal/gateway/ ok; Budget/i18n tests in ./internal/gui ok
- gofmt -l clean; go vet ./internal/gateway (darwin, GOOS=linux,
  GOOS=windows) ok; GOOS=windows go vet ./internal/gui ok. GOOS=linux go
  vet ./internal/gui fails in wails' cgo-only linux files on mote, the same
  on main, untouched here.
- GUI, chromium and webkit: claude-mode, claude-tui-setting,
  claude-quota-onboarding, mobile-web, i18n-keys, gui-zh-tw, gui-ja,
  gui-de: 57 pass, 6 fail in each engine; the fails are i18n-keys "a
  plugin's words are its own" (#5327, #5332) and mobile-web (#3952,
  #5013), the same 6 at origin/main 1100ed649 alone.
- Red on the old code: the new tests run against 1d704f819 all fail (400,
  the old "turn the interactive mode off" message).

Broken by hand: dropping len(col.res.Parts)==0 from the whole-reply redo
turns TestClaudeTUIThirdPartyRefusalAfterWordsNotRedone/whole red;
dropping the refusedTUI call turns ...PromptRemembered, ...AfterStart and
...AfterWords/stream red.

Tests use the real Pi 1.1.0 system prompt (testdata/workdir/pi-1.1.0.json)
with its cwd changed per conversation.

Not tried: a real Claude account (no refused turn reproduced against
Anthropic; the refusal text is the one the reporter's log and #4503
carry). A -p run continuing with tool results under a remembered prompt
(the wantTUI resume path) has no test of its own.
2026-11-06 01:20:14 +08:00
yetone 9f17ad4c12 claude: the interactive mode takes safeguards and a client's cache marks
With the interactive mode on, nothing runs as -p any more (e5f66f8a6),
so a request carrying safeguards or a client's own cache marks was
refused. The owner (11-01) asked for every such request to work in the
interactive mode.

Safeguards: interactive Claude Code reads CLAUDE_CODE_EXTRA_BODY only
as it starts, so startRun puts them in the run's environment
(claudeEnvVars now cleans it and DISABLE_PROMPT_CACHING from what is
inherited). A turn whose safeguards changed ends the run, and the next
starts anew, told the whole conversation (setSafeguards).

Client cache marks: the helper pastes the words without their marks, so
the run keeps Claude Code's own prompt caching (no
DISABLE_PROMPT_CACHING, no client tail), and X-Magpie-Cache-Marks-Dropped
names every mark the client placed (clientCache.pasted, systemMarks).

The provider editor's tooltip, in every language, no longer lists them
as what only -p takes. The bridge doc says how each is handled.

Run:
- mote, at this tree: go test -count=1 -timeout 45m ./internal/gateway
  ./internal/claudetui: ok (gateway 897s, claudetui 10s)
- mote: node --test claude-mode, claude-tui-setting, i18n-keys: ok, all three
- New TestClaudeTUISafeguardsInEnv and TestClaudeTUIClientCacheKeepsItsOwn
  (a stand-in helper running the script Claude Code). With each change
  broken by hand, its test went red.
- Windows (GOOS=windows on mote) and Linux (wsl-run -tags nogui) go vet
  of the gateway: ok, on the tree with the image change on top.
- Real Claude Code 2.1.316, interactive, sandbox HOME: an extra body
  given in its environment reaches Anthropic (it answered 400
  "safeguards.0.dangerous_tool_use.classifier_context: Input should be
  an object" to a made-up shape).

Not tried: a real run with a valid safeguards shape (the test account
is at its 5-hour limit).
2026-11-01 18:52:44 +08:00
ggbdpq 81245e6cf6 gateway: a translated Messages ask keeps the cache marks its client put on it (#4571)
A plugin account only streams, so a client's whole-body Anthropic
Messages ask is translated: parsed into the request, built again for the
upstream, asked streamed and its answer assembled into one Message JSON.
The parse read none of the cache_control the client had put on its
blocks, and the build set its own marks — the system and the last block
of the last message, five minutes long. A client that marked the end of
its history, as Claude Code's auto mode classifier does, found that
boundary gone from the rebuilt body: the next turn, its history grown by
a block or two, matched only the fixed prefix up to the system block and
wrote the whole transcript again, and every write went out at five
minutes where the client had asked for an hour. The same ask with
stream:true is relayed as it came and shows none of it.

A translation of Anthropic's own now reads the request with its marks
(#3835's path) and the rebuild keeps them: a block the client marked is
marked again, the tail and the system take the client's ttl, and none of
magpie's own are added, so the mark that moves on with the history
stands at the same block the next turn. A mark on thinking, which
Anthropic does not mark, and one on a block the rebuild drops, are left
out. A set that fails the checks any Messages request must pass goes the
default way, its marks dropped as before, not refused with a 400 the old
translation never gave.

Run (macOS):
- Red before, green after: TestPluginWholeAskedKeepsTheClientCacheMarks
  (the boundary unmarked and both marks ttl-less on main, the client's
  blocks otherwise kept 1:1), TestPluginWholeAskedServesBadMarksAsBefore
  green before and after.
- go test -tags nogui -count=1 ./internal/gateway: ok.

Issue #4571

Generated-by: GLM-5.3-Flash (ZCode)

Broken by hand: with the anthropic.go hunks reverted,
TestPluginWholeAskedKeepsTheClientCacheMarks is red: the boundary is
unmarked, and the tail and system are ttl-less. Matches devin plugin
0.1.29 (30cd39f19, plugins#566), which carries the client's
cache_control into its prompt cache options: the marks now reach the
plugin. The next commit fixes this one's parse skipping unsignCalls.
2026-11-01 02:45:01 +08:00
ggbdpqandyetone e31ccf2307 gateway: a classifier's own cache marks are kept, and a moved mark leaves its old block boundary in place (#3835)
Claude Desktop's auto mode classifier marks its transcript blocks with
native cache_control but sends none of magpie's private headers, so
serveSubscription took the default parse and the marks were dropped.
And even a request that opted in lost its older boundaries:
renderCachedParts ended a block only where a mark still stood, so a
mark that moved on with the conversation's growth let the block it
used to end merge into the next marked one. Anthropic's prefix check
looks back over block boundaries, not into them: the boundary gone,
each classifier turn found none of the last one's write and wrote the
whole transcript again (about 170k tokens a turn at the reporter's
site).

A part that came from one of the client's own content blocks now ends
its rendered block whether or not it still carries a mark; only the
mark's presence adds cache_control. A classifier-shaped Messages body
carrying cache_control is parsed for its marks like an opted-in
client's. Plain-string messages still merge into history chunks, so a
retained prefix reaches as far back as it did.

Changed from ggbdpq's patch: the classifier never asked for its marks
through X-Magpie-Cache-Marks, so a set the bridge can't keep (a TTL
order Anthropic refuses, more than four marks) now goes the default
way, as before, instead of being refused with a 400 that the old code
never gave. TestClaudeClientCacheClassifierBadMarksServedAsBefore
holds it. The bridge doc says so.

Run (mote, macOS):
- Red on origin/main (the reporter's offline repro, renamed beside the
  other client-cache tests): client_marks 6 -> 6 blocks with 307
  reusable bytes, as the issue reports; the classifier's marks dropped
  without the header.
- go test -tags nogui -count=1 -run 'TestClaudeClientCache|TestAudit|
  TestClaude|TestAutoMode|TestServerReview' ./internal/gateway: ok.
- Broken by hand: the fallback removed, the new bad-marks test red
  ("refused before run startup: 400 ... a ttl='1h' cache_control block
  must not come after a ttl='5m'"); restored, green.
- gofmt -l clean. go vet (darwin, GOOS=windows, GOOS=linux) ok on
  gateway and provider. Full suite at b80d1ba7b (this commit, on the
  #2937 one, rebased on ddb1701fe): go test -tags nogui -count=1
  -timeout 45m ./... , 81 packages ok, no FAIL (gateway 755s). Other
  sessions' suites ran on mote at the same time (load ~20 to 30).
- Rebased on 2f65a33aa (gateway.go and providers-accounts.md changed
  upstream, in unrelated lines): gateway, provider, plugin and library
  rerun with -count=1 -timeout 45m, all ok.
- Then rebased on a0cb8b646 (Ark web search, gateway.go): go vet and
  -run 'TestClaude|TestAutoMode|TestExtraBody|TestHeaders|TestAudit|
  TestServerReview|Ark|Search' on gateway and provider at the pushed
  head, ok.

Not tried: a real Claude subscription A/B of the classifier's cache
reads (it would spend ~170k tokens a turn on the owner's live account);
the gain rests on the offline repro's block counts.

Fixes #3835

Co-authored-by: yetone <yetoneful@gmail.com>
2026-10-30 22:48:39 +08:00
yetone ec64543952 claude: a switch gives a Claude subscription's run the agent's instructions as its system prompt, in place of Claude Code's
Every request through a Claude subscription is answered by the real
Claude Code, which sends its own system prompt, with the agent's
instructions in the run's first user message. Settings › Replies › Short
Claude system prompt (claudeLeanPrompt, off by default) starts the run
with --system-prompt-file holding the agent's instructions instead
(without a client Claude Code's billing line, plus the tool-choice
line), and the first message holds the conversation alone. The file is
under the distro's mount in WSL. A request with client cache marks
(#1717) is never lean. The mode is part of the run's identity, so a run
started in one mode never takes the other's turns. The row says the
risk: requests look less like Claude Code's own.

Measured with a real Claude subscription, Sonnet 5.5, Claude Code
2.1.301, off then on:
- chat client, ~600-token prompt, 2 tools, 3 turns: 10,048 -> 6,580
  input tokens (-35%)
- claude -p as the client, Read and Bash, 4 requests: 85,453/85,471 ->
  81,948/81,977 (-4%)
A fixed ~0.9-1.2K tokens a request.

Run at this head (rebased on 72d6103e2):
- go test -tags nogui -timeout 45m -count=1 ./...: all 66 packages ok
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok
- TestClaudeLeanPrompt*: 4 pass; each guard broken by hand goes red
  (cacheIdentity's lean bytes, the tool-results mode check, the
  client-cache exclusion, the WSL path)
- whole GUI suite (before the rebase, machine load ~300-430): the 23 red
  files were rerun alone here and on origin/main. mobile-web's settings
  screenshot differed from main because of the new row; it now takes
  the row out until BASE_REF has it, as it does for other new parts,
  and passes with claude-lean-prompt-setting (4 languages, 1100/420,
  chromium and webkit). The rest are red on main too or under load and
  already filed: usage-agents-hide (#2276, #2399), routing-bodies
  (#2559), routing-model-rest (#2115), sidebar-overlay-scrollbar
  (#1863); plugin-other-ways passed alone.
2026-10-17 04:39:59 +08:00
deephbz d9e87eb328 gateway: clients opt into Claude subscription cache marks and TTLs (#1717)
Problem:
Messages clients need control of cache boundaries and TTLs when a Claude
subscription answers. Ordinary clients must retain their run identity,
prompt and environment. A routing group's API-key member keeps its marks
and must not report the subscription bridge's drops.

Change:
Select client-owned marks only with X-Magpie-Cache-Marks: client. Map system
and fresh-history boundaries and the request tail, default missing TTLs to
5m, validate slot and TTL order, and separate opted-in run identities.
Retain prefix constraints across live and saved runs. Report unmappable
marks only for the Claude subscription try. Bound its selection hold to
two seconds and clear the report and hold for a non-Claude fallback.
Check ordinary identity bytes without a version-specific hash golden.

What was run:
Sandbox HOME, nogui: go vet ./... on darwin; gateway vet with GOOS=linux
and GOOS=windows; full gateway tests; focused cache and usage tests with
-race. gofmt and git diff --check passed. The group probe failed before
the fix with tools:1 on the API-key reply in both routing orders and both
stream modes. Hand-broken candidate scoping, stale report clearing,
keepalive holds and ordinary identity bytes each failed behavior tests.
Live, Claude Code on a Claude subscription and an Anthropic API key,
through a recording proxy: in a group whose API-key member answers, in
either order and both stream modes, the reply has no dropped-mark header
and upstream receives the tool mark; a Claude answer reports tools:1; a
failed Claude try followed by an API-key answer leaves no report. With a
delayed API-key reply, the group's first keepalive came 0.85 s after a
direct request's. Without the header, the outgoing request equals one
from a gateway built at the same base. No GUI or real Linux/Windows
execution.
2026-10-16 14:16:51 +08:00