feat(chat): add Claude Code chat backend

This commit is contained in:
2026-10-22 18:20:10 +01:00
parent dc6cb9aee1
commit 0acd7346bb
23 changed files with 3576 additions and 65 deletions
@@ -10,7 +10,7 @@ typedef ChatModelSelection = ({
/// Harnesses with a verified catalog and model-selection path, matching the
/// web's `supportsChatModels`.
bool supportsChatModels(String backend) =>
const ['', 'opencode', 'codex'].contains(backend.trim());
const ['', 'opencode', 'codex', 'claude'].contains(backend.trim());
/// The recorded current model, or the web's "Model" when none was recorded.
String chatModelLabel(String model, String selection) {
@@ -20,10 +20,17 @@ String chatModelLabel(String model, String selection) {
}
/// The helper shown above the catalog, verbatim from the web.
String chatModelSelectionNote(String backend) => backend.trim() == 'codex'
? 'Saved by Pipelines for the next turn you send. Does not resume this '
'thread or edit global Codex configuration.'
: 'Applies to the next turn in this chat.';
String chatModelSelectionNote(String backend) {
if (backend.trim() == 'codex') {
return 'Saved by Pipelines for the next turn you send. Does not resume this '
'thread or edit global Codex configuration.';
}
if (backend.trim() == 'claude') {
return 'Saved by Pipelines for the next turn you send. Does not edit your '
'global Claude Code configuration.';
}
return 'Applies to the next turn in this chat.';
}
/// A model's display name, or its id when the server gave no name.
String chatModelName(JsonMap model) {
+5 -3
View File
@@ -22,13 +22,15 @@ func main() {
executable, err := os.Executable()
if len(args) > 0 && args[0] == "skill" {
if len(args) == 2 && args[1] == "install" {
var dir string
dir, err = author.InstallSkill()
var dirs []string
dirs, err = author.InstallAllSkills()
if err == nil {
_, err = author.InstallManagerSkill()
}
if err == nil {
fmt.Println("Installed skill:", dir)
for _, dir := range dirs {
fmt.Println("Installed skill:", dir)
}
return
}
} else {
+51 -12
View File
@@ -1,9 +1,10 @@
# Chat backends
Chats can be created on more than one harness. OpenCode remains the default;
Codex is available when its App Server control socket exists. The selected
backend is stored on the operator-session row and returned as `backend` on every
`chat_sessions` row, so a restart does not have to guess from the session id.
Codex is available when its App Server control socket exists, and Claude Code
when the `claude` CLI is installed. The selected backend is stored on the
operator-session row and returned as `backend` on every `chat_sessions` row, so a
restart does not have to guess from the session id.
## Codex
@@ -31,23 +32,61 @@ not a fake empty success or silent auto-approval. App Server socket loss does
not provide durable callback recovery; a disconnected transport is reported as
an error rather than claiming old requests are still actionable.
Claude is not advertised as a backend until its sidecar and login flow are wired.
## Claude Code
The adapter in `internal/claude` owns one Claude Code CLI process per active
session. It starts `claude -p` with stream-json input and output, partial
messages, and `--permission-prompt-tool=stdio`, then performs the SDK-style
`initialize` handshake before any turn. The operator's existing Claude Code login
and configuration are used unchanged; Pipelines does not store a second
credential or alter global settings. `PIPELINES_CLAUDE` may name the executable;
otherwise `claude` is resolved from `PATH` and common per-user locations.
A new session pins a generated UUID with `--session-id`. When the process is
released (idle or server restart), the next prompt resumes the same conversation
with `--resume <id>`, so context and the selected model survive. Chat creation is
local: the CLI starts on the first prompt or model-catalog read.
Text and reasoning stream from the CLI's partial-message events; completed
messages are de-duplicated against the streamed text. Tool calls appear as normal
tool cards, Bash commands as the existing background-command rows, and results
attach to the call. `can_use_tool` becomes the normal approval card: Allow once
returns the original input, Always allow forwards the CLI's own permission
suggestions, and Reject returns a deny. `AskUserQuestion` becomes the normal
question card and `chat_answer` returns the chosen answers. Interrupt sends the
CLI's own `interrupt` control request.
The model catalog comes from the CLI's initialize response and is switched live
with `set_model`; Pipelines persists the choice for the next turn so a resumed
process starts with it. Usage and context totals come from the CLI's `get_usage`
and `get_context_usage` queries: session cost, processed tokens, context tokens
and the model window are reported values, not estimates. Compaction boundaries
surface as native compaction activity.
History is read from Claude Code's own session transcript
(`$CLAUDE_CONFIG_DIR/projects/*/<id>.jsonl` or `~/.claude`). Entries are merged by
message id, tool results attach to their calls, subagent sidechains and local
command noise are excluded, and paging is bounded. A session file larger than
64 MiB is reported as exceeding the history bound rather than silently truncated.
The live user turn keeps the client's optimistic id when it can be matched to the
recorded prompt.
## Web interaction contract
Both advertised chat adapters (OpenCode V2 and Codex) implement the same server
contract for uploads, models, pending approvals, questions, form replies,
interrupts, command readback and bounded output. Compile-time assertions and a
browser regression run against both backend identities protect this contract;
support is not satisfied by text streaming alone. Pi's pipeline executor is not
advertised as a Pi web-chat adapter, and an unavailable Claude adapter is not
presented as a working choice.
All advertised chat adapters (OpenCode V2, Codex and Claude Code) implement the
same server contract for uploads, models, pending approvals, questions, form
replies, interrupts, command readback and bounded output. Compile-time assertions
and browser regressions protect this contract; support is not satisfied by text
streaming alone. Pi's pipeline executor is not advertised as a Pi web-chat
adapter, and a harness whose CLI is absent is not presented as a working choice.
Codex uploads use native `localImage` for verified supported images. Other files
are retained intact with an explicit server-local reference; the model's own
tools inspect them rather than pretending their contents were already loaded.
The saved next-turn model is also respected with uploads. Model sandbox and
approval policy remain in force.
approval policy remain in force. Claude Code receives images as native image
blocks, small text files inline, and larger files by absolute server path; the
saved next-turn model is applied before the turn.
Codex's paged history retains tool and reasoning items, including structured MCP
errors and Code Mode outputs, instead of discarding everything except text.
+47
View File
@@ -0,0 +1,47 @@
package author
import (
"os"
"path/filepath"
"testing"
)
// Claude Code discovers personal skills under <config>/skills. The installer must
// refresh that copy without adopting a user's unrelated or edited skill.
func TestInstallAllSkillsInstallsClaudeCodeCopy(t *testing.T) {
claudeConfig := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", claudeConfig)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
dirs, err := InstallAllSkills()
if err != nil {
t.Fatal(err)
}
claudeDir := filepath.Join(claudeConfig, "skills", "pipelines")
if len(dirs) != 2 || dirs[1] != claudeDir {
t.Fatalf("installed directories: %+v", dirs)
}
body, err := os.ReadFile(filepath.Join(claudeDir, "SKILL.md"))
if err != nil || len(body) == 0 {
t.Fatalf("Claude skill not installed: %v", err)
}
// A second run is idempotent.
if _, err := InstallAllSkills(); err != nil {
t.Fatal(err)
}
// A user-edited file is never overwritten silently.
edited := filepath.Join(claudeDir, "SKILL.md")
if err := os.WriteFile(edited, []byte("user notes"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := InstallClaudeSkill(); err == nil {
t.Fatal("overwrote a user-modified Claude skill")
}
}
func TestClaudeSkillDirectoryHonoursConfigOverride(t *testing.T) {
t.Setenv("CLAUDE_CONFIG_DIR", "/tmp/claude-config-fixture")
dir, ok := ClaudeSkillDirectory()
if !ok || dir != "/tmp/claude-config-fixture/skills/pipelines" {
t.Fatalf("directory: %q ok=%v", dir, ok)
}
}
+82 -16
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
)
@@ -25,6 +26,31 @@ func SkillDirectory() (string, error) {
func digest(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) }
// ClaudeSkillDirectory is Claude Code's personal skill root. CLAUDE_CONFIG_DIR
// wins for an isolated installation, matching the CLI itself; otherwise
// ~/.claude is used when Claude Code is present.
func ClaudeSkillDirectory() (string, bool) {
if dir := os.Getenv("CLAUDE_CONFIG_DIR"); dir != "" {
absolute, err := filepath.Abs(dir)
if err != nil {
return "", false
}
return filepath.Join(absolute, "skills", "pipelines"), true
}
home, err := os.UserHomeDir()
if err != nil {
return "", false
}
config := filepath.Join(home, ".claude")
if info, err := os.Stat(config); err == nil && info.IsDir() {
return filepath.Join(config, "skills", "pipelines"), true
}
if _, err := exec.LookPath("claude"); err == nil {
return filepath.Join(config, "skills", "pipelines"), true
}
return "", false
}
// InstallSkill only updates files previously installed by Pipelines and unchanged
// by the user. It never edits OpenCode config, login, or unrelated skills.
func InstallSkill() (string, error) {
@@ -32,54 +58,94 @@ func InstallSkill() (string, error) {
if err != nil {
return "", err
}
if err := installSkillIn(dir); err != nil {
return "", err
}
return dir, nil
}
// InstallClaudeSkill installs the same managed skill into Claude Code's skill
// root when Claude Code is present. It returns "" when it is not installed.
func InstallClaudeSkill() (string, error) {
dir, ok := ClaudeSkillDirectory()
if !ok {
return "", nil
}
if err := installSkillIn(dir); err != nil {
return "", err
}
return dir, nil
}
// InstallAllSkills refreshes every detected agent skill root with the bundled
// workflow skill. A failure leaves the successful targets installed and names
// the failure, so one harness cannot silently shadow another.
func InstallAllSkills() ([]string, error) {
installed := []string{}
dir, err := InstallSkill()
if err != nil {
return installed, err
}
installed = append(installed, dir)
claudeDir, err := InstallClaudeSkill()
if err != nil {
return installed, err
}
if claudeDir != "" {
installed = append(installed, claudeDir)
}
return installed, nil
}
func installSkillIn(dir string) error {
marker := filepath.Join(dir, ".pipelines-managed.json")
if info, err := os.Lstat(marker); err == nil && !info.Mode().IsRegular() {
return "", fmt.Errorf("refusing non-regular skill ownership marker %s", marker)
return fmt.Errorf("refusing non-regular skill ownership marker %s", marker)
} else if err != nil && !os.IsNotExist(err) {
return "", err
return err
}
previous := map[string]string{}
if data, readErr := os.ReadFile(marker); readErr == nil {
if err = json.Unmarshal(data, &previous); err != nil {
return "", fmt.Errorf("invalid skill ownership marker: %w", err)
if err := json.Unmarshal(data, &previous); err != nil {
return fmt.Errorf("invalid skill ownership marker: %w", err)
}
} else if !os.IsNotExist(readErr) {
return "", readErr
return readErr
}
files := map[string][]byte{}
next := map[string]string{}
for _, file := range skillFiles {
data, err := content.ReadFile("skill/" + file)
if err != nil {
return "", err
return err
}
files[file] = data
next[file] = digest(data)
path := filepath.Join(dir, file)
if info, statErr := os.Lstat(path); statErr == nil {
if !info.Mode().IsRegular() {
return "", fmt.Errorf("refusing to replace non-regular skill file %s", path)
return fmt.Errorf("refusing to replace non-regular skill file %s", path)
}
existing, err := os.ReadFile(path)
if err != nil {
return "", err
return err
}
if previous[file] == "" || (digest(existing) != previous[file] && digest(existing) != next[file]) {
return "", fmt.Errorf("skill file %s is user-managed or modified; preserve/rename it before installing the Pipelines skill", path)
return fmt.Errorf("skill file %s is user-managed or modified; preserve/rename it before installing the Pipelines skill", path)
}
} else if !os.IsNotExist(statErr) {
return "", statErr
return statErr
}
}
// Record ownership before first creation so an interrupted installation can
// safely resume missing files. Updates accept either old or bundled hashes.
if len(previous) == 0 {
if err := os.MkdirAll(dir, 0700); err != nil {
return "", err
return err
}
data, _ := json.MarshalIndent(next, "", " ")
if err := writeSkillFile(marker, data); err != nil {
return "", err
return err
}
previous = next
}
@@ -91,10 +157,10 @@ func InstallSkill() (string, error) {
}
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return "", err
return err
}
if err := writeSkillFile(path, files[file]); err != nil {
return "", err
return err
}
}
// A file the previous install managed but this version no longer bundles - a
@@ -120,11 +186,11 @@ func InstallSkill() (string, error) {
}
}
if equal {
return dir, nil
return nil
}
}
data, _ := json.MarshalIndent(next, "", " ")
return dir, writeSkillFile(marker, data)
return writeSkillFile(marker, data)
}
func writeSkillFile(path string, data []byte) error {
+107
View File
@@ -0,0 +1,107 @@
package claude
import (
"encoding/base64"
"errors"
"fmt"
"mime"
"net/url"
"os"
"path/filepath"
"strings"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/opencode"
)
const (
maxInlineAttachment = 256 << 10
maxImageAttachment = 5 << 20
inlineBudget = 512 << 10
)
// promptContent builds Claude's stream-json user content. Images become native
// image blocks; small text files are inlined so the agent does not need a tool
// permission merely to read what the operator already attached. Anything larger
// is named by absolute path, which the CLI can still read with its own tools.
func promptContent(text string, files []opencode.PromptFile) ([]any, error) {
content := []any{}
if strings.TrimSpace(text) != "" {
content = append(content, map[string]any{"type": "text", "text": text})
}
budget := inlineBudget
for _, file := range files {
if !file.ServerPrepared() {
return nil, errors.New("refusing an attachment that was not prepared by the server")
}
path, err := promptFilePath(file.URI)
if err != nil {
return nil, err
}
info, err := os.Stat(path)
if err != nil || !info.Mode().IsRegular() {
return nil, fmt.Errorf("attached file %q is no longer available", file.Name)
}
if info.Size() > maxImageAttachment {
content = append(content, map[string]any{"type": "text", "text": fmt.Sprintf("Attached file %s is too large to inline; read it at %s", displayName(file), path)})
continue
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read attached file %q: %w", file.Name, err)
}
mediaType := mime.TypeByExtension(strings.ToLower(filepath.Ext(file.Name)))
if mediaType == "" {
mediaType = mime.TypeByExtension(strings.ToLower(filepath.Ext(path)))
}
if strings.HasPrefix(mediaType, "image/") {
content = append(content, map[string]any{
"type": "image",
"source": map[string]any{
"type": "base64",
"media_type": mediaType,
"data": base64.StdEncoding.EncodeToString(data),
},
})
continue
}
if utf8.Valid(data) && len(data) <= maxInlineAttachment && len(data) <= budget {
budget -= len(data)
content = append(content, map[string]any{
"type": "text",
"text": fmt.Sprintf("Attached file: %s\n\n%s", displayName(file), data),
})
continue
}
content = append(content, map[string]any{"type": "text", "text": fmt.Sprintf("Attached file %s is available at %s", displayName(file), path)})
}
if len(content) == 0 {
return nil, errors.New("a nonempty chat prompt is required")
}
return content, nil
}
func displayName(file opencode.PromptFile) string {
name := strings.TrimSpace(file.Name)
if name == "" {
name = filepath.Base(file.URI)
}
return name
}
// promptFilePath converts the server's file:// reference to a local path and
// refuses anything that is not a plain absolute file URL.
func promptFilePath(uri string) (string, error) {
parsed, err := url.Parse(uri)
if err != nil || parsed.Scheme != "file" || parsed.Host != "" || parsed.Opaque != "" {
return "", errors.New("invalid attachment reference")
}
path, err := url.PathUnescape(parsed.Path)
if err != nil {
return "", errors.New("invalid attachment reference")
}
if !filepath.IsAbs(path) {
return "", errors.New("attachment reference must be absolute")
}
return filepath.Clean(path), nil
}
+703
View File
@@ -0,0 +1,703 @@
package claude
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Create records one Claude session. The CLI process starts on the first
// prompt, so creating a chat is fast and does not require a signed-in CLI yet.
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
directory = strings.TrimSpace(directory)
if directory == "" {
return protocol.ChatSession{}, errors.New("a directory is required")
}
if !filepath.IsAbs(directory) {
return protocol.ChatSession{}, errors.New("the chat directory must be absolute")
}
absolute, err := filepath.Abs(directory)
if err != nil {
return protocol.ChatSession{}, err
}
if info, err := os.Stat(absolute); err != nil || !info.IsDir() {
return protocol.ChatSession{}, errors.New("the chat directory is not an existing directory")
}
id, err := newSessionID()
if err != nil {
return protocol.ChatSession{}, err
}
title = strings.TrimSpace(title)
s := c.sessionFor(id, absolute)
s.mu.Lock()
s.title = title
s.createdAt = time.Now().UnixMilli()
s.mu.Unlock()
return protocol.ChatSession{
ID: id,
Backend: Backend,
Title: title,
ModelProvider: Backend,
Directory: absolute,
CreatedAt: s.createdAt,
UpdatedAt: s.createdAt,
Tag: protocol.ChatSessionTagOperator,
}, nil
}
// Session resolves one session from memory or from its retained transcript, so
// a registry row survives a server restart.
func (c *Chat) Session(ctx context.Context, id string) (protocol.ChatSession, bool, error) {
if s := c.session(id); s != nil {
s.mu.Lock()
session := s.chatSessionLocked()
s.mu.Unlock()
return session, true, nil
}
meta, ok := transcriptSession(id)
if !ok {
return protocol.ChatSession{}, false, nil
}
return meta, true, nil
}
// Sessions lists sessions this process has opened. Registry rows for sessions
// from an earlier server are resolved by the manager through Session.
func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
c.mu.Lock()
states := make([]*session, 0, len(c.sessions))
for _, s := range c.sessions {
states = append(states, s)
}
c.mu.Unlock()
sessions := make([]protocol.ChatSession, 0, len(states))
for _, s := range states {
s.mu.Lock()
sessions = append(sessions, s.chatSessionLocked())
s.mu.Unlock()
}
sort.Slice(sessions, func(i, j int) bool { return sessions[i].ID < sessions[j].ID })
return sessions, nil
}
func (s *session) chatSessionLocked() protocol.ChatSession {
model := s.modelActual
if model == "" {
model = s.model
}
return protocol.ChatSession{
ID: s.id,
Backend: Backend,
Title: s.title,
Model: model,
ModelProvider: Backend,
Directory: s.directory,
CreatedAt: s.createdAt,
UpdatedAt: s.lastUsed.UnixMilli(),
}
}
// Prompt starts one turn with the default model selection.
func (c *Chat) Prompt(ctx context.Context, id, text string) error {
return c.PromptWithMessageID(ctx, id, text, "")
}
func (c *Chat) PromptWithMessageID(ctx context.Context, id, text, messageID string) error {
return c.PromptWithMessageIDModelFiles(ctx, id, text, messageID, "", nil)
}
func (c *Chat) PromptWithMessageIDModel(ctx context.Context, id, text, messageID, model string) error {
return c.PromptWithMessageIDModelFiles(ctx, id, text, messageID, model, nil)
}
func (c *Chat) PromptWithMessageIDFiles(ctx context.Context, id, text, messageID string, files []opencode.PromptFile) error {
return c.PromptWithMessageIDModelFiles(ctx, id, text, messageID, "", files)
}
// PromptWithMessageIDModelFiles submits one user turn, optionally applying the
// saved next-turn model and the server's private attachment files.
func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, messageID, model string, files []opencode.PromptFile) error {
s := c.session(id)
if s == nil {
found := false
if meta, ok := transcriptSession(id); ok {
s = c.sessionFor(id, meta.Directory)
found = true
}
if !found {
return errors.New("unknown Claude session " + id)
}
}
s.mu.Lock()
if strings.TrimSpace(text) == "" {
s.mu.Unlock()
return errors.New("a nonempty chat prompt is required")
}
if model != "" {
s.model = model
}
directory := s.directory
s.lastUsed = time.Now()
s.mu.Unlock()
if directory == "" {
return errors.New("the Claude session has no working directory")
}
proc, err := s.ensureProcess(ctx)
if err != nil {
return err
}
// Apply a selection that the running process has not seen yet.
s.mu.Lock()
requested := s.model
applied := s.appliedModel
s.mu.Unlock()
if requested != "" && requested != applied {
setCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
_, err := proc.request(setCtx, "set_model", map[string]any{"model": requested})
cancel()
if err != nil {
return fmt.Errorf("switch Claude model: %w", err)
}
s.mu.Lock()
s.appliedModel = requested
s.mu.Unlock()
}
content, err := promptContent(text, files)
if err != nil {
return err
}
turn := fmt.Sprintf("claude-%d", time.Now().UnixNano())
s.mu.Lock()
s.turnID = turn
s.running = true
s.prompts = append(s.prompts, promptRecord{id: messageID, text: strings.TrimSpace(text)})
if len(s.prompts) > 200 {
s.prompts = s.prompts[len(s.prompts)-200:]
}
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
payload := map[string]any{
"type": "user",
"message": map[string]any{"role": "user", "content": content},
}
if err := proc.write(payload); err != nil {
s.finishTurn(turn, "Claude Code is not accepting input: "+err.Error())
return err
}
return nil
}
// finishTurn settles a turn that never reached a CLI result.
func (s *session) finishTurn(turn, diagnostic string) {
s.mu.Lock()
if s.turnID != turn {
s.mu.Unlock()
return
}
s.running = false
s.turnID = ""
s.mu.Unlock()
if diagnostic != "" {
s.emit(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: turn,
MessageID: "claude-error-" + turn,
Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: "claude-error-" + turn,
Name: "Claude Code",
State: &protocol.ChatToolState{Status: protocol.ChatToolError, Error: &protocol.ChatError{Type: "prompt", Message: boundedText(diagnostic, 2<<10)}},
},
})
}
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
}
func (s *session) ensureProcess(ctx context.Context) (*process, error) {
for {
s.mu.Lock()
if s.proc != nil {
p := s.proc
s.lastUsed = time.Now()
s.mu.Unlock()
return p, nil
}
if s.starting != nil {
wait := s.starting
s.mu.Unlock()
select {
case <-wait:
continue
case <-ctx.Done():
return nil, ctx.Err()
}
}
wait := make(chan struct{})
s.starting = wait
s.startErr = nil
s.mu.Unlock()
p, err := s.spawn(ctx)
s.mu.Lock()
if err == nil {
s.proc = p
} else {
s.startErr = err
}
s.starting = nil
close(wait)
s.mu.Unlock()
if err != nil {
return nil, err
}
return p, nil
}
}
// Stream subscribes to the session's live frames. History is loaded separately
// through Messages; a client attaching mid-turn is told to resync.
func (c *Chat) Stream(ctx context.Context, id string, ready func(), emit func(protocol.ChatEventFrame) error) error {
s := c.session(id)
if s == nil {
meta, ok := transcriptSession(id)
if !ok {
return errors.New("unknown Claude session " + id)
}
s = c.sessionFor(id, meta.Directory)
}
ch := s.subscribe()
defer s.unsubscribe(ch)
if ready != nil {
ready()
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case frame, ok := <-ch:
if !ok {
return errors.New("Claude chat stream closed")
}
if err := emit(frame); err != nil {
return err
}
}
}
}
// Interrupt asks the CLI to cancel the in-flight turn, including queued turns.
func (c *Chat) Interrupt(ctx context.Context, id string) error {
s := c.session(id)
if s == nil {
return nil
}
s.mu.Lock()
proc := s.proc
running := s.running
s.mu.Unlock()
if proc == nil || !running {
return nil
}
requestCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
defer cancel()
_, err := proc.request(requestCtx, "interrupt", map[string]any{"cancel_queued": true})
return err
}
// ActivateSkill has no out-of-band equivalent in Claude Code; skills resolve
// through the CLI's own /skill mechanism.
func (c *Chat) ActivateSkill(context.Context, string, string) error {
return errors.New("Claude Code has no out-of-band skill activation")
}
// Models lists the CLI's own model choices, loaded at the initialize handshake.
func (c *Chat) Models(ctx context.Context, id string) ([]protocol.ChatModel, error) {
s := c.session(id)
if s == nil {
return nil, errors.New("unknown Claude session " + id)
}
proc, err := s.ensureProcess(ctx)
if err != nil {
return nil, err
}
_ = proc
s.mu.Lock()
models := append([]protocol.ChatModel(nil), s.models...)
s.mu.Unlock()
if len(models) == 0 {
return nil, errors.New("Claude Code reported no available models")
}
return models, nil
}
// SwitchModel changes the model for subsequent turns. The CLI applies it live
// when a process exists; otherwise the next process starts with it.
func (c *Chat) SwitchModel(ctx context.Context, id, provider, model string) error {
if provider != "" && provider != Backend {
return errors.New("Claude models use the claude provider")
}
model = strings.TrimSpace(model)
if model == "" {
return errors.New("a model is required")
}
s := c.session(id)
if s == nil {
return errors.New("unknown Claude session " + id)
}
s.mu.Lock()
previous := s.model
s.model = model
proc := s.proc
applied := s.appliedModel
s.mu.Unlock()
if proc != nil && model != applied {
requestCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
defer cancel()
if _, err := proc.request(requestCtx, "set_model", map[string]any{"model": model}); err != nil {
s.mu.Lock()
s.model = previous
s.mu.Unlock()
return fmt.Errorf("switch Claude model: %w", err)
}
s.mu.Lock()
s.appliedModel = model
s.mu.Unlock()
}
return nil
}
// Permissions returns the approvals still waiting for an operator answer.
func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermissionFrame, error) {
s := c.session(id)
if s == nil {
return []protocol.ChatPermissionFrame{}, nil
}
s.mu.Lock()
defer s.mu.Unlock()
frames := make([]protocol.ChatPermissionFrame, 0, len(s.approvals))
for _, approval := range s.approvals {
frames = append(frames, approval.frame)
}
sort.Slice(frames, func(i, j int) bool { return frames[i].RequestID < frames[j].RequestID })
return frames, nil
}
// Forms returns the pending operator questions.
func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error) {
s := c.session(id)
if s == nil {
return []protocol.ChatForm{}, nil
}
s.mu.Lock()
defer s.mu.Unlock()
forms := make([]protocol.ChatForm, 0, len(s.forms))
for _, form := range s.forms {
forms = append(forms, form.form)
}
sort.Slice(forms, func(i, j int) bool { return forms[i].ID < forms[j].ID })
return forms, nil
}
// Reply delivers one approval decision to the waiting CLI process.
func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
s := c.session(request.SessionID)
if s == nil {
return errors.New("unknown Claude session " + request.SessionID)
}
s.mu.Lock()
approval, ok := s.approvals[request.RequestID]
if !ok || approval.answering {
s.mu.Unlock()
return errors.New("the Claude approval is no longer awaiting an answer")
}
proc := approval.proc
var response any
switch request.Decision {
case protocol.ChatDecisionOnce:
response = map[string]any{"behavior": "allow", "updatedInput": approval.input}
case protocol.ChatDecisionAlways:
response = map[string]any{"behavior": "allow", "updatedInput": approval.input}
if len(approval.suggestions) > 0 && string(approval.suggestions) != "null" {
response = map[string]any{"behavior": "allow", "updatedInput": approval.input, "updatedPermissions": approval.suggestions}
}
case protocol.ChatDecisionReject:
response = map[string]any{"behavior": "deny", "message": "Denied by the operator"}
default:
s.mu.Unlock()
return errors.New("invalid approval decision")
}
if proc == nil {
s.mu.Unlock()
return errProcessClosed
}
approval.answering = true
s.mu.Unlock()
err := proc.respond(request.RequestID, response)
s.mu.Lock()
if err == nil {
delete(s.approvals, request.RequestID)
} else if current, exists := s.approvals[request.RequestID]; exists {
current.answering = false
}
s.mu.Unlock()
return err
}
// Answer delivers a question answer (or declines it) to the waiting CLI.
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
s := c.session(request.SessionID)
if s == nil {
return errors.New("unknown Claude session " + request.SessionID)
}
s.mu.Lock()
form, ok := s.forms[request.FormID]
if !ok || form.answering {
s.mu.Unlock()
return errors.New("the Claude question is no longer awaiting an answer")
}
proc := form.proc
s.mu.Unlock()
if proc == nil {
return errProcessClosed
}
deny := request.Action == "cancel" || request.Action == "decline"
var response any
if deny {
response = map[string]any{"behavior": "deny", "message": "The operator declined to answer"}
} else {
answers := map[string]string{}
for index, question := range form.questions {
key := fmt.Sprintf("q%d", index)
value, present := request.Answers[key]
if !present {
continue
}
switch typed := value.(type) {
case string:
answers[question] = typed
case []any:
labels := make([]string, 0, len(typed))
for _, item := range typed {
labels = append(labels, fmt.Sprint(item))
}
answers[question] = strings.Join(labels, ", ")
case []string:
answers[question] = strings.Join(typed, ", ")
default:
answers[question] = fmt.Sprint(typed)
}
}
response = map[string]any{
"behavior": "allow",
"updatedInput": map[string]any{"questions": form.rawQuestions, "answers": answers},
}
}
s.mu.Lock()
form.answering = true
s.mu.Unlock()
err := proc.respond(request.FormID, response)
s.mu.Lock()
if err == nil {
delete(s.forms, request.FormID)
} else if current, exists := s.forms[request.FormID]; exists {
current.answering = false
}
s.mu.Unlock()
return err
}
// Shells lists the commands still running in the session.
func (c *Chat) Shells(ctx context.Context, id string) ([]protocol.ChatShell, error) {
s := c.session(id)
if s == nil {
return []protocol.ChatShell{}, nil
}
s.mu.Lock()
defer s.mu.Unlock()
result := []protocol.ChatShell{}
for _, snapshot := range s.shells {
if snapshot.shell.Status == protocol.ChatShellRunning {
result = append(result, snapshot.shell)
}
}
sort.Slice(result, func(i, j int) bool { return result[i].ID < result[j].ID })
return result, nil
}
// ShellOutput pages the retained output of one command this session started.
func (c *Chat) ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) {
if query.Cursor < 0 || query.Cursor > protocol.ChatShellOutputMaxCursor || query.Limit <= 0 || query.Limit > protocol.ChatShellOutputLimit {
return protocol.ChatShellOutputPage{}, errors.New("invalid bounded Claude output query")
}
s := c.session(query.SessionID)
if s == nil {
return protocol.ChatShellOutputPage{Shell: protocol.ChatShell{ID: query.ShellID}, Unavailable: true}, nil
}
s.mu.Lock()
var snapshot *shellSnapshot
for _, candidate := range s.shells {
if candidate.shell.ID == query.ShellID {
snapshot = candidate
break
}
}
s.mu.Unlock()
if snapshot == nil {
return protocol.ChatShellOutputPage{Shell: protocol.ChatShell{ID: query.ShellID}, Unavailable: true}, nil
}
start := query.Cursor
if start > int64(len(snapshot.output)) {
start = int64(len(snapshot.output))
}
end := start + int64(query.Limit)
if end > int64(len(snapshot.output)) {
end = int64(len(snapshot.output))
}
return protocol.ChatShellOutputPage{
Shell: snapshot.shell,
Output: snapshot.output[start:end],
Cursor: end,
Size: snapshot.size,
Truncated: end < snapshot.size,
}, nil
}
// ---- CLI request handling --------------------------------------------------
type pendingApproval struct {
frame protocol.ChatPermissionFrame
input json.RawMessage
suggestions json.RawMessage
proc *process
answering bool
}
type pendingForm struct {
form protocol.ChatForm
rawQuestions json.RawMessage
questions []string
proc *process
answering bool
}
func (s *session) receivePermission(p *process, requestID string, request toolRequest) {
if requestID == "" {
return
}
if request.ToolName == "AskUserQuestion" {
s.receiveQuestion(p, requestID, request)
return
}
frame := protocol.ChatPermissionFrame{
SessionID: s.id,
RequestID: requestID,
Action: request.ToolName,
Source: &protocol.ChatPermissionSource{Type: "tool", ID: request.ToolUseID},
}
if name := request.DisplayName; name != "" && name != request.ToolName {
frame.Action = name
}
if request.Description != "" {
frame.Message = request.Description
}
frame.Resources = append(frame.Resources, permissionResources(request.ToolName, request.Input)...)
if len(request.PermissionSuggestions) > 0 && string(request.PermissionSuggestions) != "null" {
frame.AlwaysLabel = "Always allow"
}
s.mu.Lock()
s.approvals[requestID] = &pendingApproval{frame: frame, input: request.Input, suggestions: request.PermissionSuggestions, proc: p}
s.mu.Unlock()
}
func permissionResources(tool string, input json.RawMessage) []string {
var fields map[string]any
_ = json.Unmarshal(input, &fields)
text := func(key string) string {
if value, ok := fields[key].(string); ok {
return strings.TrimSpace(value)
}
return ""
}
switch tool {
case "Bash":
if command := text("command"); command != "" {
return []string{command}
}
case "Write", "Edit", "NotebookEdit", "Read":
if path := text("file_path"); path != "" {
return []string{path}
}
if path := text("notebook_path"); path != "" {
return []string{path}
}
case "WebFetch":
if target := text("url"); target != "" {
return []string{target}
}
case "WebSearch":
if query := text("query"); query != "" {
return []string{query}
}
}
// Fall back to a bounded, human-readable input summary so the operator sees
// what is being approved instead of an empty card.
bounded := boundedText(string(input), 1<<10)
if strings.TrimSpace(bounded) == "" {
return nil
}
return []string{bounded}
}
func (s *session) receiveQuestion(p *process, requestID string, request toolRequest) {
var payload struct {
Questions []struct {
Question string `json:"question"`
Header string `json:"header"`
MultiSelect bool `json:"multiSelect"`
Options []struct {
Label string `json:"label"`
Description string `json:"description"`
} `json:"options"`
} `json:"questions"`
}
if json.Unmarshal(request.Input, &payload) != nil || len(payload.Questions) == 0 {
// A question we cannot represent must not silently vanish: surface it as
// an approval card whose only useful action is deny.
s.receivePermission(p, requestID, toolRequest{ToolName: "AskUserQuestion", Input: request.Input})
return
}
form := protocol.ChatForm{ID: requestID, SessionID: s.id, Kind: "question", Title: "Claude asked a question"}
questions := make([]string, 0, len(payload.Questions))
for index, question := range payload.Questions {
questions = append(questions, question.Question)
field := protocol.ChatFormField{
Key: fmt.Sprintf("q%d", index),
Title: question.Question,
Type: "string",
Required: true,
}
if question.Header != "" {
form.Title = question.Header
}
if question.MultiSelect {
field.Type = "multiselect"
}
for _, option := range question.Options {
field.Options = append(field.Options, protocol.ChatFormOption{Value: option.Label, Label: option.Label, Description: option.Description})
}
form.Fields = append(form.Fields, field)
}
s.mu.Lock()
s.forms[requestID] = &pendingForm{form: form, rawQuestions: request.Input, questions: questions, proc: p}
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventForm, Form: &form})
}
+389
View File
@@ -0,0 +1,389 @@
// Package claude brokers an operator chat through the installed Claude Code CLI.
//
// Claude Code exposes a bidirectional JSON protocol over stdio in `--print`
// mode: stream-json input carries user turns, stream-json output carries
// assistant/tool events, and control requests carry interactive prompts
// (can_use_tool) and session queries. This adapter owns one CLI process per
// active session and mirrors that protocol into Pipelines chat frames. It never
// changes the operator's Claude configuration, starts a daemon, or invents a
// transcript: history is read back from the CLI's own session files.
package claude
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Backend is the wire value stored in the operator-session registry.
const Backend = "claude"
const (
// idleProcessExpiry releases a CLI process whose session nobody is watching.
// A later prompt resumes the same Claude session, so context is not lost.
idleProcessExpiry = 20 * time.Minute
maxLiveProcesses = 8
stderrRetained = 8 << 10
)
// BinaryPath resolves the Claude Code executable. PIPELINES_CLAUDE overrides it,
// matching the OpenCode override; common per-user install locations are tried
// because a service PATH may not carry a shell's later additions.
func BinaryPath() string {
if path := strings.TrimSpace(os.Getenv("PIPELINES_CLAUDE")); path != "" {
return path
}
if path, err := exec.LookPath("claude"); err == nil {
return path
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
for _, candidate := range []string{
filepath.Join(home, ".local/bin/claude"),
"/opt/homebrew/bin/claude",
"/usr/local/bin/claude",
} {
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate
}
}
return ""
}
// Available reports whether a Claude Code executable exists. It does not prove
// the CLI is signed in; that is established by the initialize handshake.
func Available() bool {
path := BinaryPath()
if path == "" {
return false
}
info, err := os.Stat(path)
return err == nil && !info.IsDir()
}
// ConfigDir is where Claude Code keeps its session transcripts.
func ConfigDir() string {
if dir := strings.TrimSpace(os.Getenv("CLAUDE_CONFIG_DIR")); dir != "" {
return dir
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".claude")
}
// Chat owns every Claude session this server has opened. Processes are started
// lazily per session and resumed after being released.
type Chat struct {
ctx context.Context
cancel context.CancelFunc
binary string
mu sync.Mutex
sessions map[string]*session
closed bool
}
func New(ctx context.Context) *Chat {
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithCancel(ctx)
c := &Chat{ctx: ctx, cancel: cancel, binary: BinaryPath(), sessions: map[string]*session{}}
go c.reapIdle()
return c
}
// Close stops every owned CLI process. Session transcripts stay on disk.
func (c *Chat) Close() {
c.cancel()
c.mu.Lock()
c.closed = true
sessions := make([]*session, 0, len(c.sessions))
for _, s := range c.sessions {
sessions = append(sessions, s)
}
c.sessions = map[string]*session{}
c.mu.Unlock()
for _, s := range sessions {
s.closeProcess()
}
}
// ReleaseShells drops a session's retained shell snapshot after the last
// observer leaves. A later attach re-reads the authoritative transcript.
func (c *Chat) ReleaseShells(id string) {
if s := c.session(id); s != nil {
s.mu.Lock()
s.shells = map[string]*shellSnapshot{}
s.shellOrder = nil
s.mu.Unlock()
}
}
func (c *Chat) session(id string) *session {
c.mu.Lock()
defer c.mu.Unlock()
return c.sessions[id]
}
// sessionFor returns the existing state or records a new one for an id this
// server did not create (an adopted registry row after restart).
func (c *Chat) sessionFor(id, directory string) *session {
c.mu.Lock()
defer c.mu.Unlock()
if s := c.sessions[id]; s != nil {
if directory != "" && s.directory == "" {
s.directory = directory
}
return s
}
s := &session{
chat: c,
id: id,
directory: directory,
subs: map[chan protocol.ChatEventFrame]struct{}{},
approvals: map[string]*pendingApproval{},
forms: map[string]*pendingForm{},
shells: map[string]*shellSnapshot{},
toolMessages: map[string]string{},
streamBlocks: map[int]blockState{},
streamText: map[int]string{},
streamOrdinals: map[string]int{},
lastUsed: time.Now(),
}
c.sessions[id] = s
return s
}
func (c *Chat) forget(id string) {
c.mu.Lock()
delete(c.sessions, id)
c.mu.Unlock()
}
// reapIdle releases long-idle processes and caps how many can stay alive. The
// session record and its transcript-based history survive; the next prompt
// resumes the same Claude session.
func (c *Chat) reapIdle() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-c.ctx.Done():
return
case <-ticker.C:
}
now := time.Now()
type candidate struct {
s *session
used time.Time
alive bool
}
var live []candidate
c.mu.Lock()
for _, s := range c.sessions {
s.mu.Lock()
alive := s.proc != nil
used := s.lastUsed
s.mu.Unlock()
if alive {
live = append(live, candidate{s: s, used: used})
}
}
c.mu.Unlock()
sort.Slice(live, func(i, j int) bool { return live[i].used.Before(live[j].used) })
for _, entry := range live {
entry.s.mu.Lock()
excess := len(live) > maxLiveProcesses && !entry.s.running
idle := !entry.s.running && len(entry.s.subs) == 0 && now.Sub(entry.used) > idleProcessExpiry
entry.s.mu.Unlock()
if excess || idle {
entry.s.closeProcess()
// Recompute the live count on the next tick after a close.
live = live[1:]
break
}
}
}
}
// ---------------------------------------------------------------------------
// Session state
type session struct {
chat *Chat
mu sync.Mutex
id string
directory string
title string
model string // CLI model selection (alias or full id); "" uses the CLI default
createdAt int64
proc *process
starting chan struct{}
startErr error
turnID string
running bool
lastUsed time.Time
lastErr string
subs map[chan protocol.ChatEventFrame]struct{}
approvals map[string]*pendingApproval
forms map[string]*pendingForm
shells map[string]*shellSnapshot
shellOrder []string
usage *protocol.ChatEventFrame
compaction *protocol.ChatEventFrame
prompts []promptRecord
models []protocol.ChatModel
// model is the requested selection; modelActual is the model the CLI last
// reported for a message. appliedModel is what the live process was told.
modelActual string
appliedModel string
// Stream assembly for the message currently being received.
streamID string
streamBlocks map[int]blockState
streamText map[int]string
streamOrdinals map[string]int
toolMessages map[string]string
}
type promptRecord struct {
id string
text string
}
type blockState struct {
kind string
ordinal int
}
func (s *session) sessionID() string { return s.id }
// emit broadcasts one frame to every watcher. A slow watcher never blocks the
// CLI reader; the hub repairs from history on its next subscription.
func (s *session) emit(frame protocol.ChatEventFrame) {
if frame.SessionID == "" {
frame.SessionID = s.id
}
s.mu.Lock()
if frame.Kind == protocol.ChatEventUsage && frame.Usage != nil {
s.usage = &frame
}
if frame.Kind == protocol.ChatEventCompaction && frame.Compaction != nil {
if frame.Compaction.Status == "running" {
s.compaction = &frame
} else {
s.compaction = nil
}
}
targets := make([]chan protocol.ChatEventFrame, 0, len(s.subs))
for ch := range s.subs {
targets = append(targets, ch)
}
s.mu.Unlock()
for _, ch := range targets {
select {
case ch <- frame:
default:
}
}
}
func (s *session) subscribe() chan protocol.ChatEventFrame {
ch := make(chan protocol.ChatEventFrame, 256)
s.mu.Lock()
s.subs[ch] = struct{}{}
if s.usage != nil {
ch <- *s.usage
}
if s.compaction != nil {
ch <- *s.compaction
}
running := s.running
s.mu.Unlock()
if running {
// A client attaching mid-turn has missed earlier text. Ask it to reload
// the authoritative transcript instead of pretending the stream is whole.
select {
case ch <- protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventResync}:
default:
}
}
return ch
}
func (s *session) unsubscribe(ch chan protocol.ChatEventFrame) {
s.mu.Lock()
delete(s.subs, ch)
s.mu.Unlock()
}
func (s *session) closeProcess() {
s.mu.Lock()
p := s.proc
s.proc = nil
s.mu.Unlock()
if p != nil {
p.close()
}
}
// findTranscriptFile locates the CLI's session file. Project directories are
// named from the working directory, so searching is more robust than deriving
// the encoding (and avoids guessing for a resumed/adopted session).
func findTranscriptFile(id string) string {
base := ConfigDir()
if base == "" || id == "" {
return ""
}
matches, err := filepath.Glob(filepath.Join(base, "projects", "*", id+".jsonl"))
if err != nil || len(matches) == 0 {
return ""
}
sort.Strings(matches)
return matches[len(matches)-1]
}
// newSessionID returns an RFC 4122 version 4 UUID, the exact form the CLI's
// --session-id accepts.
func newSessionID() (string, error) {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
return "", err
}
raw[6] = (raw[6] & 0x0f) | 0x40
raw[8] = (raw[8] & 0x3f) | 0x80
hexed := hex.EncodeToString(raw[:])
return hexed[0:8] + "-" + hexed[8:12] + "-" + hexed[12:16] + "-" + hexed[16:20] + "-" + hexed[20:32], nil
}
var errNoBinary = errors.New("Claude Code is not installed (set PIPELINES_CLAUDE or install the claude CLI)")
func (s *session) requireBinary() error {
if s.chat.binary == "" {
return errNoBinary
}
if info, err := os.Stat(s.chat.binary); err != nil || info.IsDir() {
return errNoBinary
}
return nil
}
+458
View File
@@ -0,0 +1,458 @@
package claude
import (
"context"
"encoding/base64"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func testChat(t *testing.T) *Chat {
t.Helper()
dir := t.TempDir()
source, err := os.ReadFile(filepath.Join("testdata", "fake-claude.py"))
if err != nil {
t.Fatal(err)
}
script := filepath.Join(dir, "claude")
if err := os.WriteFile(script, source, 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_CLAUDE", script)
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(dir, "config"))
t.Setenv("FAKE_CLAUDE_LOG", filepath.Join(dir, "args.log"))
chat := New(context.Background())
t.Cleanup(chat.Close)
return chat
}
func newCreatedChat(t *testing.T, chat *Chat) protocol.ChatSession {
t.Helper()
session, err := chat.Create(context.Background(), "Fixture", t.TempDir())
if err != nil {
t.Fatal(err)
}
return session
}
func subscribe(t *testing.T, chat *Chat, id string) chan protocol.ChatEventFrame {
t.Helper()
frames := make(chan protocol.ChatEventFrame, 512)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_ = chat.Stream(ctx, id, nil, func(frame protocol.ChatEventFrame) error {
select {
case frames <- frame:
default:
}
return nil
})
}()
t.Cleanup(func() {
cancel()
<-done
})
// Wait for the subscription to be attached before prompting.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
chat.session(id).mu.Lock()
count := len(chat.session(id).subs)
chat.session(id).mu.Unlock()
if count > 0 {
return frames
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("stream did not attach")
return nil
}
func waitFrame(t *testing.T, frames <-chan protocol.ChatEventFrame, what string, match func(protocol.ChatEventFrame) bool) protocol.ChatEventFrame {
t.Helper()
deadline := time.After(6 * time.Second)
for {
select {
case frame := <-frames:
if match(frame) {
return frame
}
case <-deadline:
t.Fatalf("timed out waiting for %s", what)
}
}
}
func waitStepEnded(t *testing.T, frames <-chan protocol.ChatEventFrame) {
t.Helper()
waitFrame(t, frames, "step ended", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded
})
}
func eventually(t *testing.T, what string, check func() bool) {
t.Helper()
deadline := time.Now().Add(6 * time.Second)
for time.Now().Before(deadline) {
if check() {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", what)
}
func TestTurnStreamsTextWithoutDuplicatingAndReportsUsage(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
t.Fatal(err)
}
text := ""
var usage *protocol.ChatUsage
ended := false
deadline := time.After(8 * time.Second)
for !ended || usage == nil {
select {
case frame := <-frames:
switch frame.Kind {
case protocol.ChatPartText:
text += frame.Delta
case protocol.ChatEventStep:
if frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded {
ended = true
}
case protocol.ChatEventUsage:
usage = frame.Usage
}
case <-deadline:
t.Fatalf("turn did not settle (ended=%v usage=%v text=%q)", ended, usage != nil, text)
}
}
if text != "Hello world" {
t.Fatalf("streamed text = %q, want one copy of Hello world", text)
}
if usage.TotalTokens == nil || *usage.TotalTokens != 100 {
t.Fatalf("usage totals: %+v", usage)
}
if usage.ContextWindow == nil || *usage.ContextWindow != 200000 || usage.ContextTokens == nil || *usage.ContextTokens != 60 {
t.Fatalf("context usage: %+v", usage)
}
if usage.CostUSD == nil || *usage.CostUSD != 0.25 || usage.Scope != "session" {
t.Fatalf("cost/scope: %+v", usage)
}
}
func TestApprovalAllowAndRejectReachTheCLI(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "permission please"); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "running tool", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.Name == "Write" && frame.Part.State != nil && frame.Part.State.Status == protocol.ChatToolRunning
})
var pending []protocol.ChatPermissionFrame
eventually(t, "permission request", func() bool {
var err error
pending, err = chat.Permissions(context.Background(), session.ID)
return err == nil && len(pending) == 1
})
request := pending[0]
if request.Action != "Write" || len(request.Resources) != 1 || !strings.HasSuffix(request.Resources[0], "note.txt") {
t.Fatalf("approval frame: %+v", request)
}
if request.AlwaysLabel == "" {
t.Fatal("a suggestion should offer Always allow")
}
if err := chat.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: session.ID, RequestID: request.RequestID, Decision: protocol.ChatDecisionOnce}); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "completed tool", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.ID == "toolu_fake_1" &&
frame.Part.State != nil && frame.Part.State.Status == protocol.ChatToolCompleted &&
len(frame.Part.State.Content) == 1 && strings.Contains(frame.Part.State.Content[0].Text, "File created")
})
waitStepEnded(t, frames)
// A rejection is delivered as a deny, and the turn still settles.
if err := chat.Prompt(context.Background(), session.ID, "permission reject"); err != nil {
t.Fatal(err)
}
eventually(t, "second permission request", func() bool {
var err error
pending, err = chat.Permissions(context.Background(), session.ID)
return err == nil && len(pending) == 1
})
if err := chat.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: session.ID, RequestID: pending[0].RequestID, Decision: protocol.ChatDecisionReject}); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "rejected tool", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.State != nil &&
frame.Part.State.Status == protocol.ChatToolError && frame.Part.State.Error != nil
})
waitStepEnded(t, frames)
if remaining, _ := chat.Permissions(context.Background(), session.ID); len(remaining) != 0 {
t.Fatalf("resolved approval still pending: %+v", remaining)
}
}
func TestQuestionBecomesAFormAndAnswerReturnsToCLI(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "question please"); err != nil {
t.Fatal(err)
}
var forms []protocol.ChatForm
eventually(t, "question form", func() bool {
var err error
forms, err = chat.Forms(context.Background(), session.ID)
return err == nil && len(forms) == 1
})
form := forms[0]
if form.Kind != "question" || len(form.Fields) != 1 || len(form.Fields[0].Options) != 2 {
t.Fatalf("form: %+v", form)
}
if err := chat.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: session.ID, FormID: form.ID, Answers: map[string]any{"q0": "Alpha"}}); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "answered tool", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.State != nil &&
frame.Part.State.Status == protocol.ChatToolCompleted && len(frame.Part.State.Content) == 1 &&
strings.Contains(frame.Part.State.Content[0].Text, "Alpha")
})
waitStepEnded(t, frames)
if forms, _ := chat.Forms(context.Background(), session.ID); len(forms) != 0 {
t.Fatalf("resolved form still pending: %+v", forms)
}
}
func TestInterruptSettlesTheTurn(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "long task"); err != nil {
t.Fatal(err)
}
if err := chat.Interrupt(context.Background(), session.ID); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
chat.session(session.ID).mu.Lock()
running := chat.session(session.ID).running
chat.session(session.ID).mu.Unlock()
if running {
t.Fatal("session still marked running after interrupt")
}
}
func TestModelChoiceIsAppliedAndProcessResumes(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
if err := chat.SwitchModel(context.Background(), session.ID, Backend, "sonnet"); err != nil {
t.Fatal(err)
}
models, err := chat.Models(context.Background(), session.ID)
if err != nil {
t.Fatal(err)
}
if len(models) != 3 || models[1].ID != "sonnet" || models[1].Provider != Backend {
t.Fatalf("models: %+v", models)
}
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
logPath := os.Getenv("FAKE_CLAUDE_LOG")
entries := readArgs(t, logPath)
if argValue(entries[len(entries)-1].Args, "--model") != "sonnet" {
t.Fatalf("spawn did not apply the selected model: %+v", entries)
}
if argValue(entries[len(entries)-1].Args, "--session-id") != session.ID {
t.Fatalf("new session did not pin its id: %+v", entries)
}
// Releasing the process and prompting again must resume the same session.
chat.session(session.ID).closeProcess()
if err := chat.Prompt(context.Background(), session.ID, "hello again"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
entries = readArgs(t, logPath)
if len(entries) < 2 || argValue(entries[len(entries)-1].Args, "--resume") != session.ID {
t.Fatalf("restart did not resume the session: %+v", entries)
}
}
type argsEntry struct {
Args []string `json:"args"`
Cwd string `json:"cwd"`
}
func readArgs(t *testing.T, path string) []argsEntry {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var entries []argsEntry
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
if line == "" {
continue
}
var entry argsEntry
if json.Unmarshal([]byte(line), &entry) == nil {
entries = append(entries, entry)
}
}
return entries
}
func argValue(values []string, flag string) string {
for index, value := range values {
if value == flag && index+1 < len(values) {
return values[index+1]
}
}
return ""
}
func TestHistoryMergesBlocksAndMapsPromptIdentity(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.PromptWithMessageID(context.Background(), session.ID, "permission please", "native-user-1"); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "permission", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.Name == "Write"
})
var pending []protocol.ChatPermissionFrame
eventually(t, "pending approval", func() bool {
pending, _ = chat.Permissions(context.Background(), session.ID)
return len(pending) == 1
})
if err := chat.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: session.ID, RequestID: pending[0].RequestID, Decision: protocol.ChatDecisionOnce}); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
eventually(t, "transcript", func() bool { return sessionTranscriptPath(session.ID) != "" })
page, err := chat.Messages(context.Background(), session.ID, 50, "")
if err != nil {
t.Fatal(err)
}
if len(page.Messages) != 2 {
t.Fatalf("history messages: %+v", page.Messages)
}
user := page.Messages[0]
if user.Role != protocol.ChatRoleUser || user.ID != "native-user-1" {
t.Fatalf("user message identity: %+v", user)
}
if len(user.Parts) != 1 || user.Parts[0].Text != "permission please" {
t.Fatalf("user parts: %+v", user.Parts)
}
assistant := page.Messages[1]
if assistant.Role != protocol.ChatRoleAssistant || len(assistant.Parts) != 2 {
t.Fatalf("assistant message: %+v", assistant)
}
if assistant.Parts[0].Type != protocol.ChatPartText || assistant.Parts[0].Text != "Hello world" {
t.Fatalf("assistant text: %+v", assistant.Parts[0])
}
tool := assistant.Parts[1]
if tool.Type != protocol.ChatPartTool || tool.Name != "Write" || tool.State == nil || tool.State.Status != protocol.ChatToolCompleted {
t.Fatalf("assistant tool: %+v", tool)
}
if len(tool.State.Content) != 1 || !strings.Contains(tool.State.Content[0].Text, "File created") {
t.Fatalf("tool content: %+v", tool.State.Content)
}
// Newest-first paging: one long assistant turn is one message.
first, err := chat.Messages(context.Background(), session.ID, 1, "")
if err != nil {
t.Fatal(err)
}
if len(first.Messages) != 1 || first.Messages[0].Role != protocol.ChatRoleAssistant || !first.HasMore || first.NextCursor == "" {
t.Fatalf("first page: %+v", first)
}
older, err := chat.Messages(context.Background(), session.ID, 1, first.NextCursor)
if err != nil {
t.Fatal(err)
}
if len(older.Messages) != 1 || older.Messages[0].Role != protocol.ChatRoleUser || older.HasMore {
t.Fatalf("older page: %+v", older)
}
}
func TestAttachmentContentIncludesImageAndText(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
dir := t.TempDir()
imagePath := filepath.Join(dir, "pixel.png")
imageData := []byte{0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 3}
if err := os.WriteFile(imagePath, imageData, 0o600); err != nil {
t.Fatal(err)
}
textPath := filepath.Join(dir, "notes.txt")
if err := os.WriteFile(textPath, []byte("fixture notes"), 0o600); err != nil {
t.Fatal(err)
}
frames := subscribe(t, chat, session.ID)
files := []opencode.PromptFile{
opencode.NewPreparedPromptFile("file://"+imagePath, "pixel.png"),
opencode.NewPreparedPromptFile("file://"+textPath, "notes.txt"),
}
if err := chat.PromptWithMessageIDFiles(context.Background(), session.ID, "see attached", "native-user-2", files); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
content, err := os.ReadFile(os.Getenv("FAKE_CLAUDE_LOG") + ".content")
if err != nil {
t.Fatal(err)
}
var blocks []map[string]any
if err := json.Unmarshal([]byte(strings.TrimSpace(string(content))), &blocks); err != nil {
t.Fatal(err)
}
var sawImage, sawText bool
for _, block := range blocks {
if block["type"] == "image" {
source, _ := block["source"].(map[string]any)
decoded, _ := base64.StdEncoding.DecodeString(source["data"].(string))
if string(decoded) != string(imageData) || source["media_type"] != "image/png" {
t.Fatalf("image block: %+v", block)
}
sawImage = true
}
if block["type"] == "text" && strings.Contains(block["text"].(string), "fixture notes") {
sawText = true
}
}
if !sawImage || !sawText {
t.Fatalf("missing attachment content: %+v", blocks)
}
}
func TestSignedOutCLIReturnsAnActionableError(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
t.Setenv("FAKE_CLAUDE_FAIL", "1")
err := chat.Prompt(context.Background(), session.ID, "hello")
if err == nil {
t.Fatal("a signed-out CLI must fail the prompt")
}
if !strings.Contains(strings.ToLower(err.Error()), "login") && !strings.Contains(strings.ToLower(err.Error()), "sign") {
t.Fatalf("error is not actionable: %v", err)
}
}
+372
View File
@@ -0,0 +1,372 @@
package claude
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"sync"
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// initializeTimeout bounds the CLI's first handshake. A cold start loads the
// operator's skills/plugins, so this is deliberately generous but still finite.
const initializeTimeout = 60 * time.Second
const controlRequestTimeout = 20 * time.Second
const maxLineBytes = 32 << 20
var errProcessClosed = errors.New("Claude Code process is not running")
// process is one owned CLI process for one session. Requests and responses are
// multiplexed on stdin/stdout; the reader goroutine is the only consumer, so a
// control request is always awaited by a different goroutine.
type process struct {
session *session
cmd *exec.Cmd
stdin io.WriteCloser
writeMu sync.Mutex
reqMu sync.Mutex
nextReq atomic.Uint64
pending map[string]chan controlReply
mu sync.Mutex
stderr strings.Builder
exited bool
exitErr error
done chan struct{}
stderrDone chan struct{}
}
type controlReply struct {
response json.RawMessage
err string
}
// spawn starts the CLI in the session directory. A session whose transcript
// already exists resumes it; a new one pins the id we recorded at create time.
func (s *session) spawn(ctx context.Context) (*process, error) {
if err := s.requireBinary(); err != nil {
return nil, err
}
if strings.TrimSpace(s.directory) == "" {
return nil, errors.New("a Claude session needs an existing absolute directory")
}
if info, err := os.Stat(s.directory); err != nil || !info.IsDir() {
return nil, fmt.Errorf("Claude session directory is not available: %s", s.directory)
}
args := []string{
"-p",
"--input-format", "stream-json",
"--output-format", "stream-json",
"--verbose",
"--include-partial-messages",
"--permission-prompt-tool=stdio",
"--permission-prompts", "host",
}
if findTranscriptFile(s.id) != "" {
args = append(args, "--resume", s.id)
} else {
args = append(args, "--session-id", s.id)
}
if s.model != "" {
args = append(args, "--model", s.model)
}
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
cmd.Env = os.Environ()
cmd.WaitDelay = 5 * time.Second
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start Claude Code: %w", err)
}
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{})}
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
// The CLI holds can_use_tool requests until the host has initialized. Do that
// before any user turn so an approval is never silently denied.
initCtx, cancel := context.WithTimeout(ctx, initializeTimeout)
defer cancel()
models, err := p.initialize(initCtx)
if err != nil {
p.close()
return nil, err
}
s.mu.Lock()
s.models = models
s.lastErr = ""
s.mu.Unlock()
return p, nil
}
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, error) {
raw, err := p.request(ctx, "initialize", map[string]any{"subtype": "initialize"})
if err != nil {
return nil, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
}
var reply struct {
Models []struct {
Value string `json:"value"`
ResolvedModel string `json:"resolvedModel"`
DisplayName string `json:"displayName"`
Description string `json:"description"`
} `json:"models"`
}
if err := json.Unmarshal(raw, &reply); err != nil {
return nil, errors.New("Claude Code returned an invalid initialize response")
}
models := make([]protocol.ChatModel, 0, len(reply.Models))
for _, m := range reply.Models {
if strings.TrimSpace(m.Value) == "" {
continue
}
name := m.DisplayName
if name == "" {
name = m.Value
}
models = append(models, protocol.ChatModel{ID: m.Value, Provider: Backend, Name: name})
}
if len(models) == 0 {
return nil, errors.New("Claude Code reported no models; check that the CLI is signed in")
}
return models, nil
}
// request sends one control request and waits for its control_response.
func (p *process) request(ctx context.Context, subtype string, payload map[string]any) (json.RawMessage, error) {
if payload == nil {
payload = map[string]any{}
}
payload["subtype"] = subtype
id := fmt.Sprintf("pipelines-%d-%d", time.Now().UnixNano(), p.nextReq.Add(1))
ch := make(chan controlReply, 1)
p.mu.Lock()
if p.exited {
p.mu.Unlock()
return nil, errProcessClosed
}
p.pending[id] = ch
p.mu.Unlock()
err := p.write(map[string]any{"type": "control_request", "request_id": id, "request": payload})
if err != nil {
p.mu.Lock()
delete(p.pending, id)
p.mu.Unlock()
return nil, err
}
select {
case <-ctx.Done():
p.mu.Lock()
delete(p.pending, id)
p.mu.Unlock()
return nil, ctx.Err()
case reply := <-ch:
if reply.err != "" {
return nil, errors.New(reply.err)
}
return reply.response, nil
case <-p.done:
return nil, errProcessClosed
}
}
// respond answers one CLI-initiated control request.
func (p *process) respond(requestID string, response any) error {
return p.write(map[string]any{
"type": "control_response",
"response": map[string]any{"subtype": "success", "request_id": requestID, "response": response},
})
}
func (p *process) write(value any) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
data = append(data, '\n')
p.writeMu.Lock()
defer p.writeMu.Unlock()
p.mu.Lock()
exited := p.exited
p.mu.Unlock()
if exited {
return errProcessClosed
}
if _, err := p.stdin.Write(data); err != nil {
return fmt.Errorf("write to Claude Code: %w", err)
}
return nil
}
func (p *process) readStderr(stderr io.Reader) {
defer close(p.stderrDone)
buffer := make([]byte, 4<<10)
for {
n, err := stderr.Read(buffer)
if n > 0 {
p.mu.Lock()
if p.stderr.Len() < stderrRetained {
remaining := stderrRetained - p.stderr.Len()
if n > remaining {
p.stderr.Write(buffer[:remaining])
} else {
p.stderr.Write(buffer[:n])
}
}
p.mu.Unlock()
}
if err != nil {
return
}
}
}
func (p *process) readStdout(stdout io.Reader) {
scanner := bufio.NewScanner(stdout)
scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
p.session.handleLine(p, line)
}
}
func (p *process) wait() {
err := p.cmd.Wait()
select {
case <-p.stderrDone:
case <-time.After(time.Second):
}
p.finish(err)
}
func (p *process) finish(err error) {
p.mu.Lock()
if p.exited {
p.mu.Unlock()
return
}
p.exited = true
p.exitErr = err
pending := p.pending
p.pending = map[string]chan controlReply{}
close(p.done)
p.mu.Unlock()
for id, ch := range pending {
select {
case ch <- controlReply{err: "Claude Code exited before answering " + id}:
default:
}
}
_ = p.stdin.Close()
p.session.processExit(p, err)
}
func (p *process) close() {
p.mu.Lock()
exited := p.exited
p.mu.Unlock()
if exited {
return
}
_ = p.stdin.Close()
if p.cmd.Process != nil {
_ = p.cmd.Process.Signal(os.Interrupt)
}
select {
case <-p.done:
case <-time.After(3 * time.Second):
if p.cmd.Process != nil {
_ = p.cmd.Process.Kill()
}
}
}
// diagnostic returns a short stderr tail for an actionable failure message.
func (p *process) diagnostic() string {
p.mu.Lock()
defer p.mu.Unlock()
text := strings.TrimSpace(p.stderr.String())
if text == "" {
return ""
}
if len(text) > 600 {
text = text[len(text)-600:]
}
return ": " + strings.ReplaceAll(text, "\n", " ")
}
// processExit settles a turn whose process disappeared instead of leaving the
// web spinner and its Stop control running forever.
func (s *session) processExit(p *process, err error) {
diagnostic := ""
if err != nil {
diagnostic = err.Error()
}
if tail := p.diagnostic(); tail != "" {
diagnostic += tail
}
s.mu.Lock()
if s.proc != p {
s.mu.Unlock()
// A resumed replacement already owns the session.
return
}
s.proc = nil
s.lastErr = strings.TrimSpace(diagnostic)
s.approvals = map[string]*pendingApproval{}
s.forms = map[string]*pendingForm{}
running := s.running
turn := s.turnID
s.running = false
s.turnID = ""
s.streamBlocks = map[int]blockState{}
s.streamText = map[int]string{}
s.streamOrdinals = map[string]int{}
s.mu.Unlock()
if !running {
return
}
message := "Claude Code exited before the turn finished"
if strings.TrimSpace(diagnostic) != "" {
message += ": " + strings.TrimSpace(diagnostic)
}
s.emit(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: turn,
MessageID: "claude-exit-" + turn,
Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: "claude-exit-" + turn,
Name: "Claude Code",
State: &protocol.ChatToolState{
Status: protocol.ChatToolError,
Error: &protocol.ChatError{Type: "process", Message: boundedText(message, 2<<10)},
},
},
})
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
}
+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Deterministic stand-in for the Claude Code CLI's SDK stdio protocol.
It implements only what Pipelines' adapter uses: initialize, stream-json turns,
can_use_tool approvals, AskUserQuestion, set_model, interrupt, usage queries and
a session transcript. It never contacts a provider.
"""
import json
import os
import re
import sys
args = sys.argv[1:]
state = {"session": None, "turn": 0, "model": None, "pending": None, "transcript": None}
for index, arg in enumerate(args):
if arg in ("--session-id", "--resume") and index + 1 < len(args):
state["session"] = args[index + 1]
if arg == "--model" and index + 1 < len(args):
state["model"] = args[index + 1]
log_path = os.environ.get("FAKE_CLAUDE_LOG")
if log_path:
with open(log_path, "a", encoding="utf-8") as log:
log.write(json.dumps({"args": args, "cwd": os.getcwd()}) + "\n")
if os.environ.get("FAKE_CLAUDE_FAIL"):
sys.stderr.write("Please run /login to sign in\n")
sys.exit(2)
def send(value):
sys.stdout.write(json.dumps(value, separators=(",", ":")) + "\n")
sys.stdout.flush()
def respond(request_id, response):
send({"type": "control_response", "response": {"subtype": "success", "request_id": request_id, "response": response}})
def slug(cwd):
return re.sub(r"[^A-Za-z0-9]", "-", cwd)
def transcript_path():
base = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join(os.path.expanduser("~"), ".claude")
directory = os.path.join(base, "projects", slug(os.getcwd()))
os.makedirs(directory, exist_ok=True)
return os.path.join(directory, state["session"] + ".jsonl")
def append(entry):
path = transcript_path()
with open(path, "a", encoding="utf-8") as file:
file.write(json.dumps(entry) + "\n")
def stamp():
return "2026-10-22T12:00:00Z"
def user_message(text):
state["turn"] += 1
append({"type": "user", "uuid": "user-%d" % state["turn"], "timestamp": stamp(),
"message": {"role": "user", "content": [{"type": "text", "text": text}]}})
send({"type": "system", "subtype": "init", "session_id": state["session"],
"model": "claude-test", "permissionMode": "default", "cwd": os.getcwd()})
message_id = "msg_fake_%d" % state["turn"]
send({"type": "stream_event", "event": {"type": "message_start", "message": {"id": message_id}}})
send({"type": "stream_event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}}})
for delta in ("Hello ", "world"):
send({"type": "stream_event", "event": {"type": "content_block_delta", "index": 0,
"delta": {"type": "text_delta", "text": delta}}})
send({"type": "stream_event", "event": {"type": "content_block_stop", "index": 0}})
send({"type": "stream_event", "event": {"type": "message_stop"}})
append({"type": "assistant", "uuid": "asst-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": "Hello world"}]}})
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": "Hello world"}]}})
if "long" in text:
append({"type": "assistant", "uuid": "asst-long-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": "Hello world"}]}})
state["pending"] = {"kind": "long", "message": message_id, "tool": ""}
return
if "permission" in text:
tool_id = "toolu_fake_%d" % state["turn"]
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "Write",
"input": {"file_path": os.path.join(os.getcwd(), "note.txt"),
"content": "hi"}}]}})
append({"type": "assistant", "uuid": "asst-tool-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "Write",
"input": {"file_path": os.path.join(os.getcwd(), "note.txt"), "content": "hi"}}]}})
state["pending"] = {"kind": "permission", "message": message_id, "tool": tool_id}
send({"type": "control_request", "request_id": "req-permission-%d" % state["turn"],
"request": {"subtype": "can_use_tool", "tool_name": "Write", "display_name": "Write",
"description": "note.txt",
"input": {"file_path": os.path.join(os.getcwd(), "note.txt"), "content": "hi"},
"permission_suggestions": [{"type": "setMode", "mode": "acceptEdits", "destination": "session"}],
"tool_use_id": tool_id}})
return
if "question" in text:
tool_id = "toolu_question_%d" % state["turn"]
questions = {"questions": [{"question": "Pick one?", "header": "Pick one", "multiSelect": False,
"options": [{"label": "Alpha", "description": "First"}, {"label": "Beta", "description": "Second"}]}]}
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "AskUserQuestion", "input": questions}]}})
append({"type": "assistant", "uuid": "asst-question-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "tool_use", "id": tool_id, "name": "AskUserQuestion", "input": questions}]}})
state["pending"] = {"kind": "question", "message": message_id, "tool": tool_id}
send({"type": "control_request", "request_id": "req-question-%d" % state["turn"],
"request": {"subtype": "can_use_tool", "tool_name": "AskUserQuestion", "display_name": "AskUserQuestion",
"input": questions, "requires_user_interaction": True, "tool_use_id": tool_id}})
return
finish(message_id)
def finish(message_id):
send({"type": "result", "subtype": "success", "is_error": False, "result": "Hello world",
"session_id": state["session"], "total_cost_usd": 0.25,
"usage": {"input_tokens": 10, "output_tokens": 20}})
def tool_result(text, is_error=False):
pending = state["pending"]
state["pending"] = None
block = {"type": "tool_result", "tool_use_id": pending["tool"], "content": text}
if is_error:
block["is_error"] = True
send({"type": "user", "message": {"role": "user", "content": [block]}})
append({"type": "user", "uuid": "result-%d" % state["turn"], "timestamp": stamp(), "toolUseResult": text,
"message": {"role": "user", "content": [block]}})
finish(pending["message"])
def handle(line):
try:
value = json.loads(line)
except ValueError:
return
kind = value.get("type")
if kind == "control_request":
request = value.get("request") or {}
subtype = request.get("subtype")
if subtype == "initialize":
respond(value.get("request_id"), {
"models": [
{"value": "default", "displayName": "Default", "description": "Default model"},
{"value": "sonnet", "displayName": "Sonnet", "description": "Sonnet model"},
{"value": "haiku", "displayName": "Haiku", "description": "Haiku model"},
],
"commands": [], "agents": [],
})
elif subtype == "set_model":
state["model"] = request.get("model")
respond(value.get("request_id"), {"model": request.get("model")})
elif subtype == "interrupt":
respond(value.get("request_id"), {"still_queued": [], "cancelled": []})
if state["pending"]:
state["pending"] = None
send({"type": "result", "subtype": "error_during_execution", "is_error": True,
"result": "Interrupted", "session_id": state["session"]})
elif subtype == "get_usage":
respond(value.get("request_id"), {"session": {
"total_cost_usd": 0.25,
"model_usage": {"claude-test": {"inputTokens": 10, "outputTokens": 20,
"cacheReadInputTokens": 30, "cacheCreationInputTokens": 40,
"costUSD": 0.25, "contextWindow": 200000}}}})
elif subtype == "get_context_usage":
respond(value.get("request_id"), {"totalTokens": 60, "maxTokens": 200000})
else:
send({"type": "control_response", "response": {"subtype": "error",
"request_id": value.get("request_id"),
"error": "unsupported in fixture"}})
return
if kind == "control_response":
response = value.get("response") or {}
pending = state["pending"]
if not pending:
return
if response.get("subtype") == "error":
tool_result("Error: " + str(response.get("error")), True)
return
result = response.get("response") or {}
if result.get("behavior") == "deny":
tool_result("Error: " + str(result.get("message") or "denied"), True)
return
if pending["kind"] == "question":
answers = (result.get("updatedInput") or {}).get("answers") or {}
tool_result("Your questions have been answered: " + json.dumps(answers))
else:
tool_result("File created successfully")
return
if kind == "user":
message = value.get("message") or {}
content = message.get("content")
text = ""
if isinstance(content, list):
text = " ".join(block.get("text", "") for block in content if block.get("type") == "text")
images = [block for block in content if block.get("type") == "image"]
if images and log_path:
with open(log_path + ".content", "a", encoding="utf-8") as log:
log.write(json.dumps(content) + "\n")
user_message(text)
for line in sys.stdin:
handle(line.strip())
+358
View File
@@ -0,0 +1,358 @@
package claude
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// maxTranscriptBytes bounds one history read. A Claude session file grows with
// every turn; past this bound the caller is told the truth instead of being
// served a silently truncated conversation.
const maxTranscriptBytes = 64 << 20
type transcriptEntry struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
UUID string `json:"uuid"`
IsSidechain bool `json:"isSidechain"`
Timestamp string `json:"timestamp"`
Cwd string `json:"cwd"`
Message struct {
ID string `json:"id"`
Role string `json:"role"`
Model string `json:"model"`
Content json.RawMessage `json:"content"`
} `json:"message"`
ToolUseResult json.RawMessage `json:"toolUseResult"`
Compact json.RawMessage `json:"compactMetadata"`
}
func readTranscript(path string) ([]transcriptEntry, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return nil, err
}
if info.Size() > maxTranscriptBytes {
return nil, fmt.Errorf("the Claude session transcript is larger than the %d MiB history limit", maxTranscriptBytes>>20)
}
scanner := bufio.NewScanner(file)
scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
var entries []transcriptEntry
for scanner.Scan() {
line := scanner.Bytes()
if len(line) == 0 {
continue
}
var entry transcriptEntry
if json.Unmarshal(line, &entry) == nil {
entries = append(entries, entry)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return entries, nil
}
// transcriptSession describes a session from its retained file, so the manager
// can resolve a registry row after a restart.
func transcriptSession(id string) (protocol.ChatSession, bool) {
path := findTranscriptFile(id)
if path == "" {
return protocol.ChatSession{}, false
}
session := protocol.ChatSession{ID: id, Backend: Backend, ModelProvider: Backend, Tag: protocol.ChatSessionTagOperator}
entries, err := readTranscript(path)
if err != nil {
return session, true
}
for _, entry := range entries {
if entry.Cwd != "" && session.Directory == "" {
session.Directory = entry.Cwd
}
if stamp, ok := transcriptTime(entry.Timestamp); ok {
if session.CreatedAt == 0 || stamp < session.CreatedAt {
session.CreatedAt = stamp
}
if stamp > session.UpdatedAt {
session.UpdatedAt = stamp
}
}
if entry.Type == "assistant" && entry.Message.Model != "" && !entry.IsSidechain {
session.Model = entry.Message.Model
}
}
return session, true
}
func transcriptTime(text string) (int64, bool) {
if strings.TrimSpace(text) == "" {
return 0, false
}
parsed, err := time.Parse(time.RFC3339Nano, text)
if err != nil {
return 0, false
}
return parsed.UnixMilli(), true
}
// transcriptMessages maps the CLI's own session file into chat messages. It
// merges the JSONL's one-entry-per-content-block shape by message id, attaches
// tool results to the call that produced them, and never invents a turn.
func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHistoryPage, error) {
path := findTranscriptFile(s.id)
if path == "" {
return protocol.ChatHistoryPage{Messages: []protocol.ChatMessage{}}, nil
}
entries, err := readTranscript(path)
if err != nil {
return protocol.ChatHistoryPage{}, err
}
s.mu.Lock()
prompts := append([]promptRecord(nil), s.prompts...)
s.mu.Unlock()
promptIDs := map[string][]string{}
for _, prompt := range prompts {
if prompt.id == "" || prompt.text == "" {
continue
}
promptIDs[prompt.text] = append(promptIDs[prompt.text], prompt.id)
}
usedPrompts := map[string]int{}
takePromptID := func(text string) string {
text = strings.TrimSpace(text)
ids := promptIDs[text]
if len(ids) == 0 {
return ""
}
index := usedPrompts[text]
if index >= len(ids) {
return ""
}
usedPrompts[text] = index + 1
return ids[index]
}
messages := []protocol.ChatMessage{}
messageIndex := map[string]int{}
toolIndex := map[string][2]int{} // tool id -> message/part index
for _, entry := range entries {
if entry.IsSidechain {
continue
}
switch entry.Type {
case "assistant":
messageID := strings.TrimSpace(entry.Message.ID)
if messageID == "" {
messageID = entry.UUID
}
if messageID == "" {
continue
}
created, _ := transcriptTime(entry.Timestamp)
index, exists := messageIndex[messageID]
if !exists {
messages = append(messages, protocol.ChatMessage{ID: messageID, SessionID: s.id, Role: protocol.ChatRoleAssistant, Model: entry.Message.Model, CreatedAt: created, Parts: []protocol.ChatPart{}})
index = len(messages) - 1
messageIndex[messageID] = index
}
if entry.Message.Model != "" {
messages[index].Model = entry.Message.Model
}
blocks := decodeBlocks(entry.Message.Content)
for _, block := range blocks {
switch block.Type {
case "text":
if strings.TrimSpace(block.Text) == "" {
continue
}
ordinal := textOrdinal(messages[index].Parts, protocol.ChatPartText)
part := protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartText, ordinal), Text: block.Text}
messages[index].Parts = append(messages[index].Parts, part)
case "thinking":
if strings.TrimSpace(block.Thinking) == "" {
continue
}
ordinal := textOrdinal(messages[index].Parts, protocol.ChatPartReasoning)
part := protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartReasoning, ordinal), Text: block.Thinking}
messages[index].Parts = append(messages[index].Parts, part)
case "tool_use":
if block.ID == "" {
continue
}
part := protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: block.ID,
Name: block.Name,
State: &protocol.ChatToolState{
Status: protocol.ChatToolRunning,
Input: truncateJSON(block.Input, 64<<10),
},
}
messages[index].Parts = append(messages[index].Parts, part)
toolIndex[block.ID] = [2]int{index, len(messages[index].Parts) - 1}
}
}
case "user":
if len(entry.Message.Content) > 0 && entry.Message.Content[0] == '"' {
// A string user entry is harness feedback (local command output or
// a tool protocol message), never a turn the operator sent.
continue
}
blocks := decodeBlocks(entry.Message.Content)
var text string
files := []protocol.ChatPart{}
hasResult := false
for _, block := range blocks {
switch block.Type {
case "tool_result":
hasResult = true
applyTranscriptToolResult(&messages, toolIndex, block)
case "text":
if strings.TrimSpace(block.Text) == "" {
continue
}
if text != "" {
text += "\n"
}
text += block.Text
case "image":
if block.Source != nil && block.Source.Data != "" && len(block.Source.Data) <= 512<<10 {
files = append(files, protocol.ChatPart{Type: protocol.ChatPartFile, Mime: block.Source.MediaType, Name: "image", URI: "data:" + block.Source.MediaType + ";base64," + block.Source.Data})
}
}
}
if hasResult || (text == "" && len(files) == 0) {
continue
}
id := takePromptID(text)
if id == "" {
id = entry.UUID
}
if id == "" {
continue
}
created, _ := transcriptTime(entry.Timestamp)
parts := []protocol.ChatPart{}
if text != "" {
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#text", Text: text})
}
parts = append(parts, files...)
messages = append(messages, protocol.ChatMessage{ID: id, SessionID: s.id, Role: protocol.ChatRoleUser, CreatedAt: created, Parts: parts})
}
}
// Drop assistant messages that ended with no renderable part (for example a
// signature-only thinking entry).
filtered := messages[:0]
for _, message := range messages {
if len(message.Parts) > 0 {
filtered = append(filtered, message)
}
}
messages = filtered
if limit <= 0 {
limit = 50
}
if limit > 100 {
limit = 100
}
offset := 0
if strings.TrimSpace(cursor) != "" {
if parsed, err := strconv.Atoi(cursor); err == nil && parsed >= 0 {
offset = parsed
}
}
if offset > len(messages) {
offset = len(messages)
}
end := len(messages) - offset
start := end - limit
if start < 0 {
start = 0
}
page := protocol.ChatHistoryPage{Messages: append([]protocol.ChatMessage{}, messages[start:end]...)}
if start > 0 {
page.HasMore = true
page.NextCursor = strconv.Itoa(offset + len(page.Messages))
}
return page, nil
}
func textOrdinal(parts []protocol.ChatPart, kind string) int {
count := 0
for _, part := range parts {
if part.Type == kind {
count++
}
}
return count
}
func applyTranscriptToolResult(messages *[]protocol.ChatMessage, toolIndex map[string][2]int, block contentBlock) {
position, ok := toolIndex[block.ToolUseID]
if !ok || position[0] >= len(*messages) {
return
}
message := &(*messages)[position[0]]
if position[1] >= len(message.Parts) {
return
}
part := &message.Parts[position[1]]
if part.State == nil {
part.State = &protocol.ChatToolState{}
}
text, images := toolResultContent(block.Content)
status := protocol.ChatToolCompleted
var toolErr *protocol.ChatError
exit := exitCode(text)
if block.IsError || (exit != nil && *exit != 0) {
status = protocol.ChatToolError
detail := strings.TrimSpace(text)
if detail == "" {
detail = "the tool returned an error"
}
toolErr = &protocol.ChatError{Type: "tool", Message: boundedText(detail, 2<<10)}
}
part.State.Status = status
part.State.Error = toolErr
if text != "" {
part.State.Content = append(part.State.Content, protocol.ChatToolContent{Type: "text", Text: boundedText(text, 128<<10)})
}
part.State.Content = append(part.State.Content, images...)
}
// Messages serves the authoritative transcript history.
func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
s := c.session(id)
if s == nil {
meta, ok := transcriptSession(id)
if !ok {
return protocol.ChatHistoryPage{}, errors.New("unknown Claude session " + id)
}
s = c.sessionFor(id, meta.Directory)
}
return s.transcriptMessages(limit, cursor)
}
// sessionTranscriptPath is used by tests and diagnostics.
func sessionTranscriptPath(id string) string {
path := findTranscriptFile(id)
if path == "" {
return ""
}
return filepath.Clean(path)
}
+722
View File
@@ -0,0 +1,722 @@
package claude
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// ---- CLI line envelope -----------------------------------------------------
type lineEnvelope struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
ParentToolUseID string `json:"parent_tool_use_id"`
Message json.RawMessage `json:"message"`
Event json.RawMessage `json:"event"`
RequestID string `json:"request_id"`
Request json.RawMessage `json:"request"`
Response json.RawMessage `json:"response"`
Status string `json:"status"`
CompactMetadata json.RawMessage `json:"compactMetadata"`
Result string `json:"result"`
IsError bool `json:"is_error"`
TotalCostUSD float64 `json:"total_cost_usd"`
Usage json.RawMessage `json:"usage"`
}
type contentBlock struct {
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
ToolUseID string `json:"tool_use_id"`
Content json.RawMessage `json:"content"`
IsError bool `json:"is_error"`
Source *struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data string `json:"data"`
} `json:"source"`
}
type messageBody struct {
ID string `json:"id"`
Role string `json:"role"`
Model string `json:"model"`
Content json.RawMessage `json:"content"`
}
type toolRequest struct {
Subtype string `json:"subtype"`
ToolName string `json:"tool_name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Input json.RawMessage `json:"input"`
PermissionSuggestions json.RawMessage `json:"permission_suggestions"`
ToolUseID string `json:"tool_use_id"`
DecisionReason string `json:"decision_reason"`
}
type streamEvent struct {
Type string `json:"type"`
Index int `json:"index"`
Message *messageBody `json:"message"`
ContentBlock *contentBlock `json:"content_block"`
Delta *struct {
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
PartialJSON string `json:"partial_json"`
} `json:"delta"`
}
// ---- Dispatch --------------------------------------------------------------
func (s *session) handleLine(p *process, line []byte) {
var envelope lineEnvelope
if err := json.Unmarshal(line, &envelope); err != nil {
return
}
// Subagent traffic is a sidechain: its text and tools are not the operator's
// main turn, and history excludes the same entries (isSidechain).
if envelope.ParentToolUseID != "" {
return
}
switch envelope.Type {
case "control_request":
s.handleControlRequest(p, envelope)
case "control_response":
s.handleControlResponse(p, envelope)
case "stream_event":
s.handleStreamEvent(envelope)
case "assistant":
s.handleAssistant(envelope)
case "user":
s.handleUser(envelope)
case "result":
s.handleResult(envelope)
case "system":
s.handleSystem(envelope)
}
}
func (s *session) handleControlResponse(p *process, envelope lineEnvelope) {
var reply struct {
Subtype string `json:"subtype"`
RequestID string `json:"request_id"`
Response json.RawMessage `json:"response"`
Error string `json:"error"`
}
if json.Unmarshal(envelope.Response, &reply) != nil || reply.RequestID == "" {
return
}
if p == nil {
return
}
p.mu.Lock()
ch := p.pending[reply.RequestID]
delete(p.pending, reply.RequestID)
p.mu.Unlock()
if ch == nil {
return
}
if reply.Subtype == "error" {
select {
case ch <- controlReply{err: reply.Error}:
default:
}
return
}
select {
case ch <- controlReply{response: reply.Response}:
default:
}
}
func (s *session) handleControlRequest(p *process, envelope lineEnvelope) {
var request toolRequest
if json.Unmarshal(envelope.Request, &request) != nil {
return
}
switch request.Subtype {
case "can_use_tool":
s.receivePermission(p, envelope.RequestID, request)
case "hook_callback", "mcp_message":
s.respondUnsupported(p, envelope.RequestID)
default:
s.respondUnsupported(p, envelope.RequestID)
}
}
func (s *session) respondUnsupported(p *process, requestID string) {
if p == nil || requestID == "" {
return
}
_ = p.write(map[string]any{
"type": "control_response",
"response": map[string]any{
"subtype": "error",
"request_id": requestID,
"error": "This Pipelines server does not support that Claude Code interaction",
},
})
}
// ---- Streaming text --------------------------------------------------------
func (s *session) handleStreamEvent(envelope lineEnvelope) {
var event streamEvent
if json.Unmarshal(envelope.Event, &event) != nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
switch event.Type {
case "message_start":
s.streamID = ""
if event.Message != nil {
s.streamID = event.Message.ID
}
if s.streamID == "" {
s.streamID = envelope.UUID
}
s.streamBlocks = map[int]blockState{}
s.streamText = map[int]string{}
case "content_block_start":
if event.ContentBlock == nil {
return
}
kind := streamKind(event.ContentBlock.Type)
if kind == "" {
return
}
ordinal := s.streamOrdinals[kind]
s.streamOrdinals[kind] = ordinal + 1
s.streamBlocks[event.Index] = blockState{kind: kind, ordinal: ordinal}
case "content_block_delta":
if event.Delta == nil {
return
}
block, ok := s.streamBlocks[event.Index]
kind := block.kind
if !ok {
kind = streamKind(deltaKind(event.Delta.Type))
if kind == "" {
return
}
block = blockState{kind: kind, ordinal: s.streamOrdinals[kind]}
s.streamOrdinals[kind]++
s.streamBlocks[event.Index] = block
}
var delta string
switch event.Delta.Type {
case "text_delta":
if block.kind != protocol.ChatPartText {
return
}
delta = event.Delta.Text
case "thinking_delta":
if block.kind != protocol.ChatPartReasoning {
return
}
delta = event.Delta.Thinking
default:
return
}
if delta == "" {
return
}
s.streamText[event.Index] += delta
messageID := s.streamID
if messageID == "" {
return
}
partID := protocol.ChatDeltaPartID(messageID, block.kind, block.ordinal)
s.broadcastLocked(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: s.turnID,
MessageID: messageID,
Kind: block.kind,
Delta: delta,
Part: &protocol.ChatPart{ID: partID, Type: block.kind},
})
case "message_stop":
// Keep the assembled blocks: the CLI sends the completed assistant
// message after message_stop, and that message must not repeat text
// already delivered as deltas. message_start resets them for the next one.
}
}
func streamKind(blockType string) string {
switch blockType {
case "text":
return protocol.ChatPartText
case "thinking", "reasoning":
return protocol.ChatPartReasoning
default:
return ""
}
}
func deltaKind(deltaType string) string {
switch deltaType {
case "text_delta":
return "text"
case "thinking_delta":
return "thinking"
default:
return ""
}
}
// broadcastLocked emits while the session lock is already held: the caller is a
// stream-delta path that owns state it just updated.
func (s *session) broadcastLocked(frame protocol.ChatEventFrame) {
targets := make([]chan protocol.ChatEventFrame, 0, len(s.subs))
for ch := range s.subs {
targets = append(targets, ch)
}
for _, ch := range targets {
select {
case ch <- frame:
default:
}
}
}
// ---- Completed messages ----------------------------------------------------
func (s *session) handleAssistant(envelope lineEnvelope) {
var body messageBody
if json.Unmarshal(envelope.Message, &body) != nil {
return
}
messageID := strings.TrimSpace(body.ID)
if messageID == "" {
messageID = envelope.UUID
}
if messageID == "" {
return
}
blocks := decodeBlocks(body.Content)
s.mu.Lock()
if body.Model != "" {
s.modelActual = body.Model
}
// Align the completed message with what was streamed, then emit only the
// remainder: the CLI sends deltas first and the full block afterwards.
var frames []protocol.ChatEventFrame
for index, block := range blocks {
switch block.Type {
case "text", "thinking":
kind := protocol.ChatPartText
full := block.Text
if block.Type == "thinking" {
kind = protocol.ChatPartReasoning
full = block.Thinking
}
if strings.TrimSpace(full) == "" {
continue
}
state, ok := s.streamBlocks[index]
if !ok || state.kind != kind {
state = blockState{kind: kind, ordinal: s.streamOrdinals[kind]}
s.streamOrdinals[kind]++
}
streamed := s.streamText[index]
delta := full
if strings.HasPrefix(full, streamed) {
delta = full[len(streamed):]
} else if streamed != "" {
// The stream and the final block disagree; never duplicate the
// whole answer. The authoritative transcript carries the full text.
delta = ""
}
if delta == "" {
continue
}
frames = append(frames, protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: s.turnID,
MessageID: messageID,
Kind: kind,
Delta: delta,
Part: &protocol.ChatPart{ID: protocol.ChatDeltaPartID(messageID, kind, state.ordinal), Type: kind},
})
case "tool_use":
if block.ID == "" {
continue
}
s.toolMessages[block.ID] = messageID
input := truncateJSON(block.Input, 64<<10)
frames = append(frames, protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: s.turnID,
MessageID: messageID,
Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: block.ID,
Name: block.Name,
State: &protocol.ChatToolState{
Status: protocol.ChatToolRunning,
Input: input,
},
},
})
if block.Name == "Bash" {
if shell := s.recordShellLocked(block.ID, bashCommand(input)); shell != nil {
frames = append(frames, protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: shell})
}
}
}
}
s.streamBlocks = map[int]blockState{}
s.streamText = map[int]string{}
s.streamOrdinals = map[string]int{}
framesCopy := frames
s.mu.Unlock()
for _, frame := range framesCopy {
s.emit(frame)
}
}
func (s *session) handleUser(envelope lineEnvelope) {
var body messageBody
if json.Unmarshal(envelope.Message, &body) != nil {
return
}
blocks := decodeBlocks(body.Content)
for _, block := range blocks {
if block.Type != "tool_result" || block.ToolUseID == "" {
continue
}
text, images := toolResultContent(block.Content)
status := protocol.ChatToolCompleted
var toolErr *protocol.ChatError
exit := exitCode(text)
if block.IsError || (exit != nil && *exit != 0) {
status = protocol.ChatToolError
message := "the tool returned an error"
if exit != nil && *exit != 0 {
message = fmt.Sprintf("Exit code %d", *exit)
}
if strings.TrimSpace(text) != "" {
message = boundedText(strings.TrimSpace(text), 2<<10)
}
toolErr = &protocol.ChatError{Type: "tool", Message: message}
}
content := []protocol.ChatToolContent{}
if text != "" {
content = append(content, protocol.ChatToolContent{Type: "text", Text: boundedText(text, 128<<10)})
}
content = append(content, images...)
s.mu.Lock()
messageID := s.toolMessages[block.ToolUseID]
shell := s.shells[block.ToolUseID]
s.mu.Unlock()
part := protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: block.ToolUseID,
State: &protocol.ChatToolState{
Status: status,
Content: content,
Error: toolErr,
},
}
s.emit(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: s.turnID,
MessageID: messageID,
Kind: protocol.ChatEventTool,
Part: &part,
})
if shell != nil {
var frame *protocol.ChatShell
s.mu.Lock()
if snapshot, ok := s.shells[block.ToolUseID]; ok {
snapshot.shell.Status = protocol.ChatShellExited
snapshot.shell.Exit = exit
if text != "" && len(text) >= len(snapshot.output) {
snapshot.output = text
snapshot.size = int64(len(text))
if len(snapshot.output) > commandOutputCap {
snapshot.output = snapshot.output[:commandOutputCap]
}
}
frame = &protocol.ChatShell{ID: snapshot.shell.ID, Status: snapshot.shell.Status, Command: snapshot.shell.Command, Exit: snapshot.shell.Exit}
}
s.mu.Unlock()
if frame != nil {
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: frame})
}
}
}
}
func (s *session) handleResult(envelope lineEnvelope) {
s.mu.Lock()
turn := s.turnID
running := s.running
proc := s.proc
s.running = false
s.turnID = ""
s.approvals = map[string]*pendingApproval{}
s.forms = map[string]*pendingForm{}
s.streamBlocks = map[int]blockState{}
s.streamText = map[int]string{}
s.streamOrdinals = map[string]int{}
s.mu.Unlock()
if envelope.Subtype != "success" && envelope.Subtype != "error_during_execution" && envelope.Subtype != "" {
message := strings.TrimSpace(envelope.Result)
if message == "" {
message = "Claude Code ended the turn: " + envelope.Subtype
}
s.emit(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: turn,
MessageID: "claude-result-" + turn,
Kind: protocol.ChatEventTool,
Part: &protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: "claude-result-" + turn,
Name: "Claude Code",
State: &protocol.ChatToolState{Status: protocol.ChatToolError, Error: &protocol.ChatError{Type: envelope.Subtype, Message: boundedText(message, 2<<10)}},
},
})
}
if running {
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: turn}})
}
if proc != nil {
go s.refreshUsage(proc)
}
}
func (s *session) handleSystem(envelope lineEnvelope) {
switch envelope.Subtype {
case "status":
if envelope.Status == "compacting" {
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: s.currentTurn(), Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running"}})
}
case "compact_boundary":
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: s.currentTurn(), Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "completed"}})
case "init":
// The CLI re-emits init at each turn; keep only the authoritative identity.
if envelope.SessionID != "" && envelope.SessionID != s.id {
s.mu.Lock()
s.lastErr = "Claude Code opened unexpected session " + envelope.SessionID
s.mu.Unlock()
}
}
}
func (s *session) currentTurn() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.turnID
}
// ---- Tool helpers ----------------------------------------------------------
func decodeBlocks(raw json.RawMessage) []contentBlock {
if len(raw) == 0 {
return nil
}
var blocks []contentBlock
if json.Unmarshal(raw, &blocks) == nil {
return blocks
}
var text string
if json.Unmarshal(raw, &text) == nil && text != "" {
return []contentBlock{{Type: "text", Text: text}}
}
return nil
}
func toolResultContent(raw json.RawMessage) (string, []protocol.ChatToolContent) {
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
blocks := decodeBlocks(raw)
var builder strings.Builder
images := []protocol.ChatToolContent{}
for _, block := range blocks {
switch block.Type {
case "text":
if builder.Len() > 0 {
builder.WriteString("\n")
}
builder.WriteString(block.Text)
case "image":
if block.Source != nil && block.Source.Data != "" && len(block.Source.Data) <= 512<<10 {
images = append(images, protocol.ChatToolContent{
Type: "file",
Mime: block.Source.MediaType,
Name: "image",
URI: "data:" + block.Source.MediaType + ";base64," + block.Source.Data,
})
}
}
}
return builder.String(), images
}
var exitLine = regexp.MustCompile(`(?m)^Exit code (\d+)\s*$`)
// exitCode reads the CLI's own "Exit code N" prefix. A successful command with
// no prefix is 0; an error without a numeric code stays unknown.
func exitCode(text string) *int {
if match := exitLine.FindStringSubmatch(text); len(match) == 2 {
if value, err := strconv.Atoi(match[1]); err == nil {
return &value
}
}
if strings.TrimSpace(text) != "" && !strings.HasPrefix(strings.TrimSpace(text), "Exit code") {
zero := 0
return &zero
}
return nil
}
func bashCommand(input json.RawMessage) string {
var parsed struct {
Command string `json:"command"`
}
if json.Unmarshal(input, &parsed) == nil {
return parsed.Command
}
return ""
}
func truncateJSON(raw json.RawMessage, limit int) json.RawMessage {
if len(raw) == 0 {
return json.RawMessage(`{}`)
}
if len(raw) > limit {
wrapped, _ := json.Marshal(map[string]any{"truncated": true, "preview": string(raw[:limit])})
return wrapped
}
return raw
}
func boundedText(text string, limit int) string {
if len(text) <= limit {
return text
}
return text[:limit] + "\n… (truncated)"
}
// ---- Shells ----------------------------------------------------------------
const commandOutputCap = 128 << 10
type shellSnapshot struct {
shell protocol.ChatShell
output string
size int64
order uint64
}
func shellID(toolID string) string {
sum := sha256.Sum256([]byte("claude\x00" + toolID))
return "sh_claude_" + hex.EncodeToString(sum[:16])
}
// recordShellLocked retains a running Bash command. Called with s.mu held; the
// caller emits the returned frame after the tool part, in that order.
func (s *session) recordShellLocked(toolID, command string) *protocol.ChatShell {
if toolID == "" {
return nil
}
id := shellID(toolID)
s.shellOrder = append(s.shellOrder, id)
shell := protocol.ChatShell{ID: id, Status: protocol.ChatShellRunning, Command: command}
s.shells[toolID] = &shellSnapshot{shell: shell, order: uint64(len(s.shellOrder))}
return &shell
}
// ---- Usage -----------------------------------------------------------------
type usageModel struct {
InputTokens int64 `json:"inputTokens"`
OutputTokens int64 `json:"outputTokens"`
CacheReadInputTokens int64 `json:"cacheReadInputTokens"`
CacheCreationInputTokens int64 `json:"cacheCreationInputTokens"`
CostUSD float64 `json:"costUSD"`
ContextWindow int64 `json:"contextWindow"`
}
type sessionUsage struct {
Session struct {
TotalCostUSD float64 `json:"total_cost_usd"`
ModelUsage map[string]usageModel `json:"model_usage"`
} `json:"session"`
}
type contextUsage struct {
TotalTokens int64 `json:"totalTokens"`
MaxTokens int64 `json:"maxTokens"`
}
// refreshUsage asks the CLI for its own cumulative session totals. It runs off
// the reader goroutine because a control request waits for a response that only
// the reader can deliver.
func (s *session) refreshUsage(p *process) {
ctx, cancel := contextWithTimeout(controlRequestTimeout)
defer cancel()
raw, err := p.request(ctx, "get_usage", map[string]any{"skip_behaviors": true})
if err != nil {
return
}
var totals sessionUsage
if json.Unmarshal(raw, &totals) != nil {
return
}
var input, output, cacheRead, cacheCreate int64
for _, model := range totals.Session.ModelUsage {
input += model.InputTokens
output += model.OutputTokens
cacheRead += model.CacheReadInputTokens
cacheCreate += model.CacheCreationInputTokens
}
total := input + output + cacheRead + cacheCreate
cost := totals.Session.TotalCostUSD
usage := &protocol.ChatUsage{
Scope: "session",
InputTokens: int(input),
OutputTokens: int(output),
TotalTokens: &total,
CostUSD: &cost,
}
ctx2, cancel2 := contextWithTimeout(controlRequestTimeout)
defer cancel2()
if rawContext, err := p.request(ctx2, "get_context_usage", map[string]any{}); err == nil {
var context contextUsage
if json.Unmarshal(rawContext, &context) == nil {
if context.MaxTokens > 0 {
usage.ContextWindow = &context.MaxTokens
usage.ContextTokens = &context.TotalTokens
}
}
}
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventUsage, Usage: usage})
}
func contextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), timeout)
}
+1 -1
View File
@@ -64,7 +64,7 @@ var notes = map[string]string{
var serviceHelp = map[string]string{
"harness": "pipelines harness launches the configured default. harness setup opencode|pi offers fuzzy model selection; --host configures a native host harness and clears any Docker link, --login reopens login, --default chooses the default harness, --model and --pipeline-model set separate defaults explicitly. harness list prints non-secret settings, including each profile's launch mode. Only configured harnesses are offered.",
"skill": "pipelines skill install installs/updates the bundled global OpenCode skill without changing login/config or user-modified skills. ./install includes this step.",
"skill": "pipelines skill install installs/updates the bundled workflow skill in OpenCode and detected Claude Code skill roots without changing login/config or user-modified skills. ./install includes this step.",
"service": "Configure per-user OS autostart: pipelines service enable. Runs use the directory you invoke pipelines run from. Use --print to preview, service status to inspect, and service disable before uninstalling. Linux uses systemd; macOS uses launchd. No sudo.",
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
+1 -1
View File
@@ -52,7 +52,7 @@ SERVER / INTERFACE
serve Start native server in the foreground (Ctrl+C stops it)
service enable Configure user autostart
service disable | status Stop/remove autostart, or inspect OS service status
skill install Install/update the shared Pi/OpenCode workflow skill
skill install Install/update the shared OpenCode and Claude Code workflow skill
uninstall [--yes] Remove verified Go binaries; retain data and drafts
Legacy managed installs: select PIPELINES_PREFIX explicitly for start/stop,
+1 -1
View File
@@ -78,7 +78,7 @@ func (d serviceDefinition) render(platform string) (string, error) {
// Only explicitly supported settings are captured, never the complete environment
// or provider credentials. File-based notification credentials remain references.
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL"}
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_CLAUDE"}
func envValues(env map[string]string) []string {
var values []string
+1 -1
View File
@@ -41,7 +41,7 @@ func TestSystemdDefinitionAcceptedByNativeValidator(t *testing.T) {
}
func TestServiceDefinitionsQuotePathsAndKeepEnvironmentLimited(t *testing.T) {
d := serviceDefinition{Binary: `/some bin/server`, Directory: `/repo "quoted" 100% $USER`, Args: []string{"-db", `/repo "quoted" 100% $USER/data.db`}, Environment: map[string]string{"PATH": "/usr/bin:/custom bin", "PIPELINES_NTFY_TOKEN_FILE": "/secret & token", "PROVIDER_SECRET": "must-not-export"}}
d := serviceDefinition{Binary: `/some bin/server`, Directory: `/repo "quoted" 100% $USER`, Args: []string{"-db", `/repo "quoted" 100% $USER/data.db`}, Environment: map[string]string{"PATH": "/usr/bin:/custom bin", "PIPELINES_NTFY_TOKEN_FILE": "/secret & token", "PIPELINES_CLAUDE": "/custom bin/claude", "PROVIDER_SECRET": "must-not-export"}}
for _, platform := range []string{"linux", "darwin"} {
text, err := d.render(platform)
if err != nil {
+4 -4
View File
@@ -164,12 +164,12 @@ func (s *Store) migrateOperatorSessions() error {
}
// SetChatModelSelection saves a Pipelines next-turn override, not a remote
// Codex settings acknowledgement. Only registered Codex operator chats qualify.
// harness acknowledgement. Only registered Codex/Claude operator chats qualify.
func (s *Store) SetChatModelSelection(ctx context.Context, id, provider, model string) error {
if provider == "" || model == "" {
return errors.New("a model and provider are required")
}
result, err := s.db.ExecContext(ctx, `UPDATE operator_sessions SET chat_model=?,chat_model_provider=? WHERE session_id=? AND backend='codex' AND tag<>''`, model, provider, id)
result, err := s.db.ExecContext(ctx, `UPDATE operator_sessions SET chat_model=?,chat_model_provider=? WHERE session_id=? AND backend IN ('codex','claude') AND tag<>''`, model, provider, id)
if err != nil {
return err
}
@@ -178,14 +178,14 @@ func (s *Store) SetChatModelSelection(ctx context.Context, id, provider, model s
return err
}
if count != 1 {
return errors.New("model selection requires a registered Codex operator chat")
return errors.New("model selection requires a registered Codex or Claude operator chat")
}
return nil
}
// ChatModelSelection reads a durable next-turn choice without touching recency.
func (s *Store) ChatModelSelection(ctx context.Context, id string) (provider, model string, err error) {
err = s.db.QueryRowContext(ctx, `SELECT chat_model_provider,chat_model FROM operator_sessions WHERE session_id=? AND backend='codex' AND tag<>''`, id).Scan(&provider, &model)
err = s.db.QueryRowContext(ctx, `SELECT chat_model_provider,chat_model FROM operator_sessions WHERE session_id=? AND backend IN ('codex','claude') AND tag<>''`, id).Scan(&provider, &model)
if errors.Is(err, sql.ErrNoRows) {
return "", "", nil
}
+6 -1
View File
@@ -1,8 +1,10 @@
package server
import (
"context"
"testing"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/codex"
"git.a-wan.net/alan/pipelines/internal/opencode"
)
@@ -20,9 +22,12 @@ type interactiveWebChat interface {
var _ interactiveWebChat = (*opencode.Chat)(nil)
var _ interactiveWebChat = (*codex.Chat)(nil)
var _ interactiveWebChat = (*claude.Chat)(nil)
func TestAdvertisedChatHarnessesExposeInteractiveWebContract(t *testing.T) {
m := &chatManager{opencode: opencode.NewChat(&opencode.Connection{}), codex: &codex.Chat{}}
claudeChat := claude.New(context.Background())
defer claudeChat.Close()
m := &chatManager{opencode: opencode.NewChat(&opencode.Connection{}), codex: &codex.Chat{}, claude: claudeChat}
for _, backend := range m.Backends() {
if _, ok := m.adapter(backend).(interactiveWebChat); !ok {
t.Errorf("advertised harness %s lacks web tool controls", backend)
+31 -12
View File
@@ -6,6 +6,7 @@ import (
"sort"
"sync"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/codex"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/protocol"
@@ -18,6 +19,7 @@ import (
type chatManager struct {
opencode chatBroker
codex chatBroker
claude chatBroker
registry operatorRegistry
mu sync.Mutex
@@ -32,6 +34,9 @@ func NewChatManager(ctx context.Context, open chatBroker, registry operatorRegis
m.codex = client
}
}
if claude.Available() {
m.claude = claude.New(ctx)
}
return m
}
@@ -40,6 +45,9 @@ func (m *chatManager) Close() {
if closer, ok := m.codex.(interface{ Close() }); ok {
closer.Close()
}
if closer, ok := m.claude.(interface{ Close() }); ok {
closer.Close()
}
}
// Backends lists the harnesses available for a new session.
@@ -51,6 +59,9 @@ func (m *chatManager) Backends() []string {
if m.codex != nil {
backends = append(backends, codex.Backend)
}
if m.claude != nil {
backends = append(backends, claude.Backend)
}
sort.Strings(backends)
return backends
}
@@ -61,6 +72,8 @@ func (m *chatManager) adapter(backend string) chatBroker {
return m.opencode
case codex.Backend:
return m.codex
case claude.Backend:
return m.claude
default:
return nil
}
@@ -127,8 +140,8 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
if err != nil {
return err
}
if m.backendFor(ctx, sessionID) == codex.Backend {
model, err := m.codexPromptModel(ctx, adapter, sessionID)
if isModelBackend(m.backendFor(ctx, sessionID)) {
model, err := m.promptModel(ctx, adapter, sessionID)
if err != nil {
return err
}
@@ -137,7 +150,7 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
PromptWithMessageIDModel(context.Context, string, string, string, string) error
})
if !ok {
return errors.New("this Codex adapter cannot apply the saved next-turn model")
return errors.New("this chat adapter cannot apply the saved next-turn model")
}
return withModel.PromptWithMessageIDModel(ctx, sessionID, text, messageID, model)
}
@@ -148,7 +161,13 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
return adapter.Prompt(ctx, sessionID, text)
}
func (m *chatManager) codexPromptModel(ctx context.Context, adapter chatBroker, sessionID string) (string, error) {
// isModelBackend reports a harness whose model choice is stored by Pipelines
// and applied at the next turn (Codex and Claude Code).
func isModelBackend(backend string) bool {
return backend == codex.Backend || backend == claude.Backend
}
func (m *chatManager) promptModel(ctx context.Context, adapter chatBroker, sessionID string) (string, error) {
provider, model, err := m.chatModelSelection(ctx, sessionID)
if err != nil || model == "" {
return model, err
@@ -158,7 +177,7 @@ func (m *chatManager) codexPromptModel(ctx context.Context, adapter chatBroker,
return "", err
}
if !found || session.ModelProvider != provider {
return "", errors.New("saved model provider no longer matches the Codex thread; select a model again")
return "", errors.New("saved model provider no longer matches the chat harness; select a model again")
}
return model, nil
}
@@ -173,8 +192,8 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t
if err != nil {
return err
}
if m.backendFor(ctx, sessionID) == codex.Backend {
model, err := m.codexPromptModel(ctx, adapter, sessionID)
if isModelBackend(m.backendFor(ctx, sessionID)) {
model, err := m.promptModel(ctx, adapter, sessionID)
if err != nil {
return err
}
@@ -183,7 +202,7 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t
PromptWithMessageIDModelFiles(context.Context, string, string, string, string, []opencode.PromptFile) error
})
if !ok {
return errors.New("this Codex adapter cannot apply the saved next-turn model with attachments")
return errors.New("this chat adapter cannot apply the saved next-turn model with attachments")
}
return withModelFiles.PromptWithMessageIDModelFiles(ctx, sessionID, text, messageID, model, files)
}
@@ -258,7 +277,7 @@ func (m *chatManager) SwitchModel(ctx context.Context, sessionID, provider, mode
if !ok {
return errors.New("this chat harness does not support changing models")
}
if m.backendFor(ctx, sessionID) == codex.Backend {
if isModelBackend(m.backendFor(ctx, sessionID)) {
registry, ok := m.registry.(chatModelSelectionRegistry)
if !ok {
return errors.New("durable chat model selection is not configured")
@@ -277,7 +296,7 @@ type chatModelSelectionRegistry interface {
}
func (m *chatManager) ModelSelectionMode(ctx context.Context, id string) string {
if m.backendFor(ctx, id) == codex.Backend {
if isModelBackend(m.backendFor(ctx, id)) {
return "next_turn"
}
return ""
@@ -291,7 +310,7 @@ func (m *chatManager) chatModelSelection(ctx context.Context, id string) (string
}
func (m *chatManager) withModelSelection(ctx context.Context, session protocol.ChatSession) (protocol.ChatSession, error) {
if session.Backend != codex.Backend {
if !isModelBackend(session.Backend) {
return session, nil
}
provider, model, err := m.chatModelSelection(ctx, session.ID)
@@ -332,7 +351,7 @@ func (m *chatManager) Messages(ctx context.Context, sessionID string, limit int,
func (m *chatManager) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
sessions := []protocol.ChatSession{}
seen := map[string]bool{}
for _, adapter := range []chatBroker{m.opencode, m.codex} {
for _, adapter := range []chatBroker{m.opencode, m.codex, m.claude} {
if adapter == nil {
continue
}
+2 -1
View File
@@ -637,7 +637,8 @@ fills its scroll pane at 1100px. Captures: `wrapped-run-title-390.png`,
| B21 | Change a chat's model | `chat_models`, `chat_model` | done — the open conversation shows its current model under the title. Clicking it lists the OpenCode endpoint's enabled, non-deprecated models with provider/name, scrolls the current selection into view, and switches through `POST /api/session/{id}/model`; the row and header update immediately and the next turn uses it. The list is read-only until a model is chosen, and a failed switch leaves the dialog open with the server's reason. Verified live: 48 models listed and an ephemeral session switched to `opencode-go/beam-free`. |
| B22 | Agent badge on chat rows | — | done — every chat row shows the harness mark at its right edge (OpenCode terminal, Codex hex, Claude starburst, Pi), with the harness name as tooltip/aria-label. OpenCode is the default for legacy rows; Codex rows carry their backend from the adapter. The model switcher is hidden for harnesses that do not support it. |
| B23 | Preload a new chat's behavior | `chat_create.instructions` | done — the New chat pane now has an editable **How should it act?** brief, prefilled with a project-agnostic care/verification brief. `chat_create` carries it as `instructions`; OpenCode stores it as the durable `pipelines.behavior` session instruction entry before the first turn, so the agent starts with the brief. Other harnesses and older OpenCode builds still create the chat if the instruction surface is unavailable. Verified live with an ephemeral create: the instruction entry was present immediately after creation. |
| B13 | Codex chat backend | `chat_backends`, `chat_create.backend` | done — OpenCode stays the default. `chat_backends` lists `codex` when the Codex App Server control socket is present; New chat shows a harness choice, the selected backend is stored on the operator-session row and echoed on every session. The Codex adapter connects to the existing App Server over its Unix WebSocket, maps `thread/start`, `turn/start`, `thread/read`, item/tool events, `item/tool/requestUserInput` to the existing question card, and carries the native user-message id so optimistic and history turns reconcile. Verified live: created a Codex chat from the browser, sent a prompt, saw the streamed answer, read it back through `chat_messages`, and saw the Codex chip and title in the list. Claude is not advertised yet: its OAuth session is expired and the SDK/CLI sidecar is still to be built. |
| B13 | Codex chat backend | `chat_backends`, `chat_create.backend` | done — OpenCode stays the default. `chat_backends` lists `codex` when the Codex App Server control socket is present; New chat shows a harness choice, the selected backend is stored on the operator-session row and echoed on every session. The Codex adapter connects to the existing App Server over its Unix WebSocket, maps `thread/start`, `turn/start`, `thread/read`, item/tool events, `item/tool/requestUserInput` to the existing question card, and carries the native user-message id so optimistic and history turns reconcile. Verified live: created a Codex chat from the browser, sent a prompt, saw the streamed answer, read it back through `chat_messages`, and saw the Codex chip and title in the list. |
| B24 | Claude Code chat backend | `chat_backends`, `chat_create.backend` | done — `chat_backends` lists `claude` when the `claude` CLI is installed (`PIPELINES_CLAUDE` overrides the path). The adapter owns one CLI process per session with stream-json input/output, performs the initialize handshake, resumes the same session after an idle release/restart, and uses the operator's existing login without changing Claude settings. Text/reasoning stream with duplicate suppression; tool cards, Bash command rows, `can_use_tool` approvals (once/always/reject with the CLI's own suggestions), `AskUserQuestion` forms, interrupts, live model switching and reported session usage/context all use the existing surfaces. History comes from Claude Code's own JSONL session file, merged by message id with tool results attached, sidechains excluded and bounded paging. Verified against a scratch server and the real signed-in CLI: advertised backend, Haiku model switch, streamed turn, real Write approval and file creation, follow-up turn on the same process, transcript readback and reported usage. The web/Flutter model pickers include Claude; native OS-specific checks remain outside this row. |
| B12 | One detail header, optimistic sends, thinking above the bubble | — | done — every non-chat detail (pipeline, run, template) now extracts its own `#detailTitle` into a shared `.detail-head` with the same 44px chevron Back control; on phones the button and title are vertically centred, and on wide screens the back control is hidden while the title stays in the header. Chat/create already use the same control. Sending now appends the operator's optimistic user turn immediately (using the native message id OpenCode persists), so the running placeholder cannot appear before their message. While a turn runs, Send stays present beside Stop; a follow-up is queued. The reasoning/thinking block moved outside and above the answer bubble, like the tool summary below it. |
| B11 | Enter composes; live shell bars stay in place | — | done — Enter now inserts a newline (a real CDP Enter produced `first\n` and no prompt), while Ctrl/Cmd+Enter sends; a slash draft still runs its command on Enter. The chat star reserves a 26px corner in the row head, so it no longer covers Streaming/New/Idle. Background-shell frames patch the tasks bar in place instead of full-rendering the pane, keeping the composer mounted. The shell cache was bumped to v2 so an installed PWA picks up these client changes. |
| B10 | Chat titles are shared across devices | `chat_rename` | done — the rename dialog writes the title to the server's operator-session registry (`SetOperatorSessionTitle`) instead of a device-local override. `chat_sessions` already prefers that title, so a second browser opened with a fresh profile showed `Shared rename probe` without any local storage; restoring it to `New chat` did the same. Old local titles are uploaded once on the next list load and then removed. The helper now reads `This name is shared with every device.` |
+8 -4
View File
@@ -1,6 +1,6 @@
/** Harnesses with a verified catalog and model-selection path. */
export function supportsChatModels(backend) {
return ["", "opencode", "codex"].includes(String(backend ?? "").trim());
return ["", "opencode", "codex", "claude"].includes(String(backend ?? "").trim());
}
/** Never turn an unknown remote model into an invented model name. */
@@ -10,7 +10,11 @@ export function chatModelLabel(session) {
}
export function chatModelSelectionNote(backend) {
return backend === "codex"
? "Saved by Pipelines for the next turn you send. Does not resume this thread or edit global Codex configuration."
: "Applies to the next turn in this chat.";
if (backend === "codex") {
return "Saved by Pipelines for the next turn you send. Does not resume this thread or edit global Codex configuration.";
}
if (backend === "claude") {
return "Saved by Pipelines for the next turn you send. Does not edit your global Claude Code configuration.";
}
return "Applies to the next turn in this chat.";
}
+4 -3
View File
@@ -3,9 +3,9 @@ import assert from "node:assert/strict";
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../src/chatModels.js";
import { PipelinesRepository } from "../src/repository.js";
test("Codex and OpenCode expose model selection, unverified backends do not", () => {
for (const backend of [undefined, "", "opencode", "codex"]) assert.equal(supportsChatModels(backend), true);
for (const backend of ["claude", "unknown"]) assert.equal(supportsChatModels(backend), false);
test("OpenCode, Codex and Claude expose model selection, unknown backends do not", () => {
for (const backend of [undefined, "", "opencode", "codex", "claude"]) assert.equal(supportsChatModels(backend), true);
for (const backend of ["unknown"]) assert.equal(supportsChatModels(backend), false);
});
test("model control distinguishes saved next-turn choice from remote current model", () => {
@@ -14,6 +14,7 @@ test("model control distinguishes saved next-turn choice from remote current mod
assert.equal(chatModelLabel({ model: null }), "Model");
assert.match(chatModelSelectionNote("codex"), /Saved by Pipelines for the next turn/);
assert.match(chatModelSelectionNote("codex"), /Does not resume/);
assert.match(chatModelSelectionNote("claude"), /Does not edit your global Claude Code configuration/);
});
test("model switch reply preserves local next-turn acknowledgement", async () => {