claude: no request-sized value on a run's command line or in its environment (#6848)
recih (on X) ran a long Claude Code session through the Claude subscription's interactive mode on a Linux server: every start, the resume and the replay alike, failed "fork/exec <magpie>: argument list too long", 8 502s, and every request after. Linux starts nothing with one argument or variable over 128KiB (MAX_ARG_STRLEN), and startRun put the conversation's safeguards in CLAUDE_CODE_EXTRA_BODY whole and the JSON schema in --json-schema whole. Now no value of a request's goes on the command line or in the environment over claudetui.StartValueMax (16KiB, under Windows' 32K variable too): - interactive mode: CLAUDE_CODE_EXTRA_BODY is a stand-in (startSafeguards: all when they fit, else without the parts Claude Code itself sheds, else []); guard.json keeps them whole and tap.js puts them in each request, as before. tap.js no longer sets the variable to a file over the bound, since Claude Code's MCP servers and tools inherit it. It is given no --json-schema (it never used it; the answer tool has the schema). - -p: a schema over the bound goes with the initialize request (jsonSchema, as the Agent SDK sends it). Claude Code passes over an initialize schema it can't use silently, so such a schema is compiled first and refused with a 400, as the flag's exit was (#3036). Other per-request starts checked (warmups, usage, sign-ins, other agents' bridges): nothing request-sized on argv or env. Run: - TestClaudeTUIStartBounded, TestClaudePrintStartBounded, TestClaudePrintSchemaPlaces (gateway) and TestTapPutsSafeguardsTooLargeForTheEnvironment (claudetui, bun and node): red on the old code on mote (152KB env, 277KB arg, 502 for a bad large schema, 204KB variable left by tap.js), and on Linux (wsl-run, magpie-desktop) the old code failed with the real "fork/exec .../magpie: argument list too long" and the tap's child start with E2BIG. All green on the new code on mote and Linux. - Real claude 2.1.316: an initialize jsonSchema answered structured_output {"city":"Paris"} (haiku); CLAUDE_CODE_EXTRA_BODY {"safeguards":[]} is sent as "safeguards":[] in every request (local listener, sandbox config). - gofmt; go vet (darwin, GOOS=linux, GOOS=windows) on the two packages; go test -tags nogui ./internal/claudetui ./internal/gateway on mote: ok claudetui 182.5s, ok gateway 1066.8s (at basee25210b6e). Rebased onaa3307585: the four new tests plus the guard, safeguards and schema tests of both packages again, ok. - Full suite (go test -tags nogui -timeout 45m ./... on mote): not finished at push; its result goes on #6848. Not tried: the reporter's own session; a real interactive run with safeguards over 16KiB end to end (the tap is tested with a FetchSession stub); a Claude Code the helper gives no tap (a path with whitespace) now sends the bounded stand-in instead of all the safeguards.
This commit is contained in:
@@ -540,7 +540,7 @@ A JSON schema is answered through an answer tool of magpie's
|
||||
(`claude_tui_schema.go`): interactive Claude Code takes `--json-schema`
|
||||
and does nothing with it (2.1.316, a real run: its result's
|
||||
`structured_output` is null), since its `StructuredOutput` tool is
|
||||
`-p`'s alone. `serveClaudeSubscription` compiles the schema
|
||||
`-p`'s alone, so an interactive run is given no `--json-schema` at all. `serveClaudeSubscription` compiles the schema
|
||||
(`compileAnswerSchema`: draft-07 unless it says otherwise, as `-p` reads
|
||||
one; a `$ref` outside itself is refused, never fetched) and adds the
|
||||
tool, `StructuredOutput` or a numbered name apart from the client's
|
||||
@@ -557,6 +557,26 @@ fit a `pattern`. A schema the compiler can't take is a 400 before any
|
||||
run (`TestClaudeTUISchemaAnswer`, `TestClaudeTUISchemaAskedOnce`,
|
||||
`TestAnswerTool`).
|
||||
|
||||
No value of a request's goes on a run's command line or in its
|
||||
environment over `startValueMax` (`claudetui.StartValueMax`, 16KiB):
|
||||
Linux refuses to start a program with one argument or variable over
|
||||
128KiB (`MAX_ARG_STRLEN`), Windows a variable over 32K characters. A
|
||||
long conversation's safeguards grew past it, and every start, the
|
||||
resume and the replay alike, failed `fork/exec …: argument list too
|
||||
long`, a 502 for every request after (#6848). The system prompt goes in
|
||||
files (`--system-prompt-file`), the messages on standard input, `-p`'s
|
||||
safeguards by `apply_flag_settings`, the interactive mode's in
|
||||
`guard.json` (above). `-p`'s JSON schema goes in `--json-schema` when it
|
||||
fits, else with the `initialize` request (`jsonSchema`, as the Agent SDK
|
||||
hands one over; a real 2.1.316 run answered `structured_output` from
|
||||
it). Claude Code passes over an `initialize` schema it can't use with
|
||||
no word of it, where the flag's exits (#3036), so such a schema is
|
||||
compiled first (`compileAnswerSchema`) and refused with a 400 before
|
||||
any run. `TestClaudeTUIStartBounded`, `TestClaudePrintStartBounded`,
|
||||
`TestClaudePrintSchemaPlaces` and
|
||||
`TestTapPutsSafeguardsTooLargeForTheEnvironment` hold it; on Linux the
|
||||
old code failed them with the real `argument list too long`.
|
||||
|
||||
A first message of any length is pasted: a conversation told whole to
|
||||
a new Claude Code (one older than its session, or a client's own) can
|
||||
run to megabytes. A real 3MB paste showed `[Pasted text` after 35s, and
|
||||
@@ -580,8 +600,11 @@ Safeguards are taken, each turn's in every request (#4804). Interactive
|
||||
Claude Code reads `CLAUDE_CODE_EXTRA_BODY` from its own environment as
|
||||
it builds each request, and nothing outside it changes that once it runs
|
||||
(2.1.316: a later `apply_flag_settings` or a rewritten `--settings` file
|
||||
changes nothing it sends). `startRun` puts them in its environment, and
|
||||
writes the same extra body to `guard.json` in the run's temp folder
|
||||
changes nothing it sends). `startRun` puts them in its environment
|
||||
(`startSafeguards`: all of them when the extra body fits
|
||||
`startValueMax`, else without the parts Claude Code itself sheds,
|
||||
`safeguardsKept`, else `[]`, a stand-in Claude Code still sends), and
|
||||
writes the whole extra body to `guard.json` in the run's temp folder
|
||||
(`guardBody`; every interactive run has the file, `{}` with no
|
||||
safeguards), named to the helper by `MAGPIE_CLAUDE_GUARD`
|
||||
(`claudetui.GuardEnv`). The helper hands it to Claude Code as WSL reads
|
||||
@@ -589,8 +612,11 @@ it, and takes it out of the environment otherwise. On each
|
||||
`/v1/messages` request whose body is a string with a `safeguards` key,
|
||||
`tap.js` reads the file, puts its `safeguards` there in place of Claude
|
||||
Code's, and sets `CLAUDE_CODE_EXTRA_BODY` in Claude Code's environment
|
||||
to it (the file without its `effort`), so the requests after are built
|
||||
with it. A JSON parse and stringify of a 2.1.316 body is byte for byte
|
||||
to it (the file without its `effort`) when it fits `envValueMax`
|
||||
(`StartValueMax`), so the requests after are built with it. A larger
|
||||
one leaves the stand-in there: what Claude Code starts (its MCP
|
||||
servers, tools) inherits the variable, and Linux starts nothing with
|
||||
one over 128KiB. A JSON parse and stringify of a 2.1.316 body is byte for byte
|
||||
the same, so the request is what Claude Code sends with that variable.
|
||||
At the first such request, or the first of the main turn's
|
||||
(`x-claude-code-request-class: main`), it writes `guard.json.live`. `setSafeguards` replaces the file (temp file and
|
||||
|
||||
@@ -44,6 +44,16 @@ const tapEnv = "MAGPIE_CLAUDE_TAP"
|
||||
// them in.
|
||||
const GuardEnv = "MAGPIE_CLAUDE_GUARD"
|
||||
|
||||
// StartValueMax bounds a value of a request's on a Claude Code run's
|
||||
// command line or in its environment: Linux refuses to start a program
|
||||
// with one over 128KiB (MAX_ARG_STRLEN), Windows a variable over 32K
|
||||
// characters, and a long conversation's safeguards grew past that, so
|
||||
// every try to resume or replay it failed "argument list too long"
|
||||
// (#6848). A larger one goes in a file or on standard input. tap.js
|
||||
// holds its CLAUDE_CODE_EXTRA_BODY to it (envValueMax), as what Claude
|
||||
// Code runs inherits it.
|
||||
const StartValueMax = 16 << 10
|
||||
|
||||
// how long a message of the transcript waits for its stream, and a turn's
|
||||
// end for its streams to end; and how often the tap is read while one
|
||||
// goes on
|
||||
|
||||
@@ -60,6 +60,8 @@
|
||||
}
|
||||
let streams = 0;
|
||||
let live = false;
|
||||
// StartValueMax (tap.go)
|
||||
const envValueMax = 16384;
|
||||
// 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
|
||||
@@ -99,8 +101,13 @@
|
||||
}
|
||||
let changed = false;
|
||||
if (safeguards) {
|
||||
// the variable is set to a file that fits what a program is
|
||||
// started with (envValueMax): whatever Claude Code runs inherits
|
||||
// it, and Linux refuses to start one with a variable over 128KiB
|
||||
// (#6848). A larger file's safeguards are put in each request
|
||||
// here, over the variable's stand-in
|
||||
const env = effort === undefined ? text : JSON.stringify(extra);
|
||||
if (process.env.CLAUDE_CODE_EXTRA_BODY !== env) process.env.CLAUDE_CODE_EXTRA_BODY = env;
|
||||
if (env.length <= envValueMax && 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;
|
||||
|
||||
@@ -2,6 +2,7 @@ package claudetui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -215,3 +216,93 @@ func TestTapAsksTheGuardFilesEffort(t *testing.T) {
|
||||
t.Skip("neither Bun nor Node is here to run tap.js")
|
||||
}
|
||||
}
|
||||
|
||||
// bigMain makes requests as Claude Code does in a run started with a
|
||||
// stand-in for safeguards too large for its environment, then starts a
|
||||
// program, as Claude Code starts its MCP servers and tools.
|
||||
const bigMain = `const url = "https://api.anthropic.com/v1/messages?beta=true";
|
||||
const headers = { "x-claude-code-request-class": "main" };
|
||||
const body = (sg) => JSON.stringify({ model: "m", messages: [{ role: "user", content: "hi" }], safeguards: sg, stream: true });
|
||||
(async () => {
|
||||
const s = new Bun.FetchSession();
|
||||
await s.fetch(url, { method: "POST", headers, body: body(JSON.parse(process.env.CLAUDE_CODE_EXTRA_BODY).safeguards) });
|
||||
await s.fetch(url, { method: "POST", headers, body: body(JSON.parse(process.env.CLAUDE_CODE_EXTRA_BODY).safeguards) });
|
||||
let started = "ok";
|
||||
try {
|
||||
require("child_process").execFileSync(process.execPath, ["-e", "0"], { stdio: "ignore" });
|
||||
} catch (e) {
|
||||
started = String(e.code || e.message);
|
||||
}
|
||||
console.log(JSON.stringify({ env: process.env.CLAUDE_CODE_EXTRA_BODY.length, started }));
|
||||
})();
|
||||
`
|
||||
|
||||
// #6848: a long conversation's safeguards grew past what Linux starts a
|
||||
// program with (128KiB a variable), and every run given them in
|
||||
// CLAUDE_CODE_EXTRA_BODY failed "argument list too long". The run is
|
||||
// started with a stand-in; tap.js puts the guard file's whole in each
|
||||
// request, and leaves the variable, which whatever Claude Code starts
|
||||
// inherits, at StartValueMax or under: the program it starts after
|
||||
// starts.
|
||||
func TestTapPutsSafeguardsTooLargeForTheEnvironment(t *testing.T) {
|
||||
ran := false
|
||||
for _, rt := range []string{"bun", "node"} {
|
||||
path, err := exec.LookPath(rt)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ran = true
|
||||
t.Run(rt, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for name, js := range map[string]string{"stub.js": guardStub, "main.js": bigMain, "tap.js": string(tapJS)} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(js), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
big := `[{"type":"dangerous_tool_use","classifier_context":"` + strings.Repeat("x", 200<<10) + `"}]`
|
||||
guard := filepath.Join(dir, "guard.json")
|
||||
if err := os.WriteFile(guard, []byte(`{"safeguards":`+big+`}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pre := "--preload"
|
||||
if rt == "node" {
|
||||
pre = "-r"
|
||||
}
|
||||
cmd := exec.Command(path, pre, filepath.Join(dir, "stub.js"), pre, filepath.Join(dir, "tap.js"), filepath.Join(dir, "main.js"), guard)
|
||||
cmd.Env = append(os.Environ(), tapEnv+"="+filepath.Join(dir, "tap.jsonl"), GuardEnv+"="+guard, `CLAUDE_CODE_EXTRA_BODY={"safeguards":[]}`)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%v: %.2000s", err, out)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
|
||||
if len(lines) != 3 {
|
||||
t.Fatalf("told %.2000s", out)
|
||||
}
|
||||
want := `{"model":"m","messages":[{"role":"user","content":"hi"}],"safeguards":` + big + `,"stream":true}`
|
||||
for i, l := range lines[:2] {
|
||||
var m map[string]any
|
||||
if json.Unmarshal([]byte(l), &m) != nil || m["body"] != want {
|
||||
t.Fatalf("request %d wasn't given the guard file's safeguards: %.300s", i, l)
|
||||
}
|
||||
}
|
||||
var end struct {
|
||||
Env int
|
||||
Started string
|
||||
}
|
||||
if json.Unmarshal([]byte(lines[2]), &end) != nil || end.Env > StartValueMax || end.Started != "ok" {
|
||||
t.Fatalf("Claude Code's environment after: %s", lines[2])
|
||||
}
|
||||
})
|
||||
}
|
||||
if !ran {
|
||||
t.Skip("neither Bun nor Node is here to run tap.js")
|
||||
}
|
||||
}
|
||||
|
||||
// tap.js holds the variable it sets to the bound the gateway starts runs
|
||||
// with.
|
||||
func TestTapHoldsTheStartBound(t *testing.T) {
|
||||
if want := fmt.Sprintf("const envValueMax = %d;", StartValueMax); !strings.Contains(string(tapJS), want) {
|
||||
t.Fatalf("tap.js has no %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// startSizes is how a script harness's run logs the size of each of its
|
||||
// arguments and environment variables as it starts.
|
||||
const startSizes = `for a in "$@"; do echo "arglen ${#a}" >> $log; done
|
||||
awk 'BEGIN { for (k in ENVIRON) print "envlen " (length(k) + 1 + length(ENVIRON[k])) }' >> $log`
|
||||
|
||||
// bigSafeguards and bigSchema are each over 128KiB, what Linux starts a
|
||||
// program with in one argument or variable.
|
||||
var (
|
||||
bigContext = strings.Repeat("The user allows edits in the project. ", 4000)
|
||||
bigSafeguards = `"safeguards":[{"type":"dangerous_tool_use","classifier_context":"` + bigContext + `"}],`
|
||||
bigSchema = func() string {
|
||||
props := make([]string, 0, 3000)
|
||||
for i := range 3000 {
|
||||
props = append(props, `"field_`+strconv.Itoa(i)+`_of_the_answer":{"type":"string","description":"one of the answer's many fields"}`)
|
||||
}
|
||||
return `{"type":"object","properties":{` + strings.Join(props, ",") + `}}`
|
||||
}()
|
||||
)
|
||||
|
||||
// askRaw sends a turn of body's and returns the status, whatever it is.
|
||||
func (h *resumeHarness) askRaw(body string) int {
|
||||
h.t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
var u Usage
|
||||
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
|
||||
code, _ := h.s.serveClaudeSubscription(rec, r, provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u)
|
||||
return code
|
||||
}
|
||||
|
||||
// startBound checks each run's arguments and environment: no value over
|
||||
// startValueMax that the run wasn't started with before this change (the
|
||||
// test's own environment), and no more than 64KiB of them in all.
|
||||
func startBound(t *testing.T, runs map[string]string) {
|
||||
t.Helper()
|
||||
if len(runs) == 0 {
|
||||
t.Fatal("no run started")
|
||||
}
|
||||
base := 0
|
||||
for _, kv := range os.Environ() {
|
||||
base = max(base, len(kv))
|
||||
}
|
||||
for name, log := range runs {
|
||||
total := 0
|
||||
sc := bufio.NewScanner(strings.NewReader(log))
|
||||
sc.Buffer(nil, 4<<20)
|
||||
for sc.Scan() {
|
||||
kind, n, ok := strings.Cut(sc.Text(), " ")
|
||||
if kind != "arglen" && kind != "envlen" || !ok {
|
||||
continue
|
||||
}
|
||||
size, _ := strconv.Atoi(n)
|
||||
if size > startValueMax && size > base {
|
||||
t.Fatalf("run %s was started with a %s of %d bytes, over %d", name, strings.TrimSuffix(kind, "len"), size, startValueMax)
|
||||
}
|
||||
if kind == "arglen" {
|
||||
total += size
|
||||
}
|
||||
}
|
||||
if total > 64<<10 {
|
||||
t.Fatalf("run %s was started with %d bytes of arguments", name, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// #6848: a long conversation's safeguards and a large JSON schema went on
|
||||
// a run's command line and in its environment whole, and Linux refused
|
||||
// to start it, "argument list too long", the resume and the replay alike:
|
||||
// every request after was a 502. The interactive mode's run is given the
|
||||
// safeguards in its guard file, a bounded stand-in in the variable, and
|
||||
// no schema (its answer tool has it).
|
||||
func TestClaudeTUIStartBounded(t *testing.T) {
|
||||
h := tuiScriptHarness(t, startSizes)
|
||||
h.extra = bigSafeguards
|
||||
h.ask("rules", "a1")
|
||||
startBound(t, h.runs())
|
||||
for _, log := range h.runs() {
|
||||
if !strings.Contains(log, "envlen ") {
|
||||
t.Fatalf("the run logged no sizes: %.500s", log)
|
||||
}
|
||||
}
|
||||
body := `{"model":"claude-sonnet-5","max_tokens":100,` + bigSafeguards + `"system":"rules","messages":[{"role":"user","content":"b1"}],"output_config":{"format":{"type":"json_schema","schema":` + bigSchema + `}}}`
|
||||
h.askRaw(body)
|
||||
startBound(t, h.runs())
|
||||
for _, log := range h.runs() {
|
||||
if strings.Contains(log, "--json-schema") {
|
||||
t.Fatalf("the interactive mode was given --json-schema: %.300s", log)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -p is given safeguards over standard input (apply_flag_settings) and a
|
||||
// schema too large for its command line with its initialize, as the
|
||||
// Agent SDK hands one over.
|
||||
func TestClaudePrintStartBounded(t *testing.T) {
|
||||
h := newScriptHarness(t, "ok", startSizes)
|
||||
body := `{"model":"claude-sonnet-5","max_tokens":100,` + bigSafeguards + `"system":"rules","messages":[{"role":"user","content":"a1"}],"output_config":{"format":{"type":"json_schema","schema":` + bigSchema + `}}}`
|
||||
h.askRaw(body)
|
||||
runs := h.runs()
|
||||
startBound(t, runs)
|
||||
seen := false
|
||||
for _, log := range runs {
|
||||
for _, l := range strings.Split(log, "\n") {
|
||||
if !strings.HasPrefix(l, "control ") || !strings.Contains(l, `"subtype":"initialize"`) {
|
||||
continue
|
||||
}
|
||||
var m struct {
|
||||
Request struct {
|
||||
JSONSchema json.RawMessage `json:"jsonSchema"`
|
||||
} `json:"request"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.TrimPrefix(l, "control ")), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(m.Request.JSONSchema) == string(cliSchema(json.RawMessage(bigSchema))) {
|
||||
seen = true
|
||||
}
|
||||
}
|
||||
if strings.Contains(log, "--json-schema") {
|
||||
t.Fatalf("a schema too large for the command line was put there: %.300s", log)
|
||||
}
|
||||
if !strings.Contains(log, bigContext[:200]) || !strings.Contains(log, "apply_flag_settings") {
|
||||
t.Fatalf("the run wasn't told the safeguards: %.300s", log)
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
t.Fatal("no run's initialize has the schema")
|
||||
}
|
||||
}
|
||||
|
||||
// A schema that fits goes on -p's command line as before, where Claude
|
||||
// Code exits over one it can't use (#3036); a large one it can't use is
|
||||
// a 400 before a run starts, as an initialize's is passed over.
|
||||
func TestClaudePrintSchemaPlaces(t *testing.T) {
|
||||
h := newScriptHarness(t, "ok", "")
|
||||
small := `{"type":"object","properties":{"a":{"type":"string"}}}`
|
||||
h.askRaw(`{"model":"claude-sonnet-5","max_tokens":100,"system":"rules","messages":[{"role":"user","content":"a1"}],"output_config":{"format":{"type":"json_schema","schema":` + small + `}}}`)
|
||||
got := false
|
||||
for _, log := range h.runs() {
|
||||
got = got || strings.Contains(log, "--json-schema "+small)
|
||||
}
|
||||
if !got {
|
||||
t.Fatalf("a small schema wasn't on the command line: %v", h.runs())
|
||||
}
|
||||
bad := strings.Replace(bigSchema, `"type":"string"`, `"type":"strng"`, 1)
|
||||
before := len(h.runs())
|
||||
if code := h.askRaw(`{"model":"claude-sonnet-5","max_tokens":100,"system":"rules","messages":[{"role":"user","content":"b1"}],"output_config":{"format":{"type":"json_schema","schema":` + bad + `}}}`); code != 400 {
|
||||
t.Fatalf("a large schema Claude Code can't use: %d", code)
|
||||
}
|
||||
if len(h.runs()) != before {
|
||||
t.Fatal("a run started for a schema refused")
|
||||
}
|
||||
}
|
||||
@@ -1058,9 +1058,6 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
// tokens a check on the subscription (0xAncientTwo)
|
||||
args = append(args, "--thinking", "disabled")
|
||||
}
|
||||
if len(req.Format.schema()) > 0 {
|
||||
args = append(args, "--json-schema", string(cliSchema(req.Format.schema())))
|
||||
}
|
||||
// in the caller's own folder when it says which it is and it is one
|
||||
// here (clientWorkDir): Claude Code tells the model the folder it runs
|
||||
// in as its working directory, and a model told magpie's folder wrote
|
||||
@@ -1260,6 +1257,28 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
turn = release
|
||||
}
|
||||
defer turn()
|
||||
// a schema is the request's, of any size: -p is given one that fits
|
||||
// a command line there (startValueMax), and a larger one with its
|
||||
// initialize (initSchema), as the Agent SDK hands it over; Linux
|
||||
// refuses to start a program with an argument over 128KiB, "argument
|
||||
// list too long" (#6848). The interactive mode is given none: its
|
||||
// answer tool has the schema, in the run's tools file
|
||||
var initSchema json.RawMessage
|
||||
if schema := cliSchema(req.Format.schema()); len(schema) > 0 && !tui {
|
||||
if len(schema) <= startValueMax {
|
||||
args = append(args, "--json-schema", string(schema))
|
||||
} else {
|
||||
// an initialize's schema Claude Code can't use is passed
|
||||
// over, structured output off with no word of it (a real
|
||||
// 2.1.316), where the flag's exits; it is checked here, a
|
||||
// 400 as the flag's is (#3036)
|
||||
if _, err := compileAnswerSchema(schema); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, &cliSchemaRefused{"Claude Code can't use the request's JSON schema: " + err.Error()}
|
||||
}
|
||||
initSchema = schema
|
||||
}
|
||||
}
|
||||
noteClaudeRun(code)
|
||||
noteEntry(ctx, tui, code)
|
||||
var cmd *exec.Cmd
|
||||
@@ -1297,7 +1316,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
guard := ""
|
||||
if tui {
|
||||
if len(req.Safeguards) > 0 {
|
||||
env = append(env, "CLAUDE_CODE_EXTRA_BODY="+claudeExtraBody(req.Safeguards, ""))
|
||||
env = append(env, "CLAUDE_CODE_EXTRA_BODY="+claudeExtraBody(startSafeguards(req.Safeguards), ""))
|
||||
}
|
||||
guard = filepath.Join(tmp, "guard.json")
|
||||
if writeGuard(guard, guardBody(req.Safeguards, "")) == nil {
|
||||
@@ -1394,7 +1413,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
run.readOutput(stdout)
|
||||
}()
|
||||
|
||||
if len(req.Safeguards) > 0 || from != nil || run.clientMarks || tui {
|
||||
if len(req.Safeguards) > 0 || from != nil || run.clientMarks || tui || initSchema != nil {
|
||||
// Initialize the SDK before applying settings. Send the potentially
|
||||
// large context over stdin rather than an environment entry. A
|
||||
// Claude Code resumed from a saved session answers it only once
|
||||
@@ -1410,7 +1429,11 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
if tui {
|
||||
wait = tuiInitWait
|
||||
}
|
||||
if err := run.cliControlWithin(ctx, map[string]any{"subtype": "initialize"}, wait); err != nil {
|
||||
hello := map[string]any{"subtype": "initialize"}
|
||||
if initSchema != nil {
|
||||
hello["jsonSchema"] = initSchema
|
||||
}
|
||||
if err := run.cliControlWithin(ctx, hello, wait); err != nil {
|
||||
run.abort()
|
||||
if tui && client && configDir == "" && run.saidOnEnd(claudetui.Untrusted) {
|
||||
kept = true
|
||||
@@ -1657,6 +1680,29 @@ func claudeExtraBody(raw json.RawMessage, tail string) string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// startValueMax bounds a value of a request's on a run's command line
|
||||
// or in its environment (claudetui.StartValueMax, #6848).
|
||||
const startValueMax = claudetui.StartValueMax
|
||||
|
||||
// startSafeguards are the safeguards an interactive run is started with
|
||||
// in CLAUDE_CODE_EXTRA_BODY: all of them when they fit startValueMax.
|
||||
// Larger ones are in the run's guard file whole, which its tap puts in
|
||||
// each request in place of these; without the parts Claude Code itself
|
||||
// sheds over its own budget (safeguardsKept) when that fits, so a
|
||||
// Claude Code that didn't load the tap still says what the user
|
||||
// allows, else an empty list, which Claude Code still sends (a real
|
||||
// 2.1.316), marking the requests the tap puts them in. A Claude Code
|
||||
// the helper gives no tap sends the stand-in.
|
||||
func startSafeguards(raw json.RawMessage) json.RawMessage {
|
||||
if len(claudeExtraBody(raw, "")) <= startValueMax {
|
||||
return raw
|
||||
}
|
||||
if kept := safeguardsKept(raw); len(claudeExtraBody(kept, "")) <= startValueMax {
|
||||
return kept
|
||||
}
|
||||
return json.RawMessage("[]")
|
||||
}
|
||||
|
||||
// safeguardVaries is what Claude Code's classifier context carries that
|
||||
// changes from one request to the next, the parts 2.1.316 itself names as
|
||||
// variable and leaves out over its 256KB budget (its "shed" list): the
|
||||
|
||||
Reference in New Issue
Block a user