The owner: make a Claude subscription stream as it goes while Claude
Code runs in its interactive mode (TUI), on macOS, Windows and WSL.
Until now the helper read Claude Code's transcript, which has a message
only once it ends, so a reply came to the client whole.
Claude Code is a Bun program, and Bun loads a script named in
BUN_OPTIONS (--preload) before it. The helper writes tap.js to a folder
of its own and starts Claude Code with BUN_OPTIONS="--preload tap.js"
(after the user's own BUN_OPTIONS, but not a Windows one's for a Claude
Code in WSL, where both go through WSLENV). tap.js makes Bun.FetchSession
a subclass whose fetch is the real one's, so the request, its headers,
its connection and TLS are Claude Code's own. For a reply to a
request marked x-claude-code-request-class: main to /v1/messages that
is text/event-stream, it tees the body: Claude Code reads its copy as
before, and tap.js writes each event, as it comes, as a JSON line to
the file MAGPIE_CLAUDE_TAP names. It takes itself out of BUN_OPTIONS,
execArgv and the environment first, so nothing Claude Code runs
inherits it.
The helper reads that file and tells the events as -p's stream_event
lines, so the gateway reads them as it reads -p's. A transcript message
waits up to 1s for its stream to begin (then it's told whole, its late
stream left out); a turn's end waits for its streams to end; a stream
cut short ends with a message_stop and no message_delta, as -p ends
one. The bridge now keeps the streamed messages by id, since a whole
message can come during the next message's stream, and a client
tool_use shown from the stream isn't told again from the whole message.
On Windows, BUN_OPTIONS has no quoting, so a temp path with a space
takes its short name; one that still has whitespace gets no tap, and
replies come whole, as they do from a Claude Code that isn't Bun or
doesn't send through FetchSession (2.1.281 on Windows doesn't; 2.1.289
and 2.1.316 do).
Run:
- gofmt -l: clean. go vet on mote for darwin, GOOS=linux and
GOOS=windows: 0.
- go test ./internal/claudetui ./internal/gateway on mote
(-timeout 45m): ok, ok (gateway 654s).
- go test ./internal/claudetui with win-run (Windows 11) and wsl-run
(magpie-desktop): ok, ok.
- macOS, real account (Claude Code 2.1.316, sandbox HOME, keychain
token): a reply came as message_start, text deltas,
content_block_stop, message_delta, message_stop, then the whole
message, then the result; stderr clean, the tap's folder removed.
- Windows native, Claude Code 2.1.316 against a fake that sends an SSE
event every 250ms (a user preload marking the request main, which
also checks the user's BUN_OPTIONS is kept): the deltas came 250ms
apart, before the whole message. The same with TEMP holding a space
(short name).
- WSL magpie-desktop, Claude Code 2.1.289 run through wsl.exe from the
Windows helper, the fake in WSL: the same.
- The scrub, on macOS and Windows: Claude Code's BUN_OPTIONS and
execArgv have no tap, MAGPIE_CLAUDE_TAP is gone, --smol is kept.
- Rebased on origin/main 02ff0e908 (no file in common): on mote, vet
for darwin, windows and linux nogui 0; go test ./internal/claudetui
ok; -run 'CoreScriptBudget|I18n|Claude|Budget' ./internal/gui ok;
-run Claude ./internal/gateway ok. In WSL claude-mode, account-weight,
old-webkit and i18n-keys: 59 of 60, the one red i18n-keys' "Unmarked"
(#4524).
Broken by hand: the told mark removed, TestClaudeTUIStreamedCallToldOnce
went red; streamed kept as the last id only, TestClaudeTUILateRowOfStreamed
went red; before() made a no-op, and settle's end loop removed, the tap
tests went red. Each was put back.
TestTapMessageWaitsForItsStream failed now and then on mote: the whole
message can be told once its stream has begun, before the rest of the
stream is read. It now checks what is promised: the stream begins
before the message, every event is told, and the result comes last
(-count=30 ok).
Not tried: a real account on Windows or in WSL (the keychain token
went missing mid-session; those runs used the fake, whose request
carries no x-claude-code-request-class since a custom base URL drops
it); a real turn of several messages with the client's tools; Claude
Code 2.1.281 on Windows, which doesn't stream and is told whole as
before.
246 lines
6.4 KiB
Go
246 lines
6.4 KiB
Go
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)
|
|
}
|
|
}
|