claude: a JSON schema is answered in the interactive mode, through an answer tool

With the interactive mode on, a request with a JSON schema was refused
with a 400 since v0.1.2592: interactive Claude Code takes --json-schema and does nothing
with it, its StructuredOutput tool being -p's alone. It now runs in the
interactive mode like any other request.

- serveClaudeSubscription compiles the schema (santhosh-tekuri/jsonschema
  v6.0.3, draft-07 unless it says otherwise, as -p reads one; a $ref
  outside the schema is refused, never fetched) and adds an answer tool,
  StructuredOutput or a numbered name apart from the client's tools, with
  the schema as its input schema, through the bridge's MCP server. A
  schema that can't be compiled is a 400 before any run.
- mcpCall checks each call against the schema: one that doesn't fit is
  told why (isError) to be made again, as -p's is; one that fits is kept.
- At the turn's result the kept input is the reply's structured output.
  A turn that ended with no call is told once to call the tool, and
  fails "no answer fitting the schema" if it still doesn't. Neither the
  call nor the words around it reach the client.
- claudePrint no longer lists the schema. The two refusal tests
  (TestClaudeTUIOnRefusesPrint, TestClaudeTUIRefusalIsNoAccountsFault)
  now use the case that is still refused before any run: an image by
  its URL that can't be downloaded (127.0.0.1, which magpie never
  fetches).
- The provider editor's card no longer says -p takes "a JSON schema"
  the interactive mode can't (en, zh-CN, zh-TW, ja, de).
- docs/subsystems/claude-subscription-bridge.md: the refusal list, and
  how a schema is answered.

Run:
- A real run, haiku, the test account in a sandbox HOME, real Claude
  Code 2.1.316 through the helper with --json-schema and a stdio MCP
  server named magpie serving the answer tool and its description: the
  result's structured_output was null (the premise), and the model
  called mcp__magpie__StructuredOutput at once with
  {"color":"Sky blue","hex":"#87CEEB"}, which fits the schema's
  pattern. 7.2s, one turn. Not run: the whole gateway path with a real
  account (the unit tests drive it with Claude Code's real transcript
  rows).
- mote, at this tree (base 14e351378, origin/main just fetched): gofmt,
  go vet (darwin, windows, linux -tags nogui), go mod verify ok;
  go test ./internal/gateway ./internal/claudetui: claudetui ok, gateway
  red in TestCodexPoolSaysTheClientsVersion only, which is #4807 (red in
  a full package run on mote, another test's Codex identity reaches it);
  alone at this tree -count=3 ok. claude-mode 44/44 and i18n-keys 4/4 in
  chromium and webkit.
- Broken by hand: answer() taking every call without checking it made
  TestClaudeTUISchemaAnswer red ("a call that doesn't fit was told
  Answer received.").
This commit is contained in:
yetone
2026-11-02 00:35:21 +08:00
parent 14e3513780
commit a25d3d0815
13 changed files with 339 additions and 27 deletions
+24 -2
View File
@@ -284,9 +284,31 @@ asked in turn (#4778: 15 tries across 3 accounts, some rested). Its
words avoid "Models" just before the error's type: "Models ›
Replies…\",\"type\":\"invalid_request_error" read as a model not served
(`provider.ModelUnserved`), which made the 400 retryable again. That is
when (`claudeTUI`, `claudePrint`):
when (`claudeTUI`, `claudeMachineWhy`) this computer has no Claude Code
path or isn't macOS, Linux or Windows. Nothing a request asks is refused
any more (`claudePrint` keeps an image known by its URL, which
`serveClaudeSubscription` has downloaded before any run, below).
- the request has a JSON schema;
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
(`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
(`answerTool`), with the schema as its input schema, through the bridge's
MCP server. `mcpCall` checks each call against the schema (`answer`): one
that doesn't fit gets an `isError` result saying why, to be made again,
as `-p`'s is; one that fits is kept (`answerArgs`). At the turn's result
the kept input is the reply's `structured_output`; a turn that ended
without one is told once to call the tool (`answerAsk`), and fails "no
answer fitting the schema" when it still doesn't. Neither the call nor
the words around it reach the client (`r.schema`). A real run (haiku,
11-02) called `mcp__magpie__StructuredOutput` at once, with input that
fit a `pattern`. A schema the compiler can't take is a 400 before any
run (`TestClaudeTUISchemaAnswer`, `TestClaudeTUISchemaAskedOnce`,
`TestAnswerTool`).
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
+1
View File
@@ -53,6 +53,7 @@ require (
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
+2
View File
@@ -80,6 +80,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU=
+3 -3
View File
@@ -36,9 +36,9 @@ func TestClaudeTUICodes(t *testing.T) {
was := claudeTUIRuns
claudeTUIRuns = true
t.Cleanup(func() { claudeTUIRuns = was })
req := &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}}, Format: &Format{Type: "json_schema", Schema: []byte(`{"type":"object"}`)}}
if tui, code := claudeTUI(req, claudeCLI{path: "/usr/local/bin/claude"}); tui || code != "schema" {
t.Fatalf("with a schema: %v %q", tui, code)
req := &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image, URL: "https://example.com/a.png"}}}}}
if tui, code := claudeTUI(req, claudeCLI{path: "/usr/local/bin/claude"}); tui || code != "image" {
t.Fatalf("an image by its URL: %v %q", tui, code)
}
if tui, code := claudeTUI(req, claudeCLI{}); tui || code != "missing" {
t.Fatalf("no Claude Code: %v %q", tui, code)
+49 -9
View File
@@ -60,6 +60,7 @@ import (
"time"
"unicode/utf8"
"github.com/santhosh-tekuri/jsonschema/v6"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/claudecode"
"github.com/yetone/magpie/internal/claudetui"
@@ -296,8 +297,15 @@ type subscriptionRun struct {
// client never sees
search func(ctx context.Context, query string) (string, []Hit, error)
searchName string
begin func() Event
resume func() // after a resumed turn has its segment
// answerName is the interactive mode's answer tool for a request with
// a JSON schema (claude_tui_schema.go), its calls checked against
// answerSchema, and answerArgs the input of the one that fit, until the
// turn's result takes it. Under mu.
answerName string
answerSchema *jsonschema.Schema
answerArgs json.RawMessage
begin func() Event
resume func() // after a resumed turn has its segment
// patience, when set, is how long a tool call may park before the agent
// is told it is still running (its MCP client gives up on a call at a
@@ -1237,7 +1245,6 @@ func claudePrint(req *Request, binary claudeCLI) (code, why string) {
is bool
code, why string
}{
{len(req.Format.schema()) > 0, "schema", "a JSON schema"},
{urlImages(req.Messages) > 0, "image", "an image known by its URL"},
} {
if c.is {
@@ -3011,9 +3018,10 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
// message, as after Claude Code's own call. Only once a reply: told
// again, the words go to the client as written.
var calls textCalls
retell := false // the run is told to make its calls once this turn's result is in
retold := false // this reply was told so
var pmu sync.Mutex // held for each line, and by quiet's settle
retell := false // the run is told to make its calls once this turn's result is in
answerAsked := false // the interactive mode's turn was asked for its answer tool's call
retold := false // this reply was told so
var pmu sync.Mutex // held for each line, and by quiet's settle
var quiet *time.Timer
text := func(s string) {
if s != "" && !r.schema {
@@ -3073,7 +3081,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
name, ok := strings.CutPrefix(name, "mcp__magpie__")
r.mu.Lock()
name = declaredName(r.names, name)
search := r.search != nil && name == r.searchName
search := r.search != nil && name == r.searchName || r.answerName != "" && name == r.answerName
refused := r.allowed != nil && !r.allowed[name]
r.mu.Unlock()
// magpie answers its own web search, as Claude Code does
@@ -3336,8 +3344,23 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
}
return
}
if envelope.Type == "result" && r.schema && r.tui && inside && !envelope.IsError && !refused && !cut {
// the interactive mode's answer is its answer tool's call
// (claude_tui_schema.go); a turn that ended without one is
// asked for it once, and the reply goes on in its answer
if a := r.takeAnswer(); a != nil {
envelope.StructuredOutput = a
} else if r.answerName != "" && !answerAsked {
answerAsked = true
ask, _ := json.Marshal(map[string]any{"type": "user", "uuid": newUUID(), "message": map[string]any{"role": "user",
"content": []map[string]any{{"type": "text", "text": answerAsk(r.answerName)}}}})
if err := r.tell(ask); err == nil {
return
}
}
}
if envelope.Type == "result" {
retell = false
retell, answerAsked = false, false
// a turn that failed — out of quota, rate limited — ends with
// this and no message_stop, the CLI waiting on its next input:
// the reply ends here, or it would wait with it (#177)
@@ -4823,8 +4846,12 @@ func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) {
}
run.mu.Lock()
call.Name = declaredName(run.names, call.Name)
search, searchName := run.search, run.searchName
search, searchName, answerName := run.search, run.searchName, run.answerName
run.mu.Unlock()
if answerName != "" && call.Name == answerName {
run.answer(w, call.Arguments)
return
}
if search != nil && call.Name == searchName {
var a struct {
Query string `json:"query"`
@@ -5593,6 +5620,16 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
return writeError(w, from, 400, "Claude Code: "+err.Error()), err.Error()
}
}
// the interactive mode answers a schema through magpie's answer tool
var answer Tool
var answerSchema *jsonschema.Schema
if name == "Claude Code" && claudeTUIOn() && len(req.Format.schema()) > 0 {
if answerSchema, err = compileAnswerSchema(cliSchema(req.Format.schema())); err != nil {
return writeError(w, from, 400, "Claude Code: "+err.Error()), err.Error()
}
answer = answerTool(req.Tools, req.Format.schema())
req.Tools = append(slices.Clone(req.Tools), answer)
}
// its model searches the web with magpie's tool, which magpie answers
var search Tool
if req.WebSearch && !searching(r.Context()) {
@@ -5712,6 +5749,9 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
if search.Name != "" {
run.search, run.searchName = s.webSearch, search.Name
}
if answer.Name != "" && run.tui {
run.answerName, run.answerSchema = answer.Name, answerSchema
}
run.mu.Unlock()
}
}
+6 -4
View File
@@ -35,13 +35,16 @@ func printMode(t *testing.T, print bool) {
// 11-01). Turned off, the same request runs as -p.
func TestClaudeTUIOnRefusesPrint(t *testing.T) {
h, started := tuiHelperHarness(t, "")
body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[{"role":"user","content":"sky?"}],"output_config":{"format":{"type":"json_schema","schema":{"type":"object","properties":{"color":{"type":"string"}}}}}}`
// an image known by its URL the interactive mode can't download (this
// computer's, which magpie never fetches): -p's Claude Code sends the
// URL as it is
body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[{"role":"user","content":[{"type":"image","source":{"type":"url","url":"http://127.0.0.1:1/a.png"}},{"type":"text","text":"what is it?"}]}]}`
ask := func() (int, string) {
var u Usage
return h.s.serveClaudeSubscription(httptest.NewRecorder(), httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u)
}
code, msg := ask()
if code == 200 || !strings.Contains(msg, "a JSON schema") || !strings.Contains(msg, "never runs it as claude -p") {
if code != 400 || !strings.Contains(msg, "couldn't fetch the image") {
t.Fatalf("%d %.300s", code, msg)
}
if runs := h.runs(); len(runs) != 0 {
@@ -51,8 +54,7 @@ func TestClaudeTUIOnRefusesPrint(t *testing.T) {
t.Fatalf("the helper started %d times for a refused request", n)
}
printMode(t, true)
// the fake's "ok" fits no schema; what counts is that -p ran it
if _, msg := ask(); strings.Contains(msg, "never runs it as claude -p") || len(h.runs()) == 0 {
if _, msg := ask(); strings.Contains(msg, "couldn't fetch the image") || len(h.runs()) == 0 {
t.Fatalf("turned off, it didn't run as -p: %.300s", msg)
}
if n := helperStarts(started); n != 0 {
+2 -2
View File
@@ -13,11 +13,11 @@ import (
// where a 502 was asked of every account in turn and rested some (#4778).
func TestClaudeTUIRefusalIsNoAccountsFault(t *testing.T) {
h, _ := tuiHelperHarness(t, "")
body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[{"role":"user","content":"sky?"}],"output_config":{"format":{"type":"json_schema","schema":{"type":"object","properties":{"color":{"type":"string"}}}}}}`
body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[{"role":"user","content":[{"type":"image","source":{"type":"url","url":"http://127.0.0.1:1/a.png"}},{"type":"text","text":"what is it?"}]}]}`
var u Usage
rec := httptest.NewRecorder()
code, msg := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u)
if code != 400 || !strings.Contains(msg, "a JSON schema") {
if code != 400 || !strings.Contains(msg, "couldn't fetch the image") {
t.Fatalf("%d %.300s", code, msg)
}
if retryable(code, rec.Body.Bytes()) {
+106
View File
@@ -0,0 +1,106 @@
package gateway
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"slices"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// Claude Code's interactive mode takes --json-schema and does nothing with
// it (2.1.316: its StructuredOutput tool is -p's alone), so a request with
// a JSON schema is given an answer tool of magpie's, through the bridge's
// MCP server like the client's tools: its input schema is the request's,
// magpie checks each call against it, and the answer is the input of the
// call that fits, told when the turn's result comes. A call that doesn't
// fit is told why and made again, as -p's is; a turn that ends with no
// call is asked for one once.
// answerToolName is the answer tool's name, unless a client's tool has it.
const answerToolName = "StructuredOutput"
const answerToolDescription = "Use this tool to give your final answer, as its input, in the shape its input schema asks. Call it once, at the end of your work, instead of answering in words."
// answerTool is the tool a request with a schema is answered through, named
// apart from the client's tools.
func answerTool(tools []Tool, schema json.RawMessage) Tool {
name := answerToolName
for n := 2; slices.ContainsFunc(tools, func(t Tool) bool { return t.Name == name }); n++ {
name = fmt.Sprintf("%s%d", answerToolName, n)
}
return Tool{Name: name, Description: answerToolDescription, Schema: cliSchema(schema)}
}
// answerAsk asks a turn that ended without the answer tool for its call.
func answerAsk(name string) string {
return "Give your final answer now by calling the " + name + " tool, with the answer as its input."
}
// noSchemaLoads refuses every $ref outside the schema itself: a schema is
// the caller's, and nothing it names is fetched or read.
type noSchemaLoads struct{}
func (noSchemaLoads) Load(url string) (any, error) {
return nil, fmt.Errorf("the schema refers to %s, outside itself", url)
}
// compileAnswerSchema compiles a request's schema to check the answer
// tool's calls against: as draft-07 without a $schema of its own, as
// Claude Code's -p reads one.
func compileAnswerSchema(raw json.RawMessage) (*jsonschema.Schema, error) {
doc, err := jsonschema.UnmarshalJSON(bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("the JSON schema isn't valid JSON: %v", err)
}
c := jsonschema.NewCompiler()
c.DefaultDraft(jsonschema.Draft7)
c.UseLoader(noSchemaLoads{})
const loc = "magpie:answer.json"
if err := c.AddResource(loc, doc); err != nil {
return nil, fmt.Errorf("the JSON schema can't be used: %v", err)
}
s, err := c.Compile(loc)
if err != nil {
return nil, fmt.Errorf("the JSON schema can't be used: %v", err)
}
return s, nil
}
// answer takes a call of the answer tool: the answer when it fits the
// schema, kept for the turn's result; why not, for the model to call it
// again, when it doesn't.
func (r *subscriptionRun) answer(w http.ResponseWriter, args json.RawMessage) {
r.mu.Lock()
schema := r.answerSchema
r.mu.Unlock()
v, err := jsonschema.UnmarshalJSON(bytes.NewReader(args))
if err == nil {
err = schema.Validate(v)
}
if err != nil {
var ve *jsonschema.ValidationError
why := err.Error()
if errors.As(err, &ve) {
why = ve.Error()
}
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": "The input doesn't fit the schema: " + why + "\nCall the tool again with input that fits."}}, IsError: true})
return
}
r.mu.Lock()
r.answerArgs = slices.Clone(args)
r.mu.Unlock()
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": "Answer received."}}})
}
// takeAnswer is the turn's answer, if a call gave one, and forgets it.
func (r *subscriptionRun) takeAnswer() json.RawMessage {
r.mu.Lock()
defer r.mu.Unlock()
a := r.answerArgs
r.answerArgs = nil
return a
}
+139
View File
@@ -0,0 +1,139 @@
package gateway
import (
"bufio"
"encoding/json"
"io"
"net/http/httptest"
"strings"
"testing"
"time"
)
// schemaTUI is a run in the interactive mode answering a request with a
// schema through magpie's answer tool.
func schemaTUI(t *testing.T, schema string) *tuiCalls {
t.Helper()
c := newTUICalls(t)
s, err := compileAnswerSchema(json.RawMessage(schema))
if err != nil {
t.Fatal(err)
}
c.run.mu.Lock()
c.run.schema, c.run.answerName, c.run.answerSchema = true, answerToolName, s
c.run.mu.Unlock()
return c
}
// answerCall makes Claude Code's call of the answer tool and returns what
// the MCP helper is told.
func (c *tuiCalls) answerCall(id, args string) mcpToolResult {
c.t.Helper()
r := httptest.NewRequest("POST", "/", strings.NewReader(`{"tool_call_id":"`+id+`","name":"`+answerToolName+`","arguments":`+args+`}`))
r.SetPathValue("token", "run")
rec := httptest.NewRecorder()
c.bridge.mcpCall(rec, r)
var res mcpToolResult
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
c.t.Fatalf("the answer tool said %q: %v", rec.Body.String(), err)
}
return res
}
func answerRow(id, input string) string {
return tuiRow("msg_"+id, `{"type":"tool_use","id":"`+id+`","name":"mcp__magpie__`+answerToolName+`","input":`+input+`}`, "tool_use", 9)
}
// Claude Code's interactive mode ignores --json-schema: the answer is the
// call of magpie's answer tool that fits the schema. One that doesn't is
// told why, to be made again, and neither call, nor the words around
// them, is told to the client.
func TestClaudeTUISchemaAnswer(t *testing.T) {
c := schemaTUI(t, `{"type":"object","properties":{"color":{"type":"string"}},"required":["color"],"additionalProperties":false}`)
first := c.run.segment
c.write(tuiRow("msg_w", `{"type":"text","text":"Let me answer."}`, "tool_use", 4), answerRow("toolu_1", `{"colour":"blue"}`))
bad := c.answerCall("toolu_1", `{"colour":"blue"}`)
if !bad.IsError || !strings.Contains(bad.Content[0]["text"].(string), "doesn't fit the schema") {
t.Fatalf("a call that doesn't fit was told %+v", bad)
}
c.write(answerRow("toolu_2", `{"color":"blue"}`))
if good := c.answerCall("toolu_2", `{"color":"blue"}`); good.IsError {
t.Fatalf("a call that fits was told %+v", good)
}
c.write(tuiRow("msg_end", `{"type":"text","text":"Done."}`, "end_turn", 2), tuiDone)
text, calls, stop, _, raw := c.reply(first)
if text != `{"color":"blue"}` || len(calls) != 0 || stop != "end_turn" {
t.Fatalf("the reply %q %v %q:\n%s", text, calls, stop, raw)
}
for _, said := range []string{"Let me answer", "Done.", "colour", answerToolName} {
if strings.Contains(raw, said) {
t.Fatalf("the client was told %q:\n%s", said, raw)
}
}
}
// A turn that ends without the answer tool's call is asked for it once,
// and the reply is the call it then makes; one that still makes none
// fails, saying so.
func TestClaudeTUISchemaAskedOnce(t *testing.T) {
for _, comply := range []bool{true, false} {
c := schemaTUI(t, `{"type":"object"}`)
pr, pw := io.Pipe()
c.run.stdin = pw
told := make(chan string, 4)
go func() {
sc := bufio.NewScanner(pr)
for sc.Scan() {
told <- sc.Text()
}
}()
first := c.run.segment
c.write(tuiRow("msg_w", `{"type":"text","text":"blue"}`, "end_turn", 4), tuiDone)
select {
case line := <-told:
if !strings.Contains(line, "calling the "+answerToolName+" tool") {
t.Fatalf("the run was told %s", line)
}
case <-time.After(5 * time.Second):
t.Fatal("a turn with no answer wasn't asked for one")
}
if comply {
c.write(answerRow("toolu_1", `{"sky":"blue"}`))
c.answerCall("toolu_1", `{"sky":"blue"}`)
} else {
c.write(tuiRow("msg_x", `{"type":"text","text":"blue, I said"}`, "end_turn", 4))
}
c.write(tuiDone)
text, _, stop, _, raw := c.reply(first)
if comply && (text != `{"sky":"blue"}` || stop != "end_turn") {
t.Fatalf("the reply %q %q:\n%s", text, stop, raw)
}
if !comply && (!strings.Contains(raw, "no answer fitting the schema") || strings.Contains(raw, "blue")) {
t.Fatalf("a turn that never answered:\n%s", raw)
}
select {
case line := <-told:
t.Fatalf("asked again: %s", line)
default:
}
pw.Close()
}
}
// The answer tool is named apart from the client's tools, takes the
// schema as Claude Code's -p does (no root $schema), and a schema that
// refers outside itself is refused, not fetched.
func TestAnswerTool(t *testing.T) {
tool := answerTool([]Tool{{Name: answerToolName}}, json.RawMessage(`{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object"}`))
if tool.Name != answerToolName+"2" || string(tool.Schema) != `{"type":"object"}` {
t.Fatalf("tool %s %s", tool.Name, tool.Schema)
}
for _, s := range []string{`{"$ref":"https://example.com/s.json"}`, `{"$ref":"file:///etc/passwd"}`, `not json`} {
if _, err := compileAnswerSchema(json.RawMessage(s)); err == nil {
t.Fatalf("%s compiled", s)
}
}
if _, err := compileAnswerSchema(json.RawMessage(`{"$defs":{"c":{"type":"string"}},"type":"object","properties":{"c":{"$ref":"#/$defs/c"}}}`)); err != nil {
t.Fatalf("a schema's own $ref: %v", err)
}
}
+1 -1
View File
@@ -43,7 +43,7 @@ func TestClaudeTUIChosen(t *testing.T) {
{"in WSL, its home unknown", &Request{Messages: text("hi")}, claudeCLI{path: "claude", wsl: &wslrun.Tool{Distro: "Ubuntu"}}, false, on, ""},
{"safeguards", &Request{Messages: text("hi"), Safeguards: json.RawMessage(`{"a":1}`)}, here, false, on, ""},
{"client cache marks", &Request{Messages: text("hi"), clientCache: &clientCache{}}, here, false, on, ""},
{"a schema", &Request{Messages: text("hi"), Format: &Format{Type: "json_schema", Schema: json.RawMessage(`{"type":"object"}`)}}, here, false, false, "a JSON schema"},
{"a schema", &Request{Messages: text("hi"), Format: &Format{Type: "json_schema", Schema: json.RawMessage(`{"type":"object"}`)}}, here, false, on, ""},
{"an image", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image, MediaType: "image/png", Data: "AA=="}}}}}, here, false, on, ""},
{"an image by its URL", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image, URL: "https://example.com/a.png"}}}}}, here, false, false, "an image known by its URL"},
{"a tool's image by its URL", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: ToolResult, Images: []Part{{Kind: Image, URL: "https://example.com/a.png"}}}}}}}, here, false, false, "an image known by its URL"},
+1 -1
View File
@@ -37,7 +37,7 @@ function ccTip(anchor, tui) {
t("Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.")),
mode(!tui, "claude -p",
t("Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out."),
t("It starts at once, and takes what the interactive mode can't yet: a JSON schema."),
t("It starts at once, with no terminal of its own to open first."),
t("The plan counts a -p request at about twice the interactive mode's.")),
el("div", "foot", t("Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.")));
document.body.append(tip);
+4 -4
View File
@@ -12,7 +12,7 @@ const I18N = {
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie 像人一样打开 Claude Code:在一个你看不到的终端里输入每个请求,再从它的会话记录里读出回复。",
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "套餐把这些请求算作 Claude Code 自身的使用,同样的工作只消耗 -p 约一半的 5 小时额度。",
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Claude Code 的打印模式,脚本和 Agent SDK 用的就是它:一个请求进去,一个回复出来。",
"It starts at once, and takes what the interactive mode can't yet: a JSON schema.": "启动即用,并且支持交互模式暂时做不到的:JSON schema。",
"It starts at once, with no terminal of its own to open first.": "启动即用,不用先打开它自己的终端。",
"The plan counts a -p request at about twice the interactive mode's.": "套餐对 -p 请求的计量约为交互模式的两倍。",
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "可在这里或 设置 › 模型 › 回复 里切换。开着交互模式时,任何请求都不会走 -p:交互模式接不了或启动失败的请求会报错并说明原因。",
"Every request runs as claude -p": "每个请求都以 claude -p 运行",
@@ -4382,7 +4382,7 @@ const I18N = {
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie 像人一樣開啟 Claude Code:在一個你看不到的終端機裡輸入每個請求,再從它的對話記錄讀出回覆。",
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "方案把這些請求算作 Claude Code 本身的使用,同樣的工作只消耗 -p 約一半的 5 小時額度。",
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Claude Code 的列印模式,腳本和 Agent SDK 用的就是它:一個請求進去,一個回覆出來。",
"It starts at once, and takes what the interactive mode can't yet: a JSON schema.": "啟動即用,並且支援互動模式暫時做不到的:JSON schema。",
"It starts at once, with no terminal of its own to open first.": "啟動即用,不用先開啟它自己的終端機。",
"The plan counts a -p request at about twice the interactive mode's.": "方案對 -p 請求的計量約為互動模式的兩倍。",
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "可在這裡或 設定 › 模型 › 回覆 裡切換。開著互動模式時,任何請求都不會走 -p:互動模式接不了或啟動失敗的請求會報錯並說明原因。",
"Every request runs as claude -p": "每個請求都以 claude -p 執行",
@@ -8737,7 +8737,7 @@ const I18N = {
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie は人と同じように Claude Code を開きます。見えない専用のターミナルで各リクエストを入力し、トランスクリプトから応答を読み取ります。",
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "プランはこれらのリクエストを Claude Code 自身の利用として数え、同じ作業で -p の約半分の 5 時間枠しか使いません。",
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Claude Code の print モードで、スクリプトや Agent SDK が使うものです。リクエストを渡し、応答を受け取ります。",
"It starts at once, and takes what the interactive mode can't yet: a JSON schema.": "すぐに起動し、対話モードにまだできないものも扱えます:JSON schema。",
"It starts at once, with no terminal of its own to open first.": "専用の端末を先に開くことなく、すぐに起動します。",
"The plan counts a -p request at about twice the interactive mode's.": "プランは -p のリクエストを対話モードの約 2 倍として数えます。",
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "ここか 設定 › モデル › 応答 で切り替えられます。対話モードがオンのときは、何も -p では実行しません。対話モードで扱えないリクエストや起動に失敗したリクエストは理由を添えてエラーになります。",
"Every request runs as claude -p": "すべてのリクエストを claude -p で実行します",
@@ -13094,7 +13094,7 @@ const I18N = {
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie öffnet Claude Code wie ein Mensch, in einem eigenen Terminal, das du nicht siehst, tippt jede Anfrage ein und liest die Antwort aus dem Transkript.",
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "Dein Plan zählt diese Anfragen als Claude Codes eigene Nutzung, mit etwa der Hälfte des 5-Stunden-Kontingents, das -p für dieselbe Arbeit braucht.",
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Der Print-Modus von Claude Code, den Skripte und das Agent SDK nutzen: eine Anfrage hinein, ihre Antwort heraus.",
"It starts at once, and takes what the interactive mode can't yet: a JSON schema.": "Er startet sofort und kann, was der interaktive Modus noch nicht kann: ein JSON-Schema.",
"It starts at once, with no terminal of its own to open first.": "Er startet sofort, ohne zuerst ein eigenes Terminal zu öffnen.",
"The plan counts a -p request at about twice the interactive mode's.": "Der Plan zählt eine -p-Anfrage etwa doppelt so hoch wie eine im interaktiven Modus.",
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "Hier oder unter Einstellungen › Modelle › Antworten umschaltbar. Mit eingeschaltetem interaktivem Modus läuft nie etwas als -p: Eine Anfrage, die er nicht annehmen kann oder für die er nicht startet, schlägt mit dem Grund fehl.",
"Every request runs as claude -p": "Jede Anfrage läuft als claude -p",
+1 -1
View File
@@ -128,7 +128,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
]);
// nothing in the card says a request falls back to -p (the owner, 11-01)
assert.equal((await tip.locator(".foot").textContent()).trim(), await tr("Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why."));
assert.equal((await tip.locator(".cc-m").nth(1).locator("p.good").textContent()).trim(), await tr("It starts at once, and takes what the interactive mode can't yet: a JSON schema."));
assert.equal((await tip.locator(".cc-m").nth(1).locator("p.good").textContent()).trim(), await tr("It starts at once, with no terminal of its own to open first."));
const box = await tip.boundingBox();
assert(box.x >= 0 && box.y >= 0 && box.x + box.width <= width && box.y + box.height <= 760, `the card is inside the window: ${JSON.stringify(box)}`);
if (lang !== "en") {