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.
This commit is contained in:
@@ -130,6 +130,40 @@ and sends keepalives without the dropped-mark header. Later fallback can
|
||||
also change the selected run after headers have been sent. Reporting never
|
||||
fails the request or delays an ordinary request's keepalives.
|
||||
|
||||
## The caller's instructions as the system prompt (`claudeLeanPrompt`)
|
||||
|
||||
Every run is the real Claude Code. By default it keeps Claude Code's own
|
||||
system prompt, and the caller's instructions go in the run's first user
|
||||
message inside `<external_system_instructions>`. Settings › Models ›
|
||||
Replies › Short Claude system prompt (`claudeLeanPrompt`, off by default)
|
||||
starts a run with `--system-prompt-file` instead. The file is `system.md`
|
||||
in the run's temp folder, under the distro's mount in WSL (`claudeCLI.file`).
|
||||
It holds `leanSystem`: the caller's instructions without a client Claude
|
||||
Code's billing line, plus the tool-choice line. The first message then holds
|
||||
the conversation alone. Claude Code still sends its billing block and its
|
||||
identity line, so requests come from the real binary. They no longer carry
|
||||
Claude Code's prompt, and that is the ban risk the setting names.
|
||||
|
||||
A request with client cache marks (#1717) is never lean: its system marks
|
||||
are placed in the first message. The mode is part of the run's identity
|
||||
(`cacheIdentity`, and the tool-results check in `serveSubscription`), so a
|
||||
run started in one mode never takes a turn of the other. After the setting
|
||||
changes, the next turn starts a run with the rendered history.
|
||||
|
||||
Measured on 2026-10-16 with a real Claude subscription on Sonnet 5.5,
|
||||
Claude Code 2.1.301:
|
||||
|
||||
| Client | Off | On |
|
||||
| --- | --- | --- |
|
||||
| Chat client, ~600-token prompt, 2 tools, 3 turns | 10,048 input tokens | 6,580 (−35%) |
|
||||
| `claude -p` as the client, Read and Bash, 4 requests | 85,453 / 85,471 | 81,948 / 81,977 (−4%) |
|
||||
|
||||
The saving is a fixed ~0.9–1.2K tokens a request. It is large for light
|
||||
clients and small for clients with Claude Code-sized prompts. Without any
|
||||
tool, Claude Code's built-in tools are already off (`--tools ""`). A run
|
||||
told the whole conversation again costs far more, because it writes the
|
||||
history to the 1h cache at 2×.
|
||||
|
||||
## Runtime path for a new turn
|
||||
|
||||
`serveClaudeSubscription`'s `start` tries, in order:
|
||||
@@ -478,6 +512,7 @@ carries none.
|
||||
|
||||
```sh
|
||||
go test -tags nogui ./internal/gateway/ -run '^TestClaudeClientCache' -count=1
|
||||
go test -tags nogui ./internal/gateway/ -run '^TestClaudeLeanPrompt' -count=1
|
||||
go test -tags nogui ./internal/claudecode/ -count=1
|
||||
go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn' -count=1
|
||||
```
|
||||
|
||||
@@ -207,6 +207,12 @@ func cacheIdentity(h hash.Hash, req *Request) {
|
||||
if c := req.clientCache; c != nil {
|
||||
fmt.Fprintf(h, "\x00client-cache:%v", c.system)
|
||||
}
|
||||
// a run started with the caller's instructions as its system prompt
|
||||
// was never told Claude Code's, and one started with Claude Code's has
|
||||
// them in its first message: neither goes on with the other's turns
|
||||
if req.leanPrompt {
|
||||
fmt.Fprint(h, "\x00lean-prompt")
|
||||
}
|
||||
}
|
||||
|
||||
func cacheDropped(w http.ResponseWriter, req *Request) {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/wslrun"
|
||||
)
|
||||
|
||||
// leanRun is what a run of a leanHarness was started with and told (its
|
||||
// log) and the system prompt file it was given, read while it ran, as the
|
||||
// file goes with the run.
|
||||
type leanRun struct {
|
||||
log string
|
||||
system string
|
||||
hasSys bool
|
||||
}
|
||||
|
||||
// newLeanHarness is a resumeHarness whose Claude Code also keeps the
|
||||
// system prompt file it is given.
|
||||
func newLeanHarness(t *testing.T) (*resumeHarness, func() []leanRun) {
|
||||
t.Helper()
|
||||
sys := t.TempDir()
|
||||
h := newScriptHarness(t, "ok", `prev=
|
||||
for a in "$@"; do
|
||||
if [ "$prev" = "--system-prompt-file" ]; then cp "$a" `+sys+`/$$; fi
|
||||
prev=$a
|
||||
done`)
|
||||
return h, func() []leanRun {
|
||||
var runs []leanRun
|
||||
for pid, log := range h.runs() {
|
||||
r := leanRun{log: log}
|
||||
if b, err := os.ReadFile(filepath.Join(sys, pid)); err == nil {
|
||||
r.system, r.hasSys = string(b), true
|
||||
}
|
||||
runs = append(runs, r)
|
||||
}
|
||||
return runs
|
||||
}
|
||||
}
|
||||
|
||||
// told is the run of runs that was told say.
|
||||
func told(t *testing.T, runs []leanRun, say string) leanRun {
|
||||
t.Helper()
|
||||
for _, r := range runs {
|
||||
if i := strings.Index(r.log, "\ntold "); i >= 0 && strings.Contains(r.log[i:], say) {
|
||||
return r
|
||||
}
|
||||
}
|
||||
t.Fatalf("no run was told %q: %+v", say, runs)
|
||||
return leanRun{}
|
||||
}
|
||||
|
||||
func leanSetting(t *testing.T, on bool) {
|
||||
t.Helper()
|
||||
if err := settings.Save(settings.Settings{ClaudeLeanPrompt: on}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = settings.Save(settings.Settings{}) })
|
||||
}
|
||||
|
||||
func (h *resumeHarness) post(body string, header ...string) {
|
||||
h.t.Helper()
|
||||
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
|
||||
for i := 0; i+1 < len(header); i += 2 {
|
||||
r.Header.Set(header[i], header[i+1])
|
||||
}
|
||||
var u Usage
|
||||
if code, msg := h.s.serveClaudeSubscription(httptest.NewRecorder(), r, provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u); code != 200 {
|
||||
h.t.Fatalf("%d %s", code, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// With Settings' lean prompt on, a run is started with the caller's own
|
||||
// instructions as its system prompt, in place of Claude Code's: given in a
|
||||
// file, the client Claude Code's billing line left out and its tool choice
|
||||
// said, and its first message holds the conversation alone. Off, the
|
||||
// instructions are in the first message, as before.
|
||||
func TestClaudeLeanPromptIsTheRunsSystemPrompt(t *testing.T) {
|
||||
h, runs := newLeanHarness(t)
|
||||
leanSetting(t, true)
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.301.eca; cc_entrypoint=cli; cch=00000;"},{"type":"text","text":"You are Aria, a notes assistant."}],"messages":[{"role":"user","content":"one"}]}`)
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":"Rules.","tools":[{"name":"look","input_schema":{"type":"object"}}],"tool_choice":{"type":"any"},"messages":[{"role":"user","content":"two"}]}`)
|
||||
|
||||
one := told(t, runs(), "one")
|
||||
if !one.hasSys || one.system != "You are Aria, a notes assistant." {
|
||||
t.Fatalf("the run's system prompt (given %t): %q\n%s", one.hasSys, one.system, one.log)
|
||||
}
|
||||
two := told(t, runs(), "two")
|
||||
if two.system != "Rules.\nYou must call at least one available tool before answering." {
|
||||
t.Fatalf("the tool choice is not in the system prompt: %q", two.system)
|
||||
}
|
||||
for _, r := range []leanRun{one, two} {
|
||||
said := r.log[strings.Index(r.log, "\ntold "):]
|
||||
if strings.Contains(said, "external_system_instructions") || strings.Contains(said, "Aria") || strings.Contains(said, "Rules.") || strings.Contains(said, "must call") {
|
||||
t.Fatalf("the run was told the instructions in its message too:\n%s", r.log)
|
||||
}
|
||||
}
|
||||
|
||||
leanSetting(t, false)
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":"You are Aria, a notes assistant.","messages":[{"role":"user","content":"three"}]}`)
|
||||
if off := told(t, runs(), "three"); off.hasSys || strings.Contains(off.log, "--system-prompt-file") || !strings.Contains(off.log, "external_system_instructions") {
|
||||
t.Fatalf("with the setting off, the run was given a system prompt (%t) or not told the instructions:\n%s", off.hasSys, off.log)
|
||||
}
|
||||
}
|
||||
|
||||
// A client that places its own cache marks (#1717) keeps Claude Code's
|
||||
// system prompt with the setting on: its marks on the system prompt are
|
||||
// placed in the run's first message.
|
||||
func TestClaudeLeanPromptNotWithClientCacheMarks(t *testing.T) {
|
||||
h, runs := newLeanHarness(t)
|
||||
leanSetting(t, true)
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":[{"type":"text","text":"Rules.","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"one"}]}`,
|
||||
"X-Magpie-Cache-Marks", "client")
|
||||
if r := told(t, runs(), "one"); r.hasSys || !strings.Contains(r.log, "external_system_instructions") {
|
||||
t.Fatalf("a client cache marks request was given a system prompt (%t):\n%s", r.hasSys, r.log)
|
||||
}
|
||||
}
|
||||
|
||||
// A run started with one system prompt goes on with no turn asked of the
|
||||
// other: one started lean was never told Claude Code's prompt, and one
|
||||
// started without it has the caller's instructions in its first message.
|
||||
// The next turn after the setting changed starts a run anew.
|
||||
func TestClaudeLeanPromptRunNotResumedAcrossTheSetting(t *testing.T) {
|
||||
h, runs := newLeanHarness(t)
|
||||
leanSetting(t, true)
|
||||
h.ask("Rules.", "one")
|
||||
h.ask("Rules.", "one", "two")
|
||||
if got := runs(); len(got) != 1 {
|
||||
t.Fatalf("the next turn with the setting unchanged started %d runs, want it to go on in the first", len(got))
|
||||
}
|
||||
leanSetting(t, false)
|
||||
h.ask("Rules.", "one", "two", "three")
|
||||
got := runs()
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("the turn after the setting went off went on in the lean run: %d runs", len(got))
|
||||
}
|
||||
if r := told(t, got, "three"); r.hasSys {
|
||||
t.Fatalf("the turn after the setting went off was told a lean run:\n%s", r.log)
|
||||
}
|
||||
}
|
||||
|
||||
// A Claude Code in WSL reads the system prompt file under the distro's
|
||||
// mount of the drive.
|
||||
func TestClaudeLeanPromptFileInWSL(t *testing.T) {
|
||||
c := claudeCLI{wsl: &wslrun.Tool{Path: "/usr/bin/claude"}}
|
||||
if got := c.file(`C:\Users\me\AppData\Local\Temp\magpie-claude-1\system.md`); got != "/mnt/c/Users/me/AppData/Local/Temp/magpie-claude-1/system.md" {
|
||||
t.Fatalf("%q", got)
|
||||
}
|
||||
if got := (claudeCLI{}).file("/tmp/x/system.md"); got != "/tmp/x/system.md" {
|
||||
t.Fatalf("%q", got)
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/wslrun"
|
||||
)
|
||||
|
||||
@@ -165,6 +166,7 @@ type subscriptionRun struct {
|
||||
safeguards json.RawMessage
|
||||
safeguardBeta string
|
||||
clientMarks bool
|
||||
lean bool // started with leanSystem as its system prompt
|
||||
cacheTail string
|
||||
cachePrefix cachePrefix
|
||||
timer *time.Timer
|
||||
@@ -535,6 +537,15 @@ func (c claudeCLI) env(env []string, configDir string) []string {
|
||||
return c.wsl.Env(env, names...)
|
||||
}
|
||||
|
||||
// file is where this Claude Code reads a file of magpie's at path: one in
|
||||
// WSL under the distro's mount of the drive.
|
||||
func (c claudeCLI) file(path string) string {
|
||||
if c.wsl != nil {
|
||||
return c.wsl.Linux(path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// exe is magpie's own executable, as this Claude Code starts it.
|
||||
func (c claudeCLI) exe() (string, error) {
|
||||
if c.wsl != nil {
|
||||
@@ -619,6 +630,16 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
"magpie": map[string]any{"command": exe, "args": []string{"claude-mcp-helper", callbackPath, toolsPath}},
|
||||
}})
|
||||
args := claudeCLIArgs(model, string(mcpConfig), req.Effort, req.WebSearch)
|
||||
if req.leanPrompt {
|
||||
// in a file of the run's own: instructions can be longer than
|
||||
// Windows lets a command line be
|
||||
systemPath := filepath.Join(tmp, "system.md")
|
||||
if err := os.WriteFile(systemPath, []byte(leanSystem(req)), 0o600); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
args = append(args, "--system-prompt-file", binary.file(systemPath))
|
||||
}
|
||||
if req.ThinkOff {
|
||||
// the client turned thinking off, as Claude Code's auto mode
|
||||
// classifier and its small asks do: a run at Claude Code's own
|
||||
@@ -708,6 +729,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, schema: len(req.Format.schema()) > 0, pending: map[string]chan mcpToolResult{}, stdin: stdin, owner: owner, effort: req.Effort, sessions: sessions}
|
||||
run.safeguardBeta = req.SafeguardBeta
|
||||
run.clientMarks = req.clientCache != nil
|
||||
run.lean = req.leanPrompt
|
||||
run.cachePrefix = prefix
|
||||
if user, _ := ownerAccount(owner); user != "" {
|
||||
run.loginVersion = provider.ClaudeLoginVersion(user)
|
||||
@@ -2539,7 +2561,8 @@ func (u cliUsage) gateway() Usage {
|
||||
func renderClaudePrompt(req *Request) ([]map[string]any, error) {
|
||||
var blocks []map[string]any
|
||||
var text strings.Builder
|
||||
if req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:") {
|
||||
// a lean run has them as its system prompt (leanSystem)
|
||||
if !req.leanPrompt && (req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:")) {
|
||||
text.WriteString("<external_system_instructions>\n")
|
||||
system := withoutBillingHeader(req.System)
|
||||
pos := 0
|
||||
@@ -2558,12 +2581,7 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) {
|
||||
}
|
||||
}
|
||||
text.WriteString(system[pos:])
|
||||
switch {
|
||||
case req.ToolChoice == "required":
|
||||
text.WriteString("\nYou must call at least one available tool before answering.")
|
||||
case strings.HasPrefix(req.ToolChoice, "name:"):
|
||||
fmt.Fprintf(&text, "\nYou must call the %s tool.", bridgeName(strings.TrimPrefix(req.ToolChoice, "name:")))
|
||||
}
|
||||
text.WriteString(toolChoiceAsk(req))
|
||||
text.WriteString("\n</external_system_instructions>\n\n")
|
||||
// The caller's instructions are a block of their own, marked for the
|
||||
// cache: Claude Code marks only the end of the message, so with them
|
||||
@@ -2650,6 +2668,27 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) {
|
||||
return closeBlocks(blocks, &text), nil
|
||||
}
|
||||
|
||||
// toolChoiceAsk is the client's tool choice in words, which Claude Code
|
||||
// takes no flag for.
|
||||
func toolChoiceAsk(req *Request) string {
|
||||
switch {
|
||||
case req.ToolChoice == "required":
|
||||
return "\nYou must call at least one available tool before answering."
|
||||
case strings.HasPrefix(req.ToolChoice, "name:"):
|
||||
return fmt.Sprintf("\nYou must call the %s tool.", bridgeName(strings.TrimPrefix(req.ToolChoice, "name:")))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// leanSystem is a lean run's system prompt (ClaudeLeanPrompt): the
|
||||
// caller's instructions without the client Claude Code's billing line, as
|
||||
// renderClaudePrompt tells them to a run that keeps Claude Code's own,
|
||||
// with its tool choice. Claude Code still puts its billing line and its
|
||||
// identity line before it, and marks it for the cache itself.
|
||||
func leanSystem(req *Request) string {
|
||||
return strings.TrimSpace(withoutBillingHeader(req.System) + toolChoiceAsk(req))
|
||||
}
|
||||
|
||||
// historyChunk is how many messages of the history renderClaudePrompt puts
|
||||
// in a block. Blocks end at the same messages in every run told the same
|
||||
// conversation, so their text is the same; 20 blocks back from a run's
|
||||
@@ -3951,6 +3990,9 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
|
||||
if req.clientCache != nil {
|
||||
req.clientCache.report = func() { cacheReportReady(w, req) }
|
||||
}
|
||||
// a client that places its own cache marks keeps Claude Code's prompt:
|
||||
// its system marks are placed in the run's first message (#1717)
|
||||
req.leanPrompt = name == "Claude Code" && req.clientCache == nil && settings.Load().ClaudeLeanPrompt
|
||||
if req.Format != nil && req.Format.schema() == nil {
|
||||
// --json-schema takes a schema only: any JSON object is asked for
|
||||
// in words
|
||||
@@ -3988,6 +4030,9 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
|
||||
if run != nil && run.clientMarks != (req.clientCache != nil) {
|
||||
run, how = nil, "cache mode changed"
|
||||
}
|
||||
if run != nil && run.lean != req.leanPrompt {
|
||||
run, how = nil, "system prompt mode changed"
|
||||
}
|
||||
if run != nil && !run.claimResume() {
|
||||
run, how = nil, answeredElsewhere
|
||||
}
|
||||
|
||||
@@ -146,6 +146,9 @@ type Tool struct {
|
||||
type Request struct {
|
||||
// clientCache is non-nil only for the Claude bridge's explicit opt-in.
|
||||
clientCache *clientCache
|
||||
// leanPrompt has the Claude bridge give the caller's instructions as
|
||||
// the run's system prompt, in place of Claude Code's (ClaudeLeanPrompt).
|
||||
leanPrompt bool
|
||||
|
||||
Model string
|
||||
System string
|
||||
|
||||
@@ -21116,7 +21116,17 @@ function renderReplies(s, keep) {
|
||||
fval.append(segs([...counts, ["", t("All")]], n,
|
||||
(v) => savePrefs({ ...keep, refusalRetries: v === "" ? null : Number(v) })));
|
||||
f.append(fwho, fval);
|
||||
box.append(r, l, f);
|
||||
// the agent's instructions as a Claude run's system prompt (off unless on)
|
||||
const c = el("div", "row pref");
|
||||
c.id = "claudeLeanRow";
|
||||
const cwho = el("div", "who");
|
||||
cwho.append(el("div", "name", t("Short Claude system prompt")),
|
||||
el("div", "sub wraps", t("A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk")));
|
||||
const cval = el("div", "val");
|
||||
cval.append(segs([["off", t("Off")], ["on", t("On")]], s.claudeLeanPrompt ? "on" : "off",
|
||||
(v) => savePrefs({ ...keep, claudeLeanPrompt: v === "on" })));
|
||||
c.append(cwho, cval);
|
||||
box.append(r, l, f, c);
|
||||
}
|
||||
|
||||
// renderDisabledModels: the models the user turned off for every request
|
||||
@@ -22048,7 +22058,7 @@ function prefsKeep(s) {
|
||||
redact: !!s.redact, redactPersonal: !!s.redactPersonal, redactKinds: s.redactKinds || {}, redactWords: s.redactWords || [], codexWarmup: s.codexWarmup || "",
|
||||
claudeWarmup: s.claudeWarmup || "", codexWarmAt: s.codexWarmAt || "", claudeWarmAt: s.claudeWarmAt || "",
|
||||
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats,
|
||||
memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, refusalRetries: s.refusalRetries ?? null,
|
||||
memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, refusalRetries: s.refusalRetries ?? null,
|
||||
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload,
|
||||
trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
|
||||
chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
|
||||
|
||||
@@ -304,6 +304,8 @@ const I18N = {
|
||||
"Replies": "回复",
|
||||
"Name the member in replies": "回复里写明成员",
|
||||
"Stop looping replies": "停止循环的回复",
|
||||
"Short Claude system prompt": "精简 Claude 系统提示词",
|
||||
"A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Claude 订阅以智能体自己的指令作为系统提示词,代替 Claude Code 的,每次请求约少 1K token。仍是真正的 Claude Code,但请求不再那么像 Claude Code 自己发出的,账号风险可能更高",
|
||||
"Ask again after a refusal": "被拒答后再问",
|
||||
"When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "供应商的安全过滤在还没说出任何内容前拒绝请求时,再换多少个账号或路由组成员去问。选“不再问”会直接把拒答交回:Claude Code 随后会像直连 Anthropic API 时一样,自己换到它的备用模型",
|
||||
"Never ask again": "不再问",
|
||||
@@ -4006,6 +4008,8 @@ const I18N = {
|
||||
"Replies": "回覆",
|
||||
"Name the member in replies": "回覆裡寫明成員",
|
||||
"Stop looping replies": "停止循環的回覆",
|
||||
"Short Claude system prompt": "精簡 Claude 系統提示詞",
|
||||
"A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Claude 訂閱以代理自己的指令作為系統提示詞,取代 Claude Code 的,每次請求約少 1K token。仍是真正的 Claude Code,但請求不再那麼像 Claude Code 自己發出的,帳號風險可能更高",
|
||||
"Ask again after a refusal": "被拒答後再問",
|
||||
"When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "供應商的安全過濾在還沒說出任何內容前拒絕請求時,再換多少個帳號或路由組成員去問。選「不再問」會直接把拒答交回:Claude Code 隨後會像直連 Anthropic API 時一樣,自己換到它的備用模型",
|
||||
"Never ask again": "不再問",
|
||||
@@ -7677,6 +7681,8 @@ const I18N = {
|
||||
"Replies": "応答",
|
||||
"Name the member in replies": "応答にメンバー名を記す",
|
||||
"Stop looping replies": "ループする応答を止める",
|
||||
"Short Claude system prompt": "Claude のシステムプロンプトを短く",
|
||||
"A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Claude サブスクリプションは Claude Code のものの代わりにエージェント自身の指示をシステムプロンプトとして応答し、リクエストごとに約 1K トークン少なくなります。本物の Claude Code のままですが、リクエストが Claude Code 自身のものらしくなくなるため、アカウントのリスクが高まる可能性があります",
|
||||
"Ask again after a refusal": "拒否のあと聞き直す",
|
||||
"When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "ベンダーの安全フィルターが何も言わないうちにリクエストを拒否したとき、ほかのアカウントやルーティンググループのメンバーにあと何回聞くか。「聞き直さない」は拒否をそのまま返します。Claude Code は Anthropic の API のときと同じく、自分のフォールバックモデルに切り替えます",
|
||||
"Never ask again": "聞き直さない",
|
||||
@@ -11358,6 +11364,8 @@ const I18N = {
|
||||
"Replies": "Antworten",
|
||||
"Name the member in replies": "Mitglied in Antworten nennen",
|
||||
"Stop looping replies": "Schleifende Antworten beenden",
|
||||
"Short Claude system prompt": "Kurzer Claude-Systemprompt",
|
||||
"A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Ein Claude-Abo antwortet mit den eigenen Anweisungen des Agenten als Systemprompt statt mit dem von Claude Code, etwa 1K Token weniger pro Anfrage. Weiterhin das echte Claude Code, aber seine Anfragen sehen Claude Codes eigenen weniger ähnlich, was das Konto stärker gefährden kann",
|
||||
"Ask again after a refusal": "Nach einer Ablehnung erneut fragen",
|
||||
"When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "Lehnt der Sicherheitsfilter eines Anbieters eine Anfrage ab, bevor etwas gesagt wurde: wie viele weitere Konten oder Mitglieder der Routing-Gruppe gefragt werden. Nie gibt die Ablehnung direkt zurück: Claude Code wechselt dann selbst zu seinem Ausweichmodell, wie bei Anthropics API",
|
||||
"Never ask again": "Nie",
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Settings › Models › Replies: Short Claude system prompt is Off, says what
|
||||
// it saves and what it risks, and On saves claudeLeanPrompt with the rest of
|
||||
// the settings kept, the page not moved by the click. In English, Chinese,
|
||||
// Japanese and German, 1100 and 420 wide.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const words = {
|
||||
en: { name: "Short Claude system prompt", head: "Replies", off: "Off", on: "On", sub: "1K fewer tokens", risk: "more at risk" },
|
||||
zh: { name: "精简 Claude 系统提示词", head: "回复", off: "关闭", on: "开启", sub: "约少 1K token", risk: "风险可能更高" },
|
||||
ja: { name: "Claude のシステムプロンプトを短く", head: "応答", off: "オフ", on: "オン", sub: "約 1K トークン少なく", risk: "リスクが高まる" },
|
||||
de: { name: "Kurzer Claude-Systemprompt", head: "Antworten", off: "Aus", on: "An", sub: "1K Token weniger", risk: "stärker gefährden" },
|
||||
};
|
||||
|
||||
function serve(lang, saved) {
|
||||
const settings = { lang, theme: "light", redact: true };
|
||||
const state = { agents: [], profiles: [], settings };
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/settings") {
|
||||
if (r.request().method() === "POST") {
|
||||
saved.push(JSON.parse(r.request().postData()));
|
||||
Object.assign(settings, saved.at(-1));
|
||||
}
|
||||
return json(settings);
|
||||
}
|
||||
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await r.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "ja", "de"]) for (const width of [1100, 420]) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang} ${width}: a short Claude system prompt is offered`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 900 } })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const saved = [];
|
||||
await page.route("**/*", serve(lang, saved));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=settings&tab=models");
|
||||
await settingsDrawn(page); // rows found are the ones that stay (#1659)
|
||||
const row = page.locator("#replyList #claudeLeanRow");
|
||||
await row.waitFor();
|
||||
// scrolled to as a reader does, with the wheel: WebKit at 420 put
|
||||
// back a scroll made from script
|
||||
await page.mouse.move(width / 2, 450);
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const box = await row.boundingBox();
|
||||
if (box && box.y >= 0 && box.y + box.height <= 900) break;
|
||||
await page.mouse.wheel(0, 120);
|
||||
await page.waitForTimeout(50);
|
||||
}
|
||||
assert.equal(await row.locator(".name").textContent(), w.name);
|
||||
const sub = await row.locator(".sub").textContent();
|
||||
assert(sub.includes(w.sub) && sub.includes(w.risk), sub);
|
||||
for (const part of [".name", ".sub", ".segs"]) {
|
||||
const fit = await row.locator(part).first().evaluate((e) => {
|
||||
const r = e.getBoundingClientRect();
|
||||
return e.scrollWidth <= e.clientWidth + 1 && r.width > 0 && r.right <= innerWidth + 1;
|
||||
});
|
||||
assert(fit, `${part} fits at ${width}`);
|
||||
}
|
||||
assert.equal(await page.locator("#replyList").evaluate((l) => l.previousElementSibling.textContent.trim()), w.head);
|
||||
const on = row.locator(".segs button", { hasText: w.on });
|
||||
const off = row.locator(".segs button", { hasText: w.off });
|
||||
assert.equal(await off.getAttribute("aria-pressed"), "true", "Off at first");
|
||||
|
||||
const before = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]);
|
||||
const b = await on.boundingBox();
|
||||
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
|
||||
await page.waitForFunction(() => document.querySelector("#claudeLeanRow"));
|
||||
for (let i = 0; i < 50 && !saved.length; i++) await page.waitForTimeout(50);
|
||||
assert.equal(saved.length, 1, "saved once");
|
||||
assert.equal(saved[0].claudeLeanPrompt, true);
|
||||
assert.equal(saved[0].noLoopGuard, false, "the row beside it kept");
|
||||
assert.equal(saved[0].redact, true, "the rest kept");
|
||||
assert.equal(saved[0].lang, lang);
|
||||
assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]), before, "the click moved nothing");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -349,6 +349,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
});
|
||||
await current.waitForTimeout(350);
|
||||
}
|
||||
// Replies' Short Claude system prompt row is new: until BASE_REF
|
||||
// has it, the page is compared with the row taken out;
|
||||
// claude-lean-prompt-setting.test.cjs covers the row.
|
||||
if (view === "settings" && !baselineFile("app.js").includes("claudeLeanRow")) {
|
||||
await current.locator("#claudeLeanRow").evaluate((r) => r.remove());
|
||||
await current.waitForTimeout(350);
|
||||
}
|
||||
const before = PNG.sync.read(await still(original));
|
||||
const after = PNG.sync.read(await still(current));
|
||||
const sameSize = before.width === after.width && before.height === after.height;
|
||||
|
||||
@@ -229,6 +229,13 @@ type Settings struct {
|
||||
// is stuck in a loop of the same few lines (#1359). Off, as by
|
||||
// default, the gateway ends such a reply with an error.
|
||||
NoLoopGuard bool `json:"noLoopGuard,omitempty"`
|
||||
// ClaudeLeanPrompt starts a Claude subscription's Claude Code run with
|
||||
// the caller's own instructions as its system prompt
|
||||
// (--system-prompt-file), in place of Claude Code's (about 1.1K tokens
|
||||
// a request on Sonnet 5.5), and not in its first message. Still the
|
||||
// real Claude Code, its billing line and identity line kept; off, as by
|
||||
// default, the run is the shape every Claude Code run has.
|
||||
ClaudeLeanPrompt bool `json:"claudeLeanPrompt,omitempty"`
|
||||
// RefusalRetries is how many more times a request the vendor's safety
|
||||
// filter refused, with nothing said, is asked of another account or
|
||||
// routing group member (#248), unset for every one left. 0 hands the
|
||||
|
||||
Reference in New Issue
Block a user