diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 67860c3d3..20c7c1877 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -152,11 +152,59 @@ talks to it as it talks to `-p`: stream-json in and out. The helper: this command (`leaveSignals`), since it re-raised SIGTERM and killed the helper before it could end Claude Code and remove its files. Windows ends a run by killing its job, which no handler hears, so a helper - starting removes such folders over an hour old (`dropLeftImages`); + starting removes such folders, and the tap's, over an hour old + (`dropLeft`); - tails `/projects/*/.jsonl` and tells each - row as `-p` would (`translator`): assistant messages whole (no partial - stream), a tool's result, a `` API error as the turn's error - result with its `rate_limit_info`, and `turn_duration` as the result. + row as `-p` would (`translator`): assistant messages whole, a tool's + result, a `` API error as the turn's error result with its + `rate_limit_info`, and `turn_duration` as the result; +- streams each reply as it comes, through the tap (`tap.go`, `tap.js`). + +The transcript has a message only once it ends, so the tap streams it. +Claude Code is a Bun program, and Bun loads first what `BUN_OPTIONS` +names with `--preload`. The helper writes `tap.js` and an empty +`tap.jsonl` to a `magpie-claude-tap-*` temp folder, and starts Claude +Code with `BUN_OPTIONS` set to the user's own value followed by +`--preload `, and `MAGPIE_CLAUDE_TAP` set to the file. Claude Code +in WSL gets both through `WSLENV`, with the paths as WSL reads them, and +not the user's Windows `BUN_OPTIONS`. `BUN_OPTIONS` has no quoting, so on +Windows a path with a space takes its short name. A path that still has +whitespace gets no tap. + +`tap.js` takes itself out of `BUN_OPTIONS`, `process.execArgv` and the +environment, so nothing Claude Code runs loads it. Claude Code sends its +API requests through `Bun.FetchSession`, and the tap puts a subclass in +its place. That subclass calls the real fetch, with the request, +connection and TLS left as they were, and tees the body of each reply to +a request with `x-claude-code-request-class: main`, a `/v1/messages` path +and a `text/event-stream` reply. Claude Code reads one branch as before. +The tap parses the other and writes one JSON line per event to the file: +`{s, open}` when a stream starts, `{s, e}` for each event other than +`ping`, and `{s, end: "done"|"cut"}` when it ends. At load it writes +`{tap: "on"}`, or `{tap: "none"}` when there is no `FetchSession` to +replace. + +The helper reads the file every time round the tail loop, every 10ms +while a stream is open, and tells each event as `-p` does: a +`stream_event` line. Order is kept two ways: + +- Before an assistant message `X` from the transcript is told, + `tap.before` waits up to 1s (`tapWait`) for a stream with no + `message_start` yet to start as `X`. If none does, `X` is told whole, + and when its stream comes late it is left out (`dropped`). +- Before a turn's result, `tap.settle` waits up to 1s for the open + streams to end, and ends the rest there. + +A stream cut short gets a `message_stop` with no `message_delta`, as `-p` +ends such a stream, and the bridge counts it as an attempt and asks +again. In the bridge, a message that was streamed (`streamed`, by id) has +its whole rows left out, a late one too. A client's `tool_use` that was +streamed is marked `told`, so `onCall` doesn't tell it a second time. + +A Claude Code that isn't Bun, or doesn't load the tap, writes nothing to +the file. Its messages are told whole, with no wait, as before. Claude +Code 2.1.281 on Windows doesn't send through `FetchSession`. 2.1.289 (WSL) +and 2.1.316 (macOS, Windows) do. The transcript has a message only once it ends, and Claude Code doesn't always write the message calling a client's tool before that call is diff --git a/internal/claudetui/child_unix.go b/internal/claudetui/child_unix.go index 77d8cedcd..a485e80e1 100644 --- a/internal/claudetui/child_unix.go +++ b/internal/claudetui/child_unix.go @@ -31,7 +31,7 @@ func (s *shim) start(path string, args []string) error { // wide, so a line of Claude Code's screen is a line _ = unix.IoctlSetWinsize(int(tty.Fd()), unix.TIOCSWINSZ, &unix.Winsize{Row: 50, Col: 200}) cmd := proc.Command(path, args...) - cmd.Env = childEnv() + cmd.Env = childEnv(s.env...) cmd.Stdin, cmd.Stdout, cmd.Stderr = tty, tty, tty // its own session, the terminal its controlling one: the shim ending // closes the terminal, and Claude Code is hung up on with it diff --git a/internal/claudetui/child_windows.go b/internal/claudetui/child_windows.go index 2aa648979..8c653ccb7 100644 --- a/internal/claudetui/child_windows.go +++ b/internal/claudetui/child_windows.go @@ -26,7 +26,7 @@ type child struct { // endSignals are what the helper ends on, its Claude Code with it: Ctrl+C, // and its console closed. The gateway ends a run by killing its job, which // no handler hears: the images folder is then left for another helper to -// remove (dropLeftImages). +// remove (dropLeft). var endSignals = []os.Signal{os.Interrupt, syscall.SIGTERM} func (s *shim) start(path string, args []string) error { @@ -67,7 +67,7 @@ func (s *shim) start(path string, args []string) error { out.Close() return fmt.Errorf("a pseudo console: %w", err) } - h, err := startIn(console, cmd.Path, line, childEnv()) + h, err := startIn(console, cmd.Path, line, childEnv(s.env...)) if err != nil { windows.ClosePseudoConsole(console) in.Close() diff --git a/internal/claudetui/tap.go b/internal/claudetui/tap.go new file mode 100644 index 000000000..1447c27e2 --- /dev/null +++ b/internal/claudetui/tap.go @@ -0,0 +1,245 @@ +package claudetui + +import ( + "bufio" + _ "embed" + "encoding/json" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" +) + +// The transcript has a message only once it ends, so on its own the +// helper tells a reply a whole message at a time. Claude Code is a Bun +// program, and Bun loads a script before it that BUN_OPTIONS names +// (--preload): tap.js copies the main turn's replies, as Anthropic streams +// them, to a file of the helper's, and the helper tells them on as -p's +// stream_event lines. The requests, and what Claude Code reads and +// writes, are its own: the tap reads a copy of each reply's body. A Claude +// Code that isn't Bun, or doesn't load it, writes nothing there, and its +// replies are told whole as before. +// +//go:embed tap.js +var tapJS []byte + +// tapPrefix names the folders a tap is written to, the helper's pid after +// it; tap.js knows itself by it, to take itself out of what Claude Code +// hands on. +const tapPrefix = "magpie-claude-tap-" + +// tapEnv names the file tap.js writes to. +const tapEnv = "MAGPIE_CLAUDE_TAP" + +// 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 +var ( + tapWait = time.Second + tapPoll = 10 * time.Millisecond +) + +// tap reads what tap.js writes. +type tap struct { + dir string + f *os.File + rd *bufio.Reader + // part is a line not yet ended + part []byte + // on: tap.js was loaded and taps Claude Code's requests + on bool + // open are the streams going, by tap.js's number: the id of the + // message each is, once its message_start comes + open map[int]*tapStream + ended map[int]bool + started map[string]bool + // dropped are the messages told whole, as their stream came late: + // their stream says nothing + dropped map[string]bool + out emitter + sid string +} + +type tapStream struct { + id string + stopped bool +} + +// newTap writes tap.js and the file it writes to in a folder of the +// helper's, and returns the environment that has Claude Code load it: +// nil, with no tap, where that can't be done. path maps a path of the +// helper's to Claude Code's (shim.path). +func newTap(path func(string) string) (*tap, []string) { + dir, err := os.MkdirTemp("", tapPrefix+strconv.Itoa(os.Getpid())+"-") + if err != nil { + return nil, nil + } + t := &tap{dir: dir, open: map[int]*tapStream{}, ended: map[int]bool{}, started: map[string]bool{}, dropped: map[string]bool{}} + js, out := filepath.Join(dir, "tap.js"), filepath.Join(dir, "tap.jsonl") + if os.WriteFile(js, tapJS, 0o600) != nil || os.WriteFile(out, nil, 0o600) != nil { + t.drop() + return nil, nil + } + if t.f, err = os.Open(out); err != nil { + t.drop() + return nil, nil + } + t.rd = bufio.NewReaderSize(t.f, 1<<20) + // BUN_OPTIONS is split at whitespace, with no quoting: a path with a + // space in it takes its short name, or there is no tap + preload := path(shortPath(js)) + if runtime.GOOS == "windows" && !strings.HasPrefix(preload, "/") { + preload = filepath.ToSlash(preload) + } + if strings.ContainsAny(preload, " \t\r\n") { + t.drop() + return nil, nil + } + opts := "--preload " + preload + // the user's own, but not a Windows one's for a Claude Code in WSL + if v := strings.TrimSpace(os.Getenv("BUN_OPTIONS")); v != "" && os.Getenv(WSLEnv) == "" { + opts = v + " " + opts + } + return t, []string{"BUN_OPTIONS=" + opts, tapEnv + "=" + path(out)} +} + +// drop removes the tap's folder. +func (t *tap) drop() { + if t == nil { + return + } + if t.f != nil { + _ = t.f.Close() + } + _ = os.RemoveAll(t.dir) +} + +// read tells what tap.js wrote since it was last read. +func (t *tap) read() { + if t == nil { + return + } + for { + line, err := t.rd.ReadBytes('\n') + t.part = append(t.part, line...) + if err != nil { + return + } + t.line(t.part) + t.part = nil + } +} + +func (t *tap) line(b []byte) { + var l struct { + Tap string `json:"tap"` + S int `json:"s"` + Open bool `json:"open"` + End string `json:"end"` + Event json.RawMessage `json:"e"` + } + if json.Unmarshal(b, &l) != nil || t.ended[l.S] { + return + } + switch { + case l.Tap != "": + t.on = l.Tap == "on" + case l.Open: + t.open[l.S] = &tapStream{} + case len(l.Event) > 0: + var e struct { + Type string `json:"type"` + Message struct { + ID string `json:"id"` + } `json:"message"` + } + if json.Unmarshal(l.Event, &e) != nil { + return + } + st := t.open[l.S] + if e.Type == "message_start" { + st = &tapStream{id: e.Message.ID} + t.open[l.S] = st + if t.dropped[st.id] { + return + } + t.started[st.id] = true + } + if st == nil || st.id == "" || t.dropped[st.id] { + return + } + if e.Type == "message_stop" { + st.stopped = true + } + t.event(l.Event) + case l.End != "": + t.end(l.S) + } +} + +// end ends stream n: one cut short ends as Claude Code ends such a +// stream in -p, with a message_stop and no message_delta, which the +// bridge takes as an attempt it asks again after. +func (t *tap) end(n int) { + st := t.open[n] + delete(t.open, n) + t.ended[n] = true + if st != nil && st.id != "" && !st.stopped && !t.dropped[st.id] { + t.event(json.RawMessage(`{"type":"message_stop"}`)) + } +} + +func (t *tap) event(e json.RawMessage) { + t.out.emit(map[string]any{"type": "stream_event", "event": e, "session_id": t.sid, "parent_tool_use_id": nil}) +} + +// going says whether a stream is open, one with no message yet if bare. +func (t *tap) going(bare bool) bool { + for _, st := range t.open { + if !bare || st.id == "" { + return true + } + } + return false +} + +// before is called before the transcript's message id is told: a message +// streamed is told after its stream has begun, for the bridge to leave +// its whole rows out; one whose stream hasn't come within tapWait is told +// whole, its stream left out. A message no stream can be (no reply is +// being read: Claude Code asked again without a stream) waits for none. +func (t *tap) before(id string) { + if t == nil { + return + } + t.read() + if !t.on || t.started[id] || t.dropped[id] { + return + } + for until := time.Now().Add(tapWait); t.going(true) && time.Now().Before(until); { + time.Sleep(tapPoll) + t.read() + if t.started[id] { + return + } + } + t.dropped[id] = true +} + +// settle is called before a turn's end is told: its streams end first, +// within tapWait, and one still going then ends there. +func (t *tap) settle() { + if t == nil { + return + } + t.read() + for until := time.Now().Add(tapWait); t.going(false) && time.Now().Before(until); { + time.Sleep(tapPoll) + t.read() + } + for n := range t.open { + t.end(n) + } +} diff --git a/internal/claudetui/tap.js b/internal/claudetui/tap.js new file mode 100644 index 000000000..6bc4471b7 --- /dev/null +++ b/internal/claudetui/tap.js @@ -0,0 +1,106 @@ +// magpie's tap on Claude Code's stream (internal/claudetui/tap.go). Claude +// Code, a Bun program, loads this before itself (BUN_OPTIONS --preload). +// Its requests to Anthropic go through Bun.FetchSession: this makes that +// a FetchSession whose fetch is the real one's, the request, connection +// and TLS untouched, and copies the reply of each of the main turn's +// requests (x-claude-code-request-class: main), as it streams, to the +// file MAGPIE_CLAUDE_TAP names: a JSON line an event. Claude Code reads +// its own copy of the stream as before. +(() => { + const file = process.env.MAGPIE_CLAUDE_TAP; + if (!file) return; + // none of it is handed on to what Claude Code runs, nor says it is here + delete process.env.MAGPIE_CLAUDE_TAP; + const ours = /(^|\s)--preload(=|\s+)\S*magpie-claude-tap-\S*/; + const opts = (process.env.BUN_OPTIONS || "").replace(ours, "").trim(); + if (opts) process.env.BUN_OPTIONS = opts; + else delete process.env.BUN_OPTIONS; + const argv = process.execArgv; + for (let i = argv.length - 1; i >= 0; i--) { + if (!/magpie-claude-tap-/.test(argv[i])) continue; + if (argv[i].startsWith("--preload=")) argv.splice(i, 1); + else if (argv[i - 1] === "--preload") argv.splice(--i, 2); + } + + const fs = require("fs"); + let fd; + try { + fd = fs.openSync(file, "a"); + } catch { + return; + } + const put = (v) => { + try { + fs.writeSync(fd, JSON.stringify(v) + "\n"); + } catch {} + }; + const Real = globalThis.Bun && Bun.FetchSession; + if (typeof Real !== "function") { + put({ tap: "none" }); + return; + } + let streams = 0; + // read tells each event of stream s, then its end: cut when it broke + // off, as a dropped connection or Claude Code's own Esc ends it + const read = async (s, body) => { + const dec = new TextDecoder(); + let buf = ""; + const event = (text) => { + const data = text + .split("\n") + .filter((l) => l.startsWith("data:")) + .map((l) => l.slice(5).replace(/^ /, "")) + .join("\n"); + if (!data) return; + let e; + try { + e = JSON.parse(data); + } catch { + return; + } + if (e && e.type !== "ping") put({ s, e }); + }; + try { + for await (const chunk of body) { + buf = (buf + dec.decode(chunk, { stream: true })).replace(/\r\n?/g, "\n"); + let i; + while ((i = buf.indexOf("\n\n")) >= 0) { + event(buf.slice(0, i)); + buf = buf.slice(i + 2); + } + } + if (buf.trim()) event(buf); + put({ s, end: "done" }); + } catch (err) { + put({ s, end: "cut" }); + } + }; + class FetchSession extends Real { + async fetch(input, init) { + const res = await super.fetch(input, init); + try { + const url = String((input && input.url) || input); + const headers = new Headers((init && init.headers) || (input && input.headers) || undefined); + if ( + headers.get("x-claude-code-request-class") === "main" && + /\/v1\/messages(\?|$)/.test(url) && + res.body && + /^text\/event-stream/.test(res.headers.get("content-type") || "") + ) { + const [theirs, mine] = res.body.tee(); + Object.defineProperty(res, "body", { value: theirs, configurable: true }); + // told before Claude Code has the reply, so the helper knows a + // stream is coming before any of its messages + const s = ++streams; + put({ s, open: true }); + read(s, mine); + } + } catch {} + return res; + } + } + try { + Bun.FetchSession = FetchSession; + } catch {} + put({ tap: Bun.FetchSession === FetchSession ? "on" : "none" }); +})(); diff --git a/internal/claudetui/tap_other.go b/internal/claudetui/tap_other.go new file mode 100644 index 000000000..8affc775d --- /dev/null +++ b/internal/claudetui/tap_other.go @@ -0,0 +1,6 @@ +//go:build !windows + +package claudetui + +// shortPath is path: only Windows has short names. +func shortPath(path string) string { return path } diff --git a/internal/claudetui/tap_test.go b/internal/claudetui/tap_test.go new file mode 100644 index 000000000..87db975f3 --- /dev/null +++ b/internal/claudetui/tap_test.go @@ -0,0 +1,270 @@ +package claudetui + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + "time" +) + +// testTap is a tap in a folder of the test's, telling l, and a func that +// writes lines to it as tap.js does. +func testTap(t *testing.T, l *lines) (*tap, func(...string)) { + t.Helper() + tmp := t.TempDir() + t.Setenv("TMPDIR", tmp) + t.Setenv("TMP", tmp) + t.Setenv("TEMP", tmp) + tp, env := newTap(func(p string) string { return p }) + if tp == nil { + t.Fatal("no tap") + } + t.Cleanup(tp.drop) + tp.out, tp.sid = l, "sid" + out := strings.TrimPrefix(env[1], tapEnv+"=") + return tp, func(ls ...string) { + f, err := os.OpenFile(out, os.O_APPEND|os.O_WRONLY, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + for _, s := range ls { + _, _ = f.WriteString(s + "\n") + } + } +} + +// a reply's stream as tap.js writes it, stream n, message id +func tapReply(n int, id string) []string { + var ls []string + for _, e := range []string{`{"type":"message_start","message":{"id":"` + id + `"}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, + `{"type":"message_stop"}`} { + ls = append(ls, fmt.Sprintf(`{"s":%d,"e":%s}`, n, e)) + } + return append(ls, fmt.Sprintf(`{"s":%d,"end":"done"}`, n)) +} + +func whole(id string) []byte { + return []byte(`{"type":"assistant","requestId":"req_1","message":{"id":"` + id + `","model":"claude-haiku","content":[{"type":"text","text":"hi"}]}}`) +} + +// kinds is what l was told: a stream's events by their type +func kinds(l *lines) []string { + var k []string + for _, m := range l.out { + if e, ok := m["event"].(map[string]any); ok && m["type"] == "stream_event" { + k = append(k, e["type"].(string)) + continue + } + k = append(k, m["type"].(string)) + } + return k +} + +var streamedTurn = []string{"message_start", "content_block_start", "content_block_delta", "content_block_stop", "message_delta", "message_stop", "assistant", "result"} + +// A streamed reply is told as its stream goes, its whole message after, +// and the turn's end after both. +func TestTapStreamsBeforeWhole(t *testing.T) { + l := &lines{} + tp, write := testTap(t, l) + tr := newTranslator(l) + tr.tap = tp + write(`{"tap":"on"}`, `{"s":1,"open":true}`) + write(tapReply(1, "msg_1")...) + tr.row(whole("msg_1")) + tr.row([]byte(`{"type":"system","subtype":"turn_duration"}`)) + if got := kinds(l); !slices.Equal(got, streamedTurn) { + t.Fatalf("told %v, want %v", got, streamedTurn) + } + if l.out[0]["session_id"] != "sid" { + t.Fatalf("a stream_event without its session: %v", l.out[0]) + } +} + +// A message the transcript has before its stream begins waits for it: a +// stream is open, and its message_start comes after. +func TestTapMessageWaitsForItsStream(t *testing.T) { + l := &lines{} + tp, write := testTap(t, l) + tr := newTranslator(l) + tr.tap = tp + write(`{"tap":"on"}`, `{"s":1,"open":true}`) + go func() { + time.Sleep(100 * time.Millisecond) + write(tapReply(1, "msg_1")...) + }() + tr.row(whole("msg_1")) + tr.row([]byte(`{"type":"system","subtype":"turn_duration"}`)) + // the message is told once its stream has begun, the rest of the + // stream perhaps still to come (the bridge reads its whole rows by id), + // and the turn's end after all of it + got := kinds(l) + if i := slices.Index(got, "assistant"); i < 1 || got[0] != "message_start" { + t.Fatalf("told %v: the message before its stream began", got) + } + if rest := slices.DeleteFunc(slices.Clone(got), func(k string) bool { return k == "assistant" }); !slices.Equal(rest, slices.DeleteFunc(slices.Clone(streamedTurn), func(k string) bool { return k == "assistant" })) { + t.Fatalf("told %v, want the stream then the result", got) + } +} + +// A message no stream is being read for (Claude Code asked again without +// one) is told at once; one whose stream doesn't begin in tapWait is told +// whole, and its stream, come late, says nothing. +func TestTapMessageWithoutStream(t *testing.T) { + old := tapWait + tapWait = 200 * time.Millisecond + t.Cleanup(func() { tapWait = old }) + l := &lines{} + tp, write := testTap(t, l) + tr := newTranslator(l) + tr.tap = tp + write(`{"tap":"on"}`) + start := time.Now() + tr.row(whole("msg_9")) + if took := time.Since(start); took > tapWait/2 { + t.Fatalf("a message with no stream open waited %s", took) + } + write(`{"s":1,"open":true}`) + start = time.Now() + tr.row(whole("msg_1")) + if took := time.Since(start); took < tapWait { + t.Fatalf("a message whose stream is open waited only %s", took) + } + write(tapReply(1, "msg_1")...) + tr.row([]byte(`{"type":"system","subtype":"turn_duration"}`)) + if got, want := kinds(l), []string{"assistant", "assistant", "result"}; !slices.Equal(got, want) { + t.Fatalf("told %v, want %v", got, want) + } +} + +// A stream cut short ends with a message_stop and no message_delta, as +// Claude Code ends one in -p; one still going at the turn's end ends there. +func TestTapCutStreamStops(t *testing.T) { + old := tapWait + tapWait = 100 * time.Millisecond + t.Cleanup(func() { tapWait = old }) + l := &lines{} + tp, write := testTap(t, l) + tr := newTranslator(l) + tr.tap = tp + r := tapReply(1, "msg_1") + write(`{"tap":"on"}`, `{"s":1,"open":true}`, r[0], r[2], `{"s":1,"end":"cut"}`) + r = tapReply(2, "msg_2") + write(`{"s":2,"open":true}`, r[0], r[2]) + tr.row(whole("msg_2")) + tr.row([]byte(`{"type":"system","subtype":"turn_duration"}`)) + want := []string{"message_start", "content_block_delta", "message_stop", "message_start", "content_block_delta", "assistant", "message_stop", "result"} + if got := kinds(l); !slices.Equal(got, want) { + t.Fatalf("told %v, want %v", got, want) + } + // what comes after its end says nothing + write(r[3:]...) + tp.read() + if got := kinds(l); len(got) != len(want) { + t.Fatalf("an ended stream told more: %v", got) + } +} + +// A Claude Code that isn't Bun, or doesn't load the tap, writes nothing +// to it: its messages are told whole, at once. +func TestTapNotLoaded(t *testing.T) { + for _, first := range []string{"", `{"tap":"none"}`} { + l := &lines{} + tp, write := testTap(t, l) + tr := newTranslator(l) + tr.tap = tp + if first != "" { + write(first) + } + write(`{"s":1,"open":true}`) + start := time.Now() + tr.row(whole("msg_1")) + if took := time.Since(start); took > tapWait/2 { + t.Fatalf("%q: a message waited %s", first, took) + } + if got := kinds(l); !slices.Equal(got, []string{"assistant"}) { + t.Fatalf("%q: told %v", first, got) + } + } + // and with no tap at all + l := &lines{} + tr := newTranslator(l) + tr.row(whole("msg_1")) + tr.row([]byte(`{"type":"system","subtype":"turn_duration"}`)) + if got := kinds(l); !slices.Equal(got, []string{"assistant", "result"}) { + t.Fatalf("told %v", got) + } +} + +// Claude Code is given the tap with the user's own BUN_OPTIONS before it, +// but not a Windows one's in WSL; a path BUN_OPTIONS can't carry gives no +// tap. +func TestTapEnv(t *testing.T) { + tmp := t.TempDir() + t.Setenv("TMPDIR", tmp) + t.Setenv("TMP", tmp) + t.Setenv("TEMP", tmp) + t.Setenv("BUN_OPTIONS", "--smol") + tp, env := newTap(func(p string) string { return p }) + if tp == nil { + t.Fatal("no tap") + } + defer tp.drop() + js := filepath.Join(tp.dir, "tap.js") + if runtime.GOOS == "windows" { + js = filepath.ToSlash(shortPath(js)) + } + if want := []string{"BUN_OPTIONS=--smol --preload " + js, tapEnv + "=" + filepath.Join(tp.dir, "tap.jsonl")}; !slices.Equal(env, want) { + t.Fatalf("env %q, want %q", env, want) + } + if b, _ := os.ReadFile(filepath.Join(tp.dir, "tap.js")); string(b) != string(tapJS) { + t.Fatal("tap.js isn't written") + } + t.Setenv(WSLEnv, `{"args":["-d","Ubuntu"],"projects":"x"}`) + wsl, env := newTap(func(p string) string { return "/mnt/c/" + filepath.Base(p) }) + defer wsl.drop() + if want := []string{"BUN_OPTIONS=--preload /mnt/c/tap.js", tapEnv + "=/mnt/c/tap.jsonl"}; !slices.Equal(env, want) { + t.Fatalf("WSL env %q, want %q", env, want) + } + if runtime.GOOS != "windows" { + spaced := filepath.Join(tmp, "a b") + _ = os.Mkdir(spaced, 0o700) + t.Setenv("TMPDIR", spaced) + if tp, env := newTap(func(p string) string { return p }); tp != nil || env != nil { + t.Fatalf("a path with a space gave %q", env) + } + if left, _ := os.ReadDir(spaced); len(left) > 0 { + t.Fatalf("a tap not used is left: %v", left) + } + } +} + +// A Claude Code that loads the tap streams its reply before writing its +// message: the shim tells the stream, then the message, then the result. +func TestShimStreamsThroughTap(t *testing.T) { + out := runShim(t, []string{"FAKE_TAP=1"}, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 10) + var got []string + for _, m := range out[1:] { + if e, ok := m["event"].(map[string]any); ok { + got = append(got, e["type"].(string)) + continue + } + got = append(got, m["type"].(string)) + } + want := []string{"message_start", "content_block_start", "content_block_delta", "content_block_delta", "content_block_stop", "message_delta", "message_stop", "assistant", "result"} + if !slices.Equal(got, want) { + t.Fatalf("told %v, want %v", got, want) + } + if d := out[4]["event"].(map[string]any)["delta"].(map[string]any)["text"]; d != "hello" { + t.Fatalf("the stream said %v", d) + } +} diff --git a/internal/claudetui/tap_windows.go b/internal/claudetui/tap_windows.go new file mode 100644 index 000000000..ec9798b77 --- /dev/null +++ b/internal/claudetui/tap_windows.go @@ -0,0 +1,18 @@ +package claudetui + +import "golang.org/x/sys/windows" + +// shortPath is path's short (8.3) name, which has no spaces where the +// volume keeps short names; path where it has none. +func shortPath(path string) string { + p, err := windows.UTF16PtrFromString(path) + if err != nil { + return path + } + buf := make([]uint16, windows.MAX_LONG_PATH) + n, err := windows.GetShortPathName(p, &buf[0], uint32(len(buf))) + if err != nil || n == 0 || int(n) > len(buf) { + return path + } + return windows.UTF16ToString(buf[:n]) +} diff --git a/internal/claudetui/transcript.go b/internal/claudetui/transcript.go index 82a9f5afd..9c5241cbb 100644 --- a/internal/claudetui/transcript.go +++ b/internal/claudetui/transcript.go @@ -23,6 +23,9 @@ type translator struct { // the turn failed: its row's result is told, and the // turn_duration after it says nothing more failed bool + // tap has the streams of the messages (tap.go): a message is told + // after its stream has begun, and a turn's end after its streams' + tap *tap } func newTranslator(out emitter) *translator { return &translator{out: out} } @@ -68,6 +71,7 @@ func (t *translator) row(b []byte) { } case "assistant": var m struct { + ID string `json:"id"` Model string `json:"model"` Content []struct { Type string `json:"type"` @@ -75,6 +79,9 @@ func (t *translator) row(b []byte) { } `json:"content"` } _ = json.Unmarshal(r.Message, &m) + if m.Model != "" && m.ID != "" { + t.tap.before(m.ID) + } line := map[string]any{"type": "assistant", "message": r.Message} if r.RequestID != "" { line["request_id"] = r.RequestID @@ -96,10 +103,14 @@ func (t *translator) row(b []byte) { t.out.emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": r.APIParams.RateLimitInfo}) } t.failed = true + t.tap.settle() t.out.turnOver() t.out.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "result": text, "api_error_status": r.APIStatus}) case "system": + if r.Subtype == "turn_duration" { + t.tap.settle() + } if r.Subtype == "turn_duration" && !t.failed { t.out.emit(map[string]any{"type": "result", "subtype": "success", "is_error": false}) } diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index 8f88f9536..59ccd7402 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -5,7 +5,9 @@ // pseudo-terminal of its own. A user message is pasted into Claude Code's // prompt and sent with Enter, as a person does; what Claude Code answers is // read from the session's transcript, which Claude Code writes as it goes, -// and told back as stream-json, one whole message at a time. +// and told back as stream-json; a reply as Anthropic streams it, where +// Claude Code loads the helper's tap (tap.go), and one whole message at a +// time where it doesn't. // // Anthropic counts a request by its entrypoint: the interactive mode's // "cli", where -p's is "sdk-cli", and an sdk-cli request costs about @@ -91,6 +93,11 @@ type shim struct { // wsl is a Claude Code in a WSL distro (WSLEnv); nil for this // machine's wsl *WSL + + // tap copies the replies' streams (tap.go), nil with none; env is + // what Claude Code is given for it + tap *tap + env []string } // Run runs Claude Code at path, args being the bridge's `claude -p` ones, @@ -142,20 +149,26 @@ func Run(args []string) error { from = fi.Size() } } + if s.tap, s.env = newTap(s.path); s.tap != nil { + s.tap.out, s.tap.sid = s, s.sid + } + defer s.tap.drop() if err := s.start(path, append(slices.Clone(wslArgs(wsl)), args...)); err != nil { + s.tap.drop() MarkBroken() fmt.Fprintf(os.Stderr, "claude-tui: Claude Code's interactive mode could not start (%v); this run is -p\n", err) return printMode(path, pargs) } defer s.stop() defer s.dropImages() - go dropLeftImages() + go dropLeft() sigs := make(chan os.Signal, 1) signal.Notify(sigs, endSignals...) go func() { <-sigs s.stop() s.dropImages() + s.tap.drop() os.Exit(1) }() if err := s.ready(); err != nil { @@ -164,6 +177,7 @@ func Run(args []string) error { } signal.Reset() s.stop() + s.tap.drop() fmt.Fprintf(os.Stderr, "claude-tui: %v; this run is -p\n", err) return printMode(path, pargs) } @@ -194,8 +208,9 @@ func configDir() string { // childEnv is the environment for Claude Code: the shim's, without what a // Claude Code above it marks its own children with (one started from a // Claude Code session keeps no transcript, "inherited -// CLAUDE_CODE_CHILD_SESSION marker"), in a terminal it can draw in. -func childEnv() []string { +// CLAUDE_CODE_CHILD_SESSION marker"), in a terminal it can draw in, with +// extra (the tap's) in place of the shim's own. +func childEnv(extra ...string) []string { var env []string for _, e := range os.Environ() { k, _, _ := strings.Cut(e, "=") @@ -205,6 +220,8 @@ func childEnv() []string { k == "CLAUDE_PID", k == "CLAUDE_EFFORT", k == "TERM", k == "COLUMNS", k == "LINES", strings.HasPrefix(k, "CLAUDE_CODE_MESSAGING_"), k == WSLEnv: continue + case slices.ContainsFunc(extra, func(x string) bool { return strings.HasPrefix(x, k+"=") }): + continue case strings.EqualFold(k, "WSLENV") && os.Getenv(WSLEnv) != "": // a Claude Code in WSL is given only what WSLENV names continue @@ -212,9 +229,14 @@ func childEnv() []string { env = append(env, e) } if os.Getenv(WSLEnv) != "" { - env = append(env, "WSLENV="+strings.Trim(os.Getenv("WSLENV")+":TERM", ":")) + pass := os.Getenv("WSLENV") + ":TERM" + for _, x := range extra { + k, _, _ := strings.Cut(x, "=") + pass += ":" + k + } + env = append(env, "WSLENV="+strings.Trim(pass, ":")) } - return append(env, "TERM=xterm-256color") + return append(append(env, extra...), "TERM=xterm-256color") } // read keeps the tail of what Claude Code draws, and answers what it asks @@ -515,16 +537,18 @@ func (s *shim) dropImages() { // after it. const imagesPrefix = "magpie-claude-images-" -// imagesLeft is how long an image folder is left before another helper -// removes it: one killed with its images still in the prompt, as Windows -// ends a run, can't remove its own. +// imagesLeft is how long an image or tap folder is left before another +// helper removes it: one killed, as Windows ends a run, can't remove its +// own. A tap's files are open by then, in a run that goes on longer: +// removed, they are read and written as before. const imagesLeft = time.Hour -// dropLeftImages removes the image folders helpers left, untouched for -// imagesLeft. -func dropLeftImages() { +// dropLeft removes the image and tap folders helpers left, made over +// imagesLeft ago. +func dropLeft() { m, _ := filepath.Glob(filepath.Join(os.TempDir(), imagesPrefix+"*")) - for _, d := range m { + t, _ := filepath.Glob(filepath.Join(os.TempDir(), tapPrefix+"*")) + for _, d := range append(m, t...) { if fi, err := os.Stat(d); err == nil && fi.IsDir() && time.Since(fi.ModTime()) > imagesLeft { _ = os.RemoveAll(d) } @@ -746,6 +770,7 @@ func (s *shim) tail(from int64) { return } t := newTranslator(s) + t.tap = s.tap rd := bufio.NewReaderSize(f, 1<<20) var part []byte for { @@ -762,6 +787,11 @@ func (s *shim) tail(from int64) { return } t.quiet() + s.tap.read() + wait := 50 * time.Millisecond + if s.tap != nil && s.tap.going(false) { + wait = tapPoll + } select { case <-s.exited: // what it wrote last @@ -769,8 +799,9 @@ func (s *shim) tail(from int64) { t.row(append(part, line...)) } t.flush() + s.tap.settle() return - case <-time.After(50 * time.Millisecond): + case <-time.After(wait): } } } diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 5dcce806e..63451aaa1 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -113,6 +113,19 @@ func fakeClaude(args []string) { } // what it was started with, for the test to read _ = os.WriteFile(filepath.Join(os.Getenv("CLAUDE_CONFIG_DIR"), "args"), []byte(strings.Join(args, "\n")), 0o600) + // FAKE_TAP: Bun loads the tap BUN_OPTIONS names, which says so, and + // each reply is streamed to it before its message is written + var tapped *os.File + if os.Getenv("FAKE_TAP") == "1" { + _, js, _ := strings.Cut(os.Getenv("BUN_OPTIONS"), "--preload ") + if b, err := os.ReadFile(js); err == nil && string(b) == string(tapJS) { + tapped, _ = os.OpenFile(os.Getenv(tapEnv), os.O_APPEND|os.O_WRONLY, 0) + } + if tapped != nil { + _, _ = tapped.WriteString(`{"tap":"on"}` + "\n") + } + } + streams := 0 fmt.Print("\r\n❯ ") // the prompt's words; an image file's path pasted alone is read a // moment later and becomes "[Image #:]" where the @@ -168,6 +181,20 @@ func fakeClaude(args []string) { line := typed.String() typed.Reset() mu.Unlock() + if tapped != nil { + streams++ + n := streams + for _, e := range []string{`{"type":"message_start","message":{"id":"msg_1","model":"claude-haiku","usage":{"input_tokens":3}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"echo: "}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":` + strconvQuote(line) + `}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `{"type":"message_stop"}`} { + _, _ = fmt.Fprintf(tapped, `{"s":%d,"e":%s}`+"\n", n, e) + } + _, _ = fmt.Fprintf(tapped, `{"s":%d,"end":"done"}`+"\n", n) + } f, _ := os.OpenFile(filepath.Join(dir, sid+".jsonl"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) rows := []any{ map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": line}}, @@ -242,6 +269,11 @@ func runShim(t *testing.T, env []string, pargs []string, lines []string, want in return out } +func strconvQuote(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + func fakePath(t *testing.T) string { t.Helper() exe, _ := os.Executable() @@ -330,30 +362,32 @@ func TestShimPastesImages(t *testing.T) { } } -// A folder of images a killed helper left is removed by a later one after -// imagesLeft, and one in use isn't. -func TestDropLeftImages(t *testing.T) { +// A folder of images or a tap's a killed helper left is removed by a +// later one after imagesLeft, and one in use isn't. +func TestDropLeft(t *testing.T) { tmp := t.TempDir() t.Setenv("TMPDIR", tmp) t.Setenv("TMP", tmp) t.Setenv("TEMP", tmp) - old, now := filepath.Join(tmp, imagesPrefix+"1-a"), filepath.Join(tmp, imagesPrefix+"2-b") - for _, d := range []string{old, now} { - if err := os.MkdirAll(d, 0o700); err != nil { + for _, prefix := range []string{imagesPrefix, tapPrefix} { + old, now := filepath.Join(tmp, prefix+"1-a"), filepath.Join(tmp, prefix+"2-b") + for _, d := range []string{old, now} { + if err := os.MkdirAll(d, 0o700); err != nil { + t.Fatal(err) + } + _ = os.WriteFile(filepath.Join(d, "image-1.png"), []byte("x"), 0o600) + } + then := time.Now().Add(-imagesLeft - time.Minute) + if err := os.Chtimes(old, then, then); err != nil { t.Fatal(err) } - _ = os.WriteFile(filepath.Join(d, "image-1.png"), []byte("x"), 0o600) - } - then := time.Now().Add(-imagesLeft - time.Minute) - if err := os.Chtimes(old, then, then); err != nil { - t.Fatal(err) - } - dropLeftImages() - if _, err := os.Stat(old); !os.IsNotExist(err) { - t.Errorf("the folder left %s ago is still there (%v)", imagesLeft, err) - } - if _, err := os.Stat(now); err != nil { - t.Errorf("the folder in use was removed: %v", err) + dropLeft() + if _, err := os.Stat(old); !os.IsNotExist(err) { + t.Errorf("the %s folder left %s ago is still there (%v)", prefix, imagesLeft, err) + } + if _, err := os.Stat(now); err != nil { + t.Errorf("the %s folder in use was removed: %v", prefix, err) + } } } @@ -532,4 +566,16 @@ func TestShimInWSL(t *testing.T) { if len(wslenv) != 1 || wslenv[0] != "WSLENV=CLAUDE_CONFIG_DIR/p:TERM" { t.Fatalf("WSLENV %q", wslenv) } + // the tap's go through WSLENV too, in place of the shim's own + t.Setenv("BUN_OPTIONS", "--smol") + env = childEnv("BUN_OPTIONS=--preload /mnt/c/t/tap.js", tapEnv+"=/mnt/c/t/tap.jsonl") + var bun []string + for _, e := range env { + if strings.HasPrefix(e, "BUN_OPTIONS=") || strings.HasPrefix(e, tapEnv+"=") || strings.HasPrefix(e, "WSLENV=") { + bun = append(bun, e) + } + } + if want := []string{"WSLENV=CLAUDE_CONFIG_DIR/p:TERM:BUN_OPTIONS:" + tapEnv, "BUN_OPTIONS=--preload /mnt/c/t/tap.js", tapEnv + "=/mnt/c/t/tap.jsonl"}; !slices.Equal(bun, want) { + t.Fatalf("env %q, want %q", bun, want) + } } diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 686dee85b..a5a565249 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -2500,7 +2500,10 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { stopped := false // this message's message_delta said why it stopped cut := false // an attempt was cut short, and Claude Code asks again shown := false // this message has shown the client words or a call - streamed := "" // the message whose stream the events are + // the messages streamed: their whole messages come too, after their + // stream has begun, in Claude Code's interactive mode (claudetui's + // tap) as late as during the next message's stream + streamed := map[string]bool{} // a message told in whole messages: its id, its stop, and its blocks // so far; it is whole when anything else comes, or nothing does for // unstreamedQuiet, as when Claude Code goes on to call the client's @@ -2749,7 +2752,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { // whole messages come after its stream's events, under its id; // Claude Code's own (an error it tells as a message) is // - next := envelope.Type == "assistant" && whole.ID != "" && whole.ID != streamed && whole.Model != "" + next := envelope.Type == "assistant" && whole.ID != "" && !streamed[whole.ID] && whole.Model != "" if unstreamed != "" && !(next && whole.ID == unstreamed) { settle() } @@ -2947,12 +2950,14 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { e := envelope.Event switch e.Type { case "message_start": - streamed = e.Message.ID + streamed[e.Message.ID] = true begin(e.Message.ID, e.Message.Model, e.Message.Usage) case "content_block_start": switch e.ContentBlock.Type { case "tool_use": if name, theirs := toolStart(e.Index, e.ContentBlock.Name); theirs { + // shown, its call doesn't tell it again (onCall) + told[e.ContentBlock.ID] = true r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: name}) } case "text": diff --git a/internal/gateway/claude_tui_call_test.go b/internal/gateway/claude_tui_call_test.go index b562b557b..db68ac692 100644 --- a/internal/gateway/claude_tui_call_test.go +++ b/internal/gateway/claude_tui_call_test.go @@ -253,3 +253,64 @@ func TestClaudeTUIParallelCallsBeforeTheirMessage(t *testing.T) { }) } } + +// se is a stream_event line, as the helper tells what its tap read. +func se(event string) string { return `{"type":"stream_event","event":` + event + `}` } + +// A streamed message's call is told once: its call, come before its +// stream ends, doesn't tell the client itself too. +func TestClaudeTUIStreamedCallToldOnce(t *testing.T) { + c := newTUICalls(t) + first := c.run.segment + c.write( + se(`{"type":"message_start","message":{"id":"msg_call","model":"claude-haiku-5-5","usage":{"input_tokens":3}}}`), + se(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + se(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"reading"}}`), + se(`{"type":"content_block_stop","index":0}`), + se(`{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_a","name":"mcp__magpie__Read","input":{}}}`), + se(`{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"p\":1}"}}`), + ) + c.call("toolu_a", `{"p":1}`) + time.Sleep(3 * callFirst) // the call's own turn to tell the client passes + c.write( + se(`{"type":"content_block_stop","index":1}`), + se(`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":40}}`), + se(`{"type":"message_stop"}`), + tuiRow("msg_call", `{"type":"text","text":"reading"}`, "tool_use", 40), + tuiRow("msg_call", tuiCall("toolu_a", 1), "tool_use", 40), + ) + text, calls, stop, _, raw := c.reply(first) + if text != "reading" || len(calls) != 1 || calls[0] != `toolu_a{"p":1}` || stop != "tool_use" { + t.Fatalf("first reply %q %v %q:\n%s", text, calls, stop, raw) + } +} + +// A streamed message's whole rows can come as the next message streams, +// the transcript behind the tap: they are that message's, not one more. +func TestClaudeTUILateRowOfStreamed(t *testing.T) { + c := newTUICalls(t) + first := c.run.segment + c.write( + se(`{"type":"message_start","message":{"id":"msg_1","model":"claude-haiku-5-5","usage":{"input_tokens":3}}}`), + se(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + se(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a"}}`), + se(`{"type":"content_block_stop","index":0}`), + se(`{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"srvtoolu_1","name":"WebSearch","input":{}}}`), + se(`{"type":"content_block_stop","index":1}`), + se(`{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":4}}`), + se(`{"type":"message_stop"}`), + se(`{"type":"message_start","message":{"id":"msg_2","model":"claude-haiku-5-5","usage":{"input_tokens":3}}}`), + se(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + tuiRow("msg_1", `{"type":"text","text":"a"}`, "tool_use", 4), + se(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"b"}}`), + se(`{"type":"content_block_stop","index":0}`), + se(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`), + se(`{"type":"message_stop"}`), + tuiRow("msg_2", `{"type":"text","text":"b"}`, "end_turn", 2), + tuiDone, + ) + text, _, stop, _, raw := c.reply(first) + if text != "ab" || stop != "end_turn" { + t.Fatalf("reply %q %q:\n%s", text, stop, raw) + } +}