chore: remove dead non-ACP provider client packages (#1083)

* chore: remove dead non-ACP provider client packages

Delete five Go packages under apps/backend/pkg/ that were unreachable
from any binary: amp, codex, claudecode, copilot, opencode. These were
the client libraries for legacy non-ACP agent implementations removed in
a5b54b53 — that commit deleted the callers but missed the client libraries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: drop orphaned copilot-sdk dep and stale architecture doc

go mod tidy removes github.com/github/copilot-sdk/go v0.1.18 and its
transitive dep github.com/google/jsonschema-go v0.4.2; both were only
imported by the deleted pkg/copilot/client.go.

Delete docs/agents/claude_code.md: it describes the pre-ACP streamjson
transport and pkg/claudecode/ package. Every source file it references
has been removed (pkg/claudecode/ in this PR; streamjson/ and
agents/claude_code.go in a5b54b53).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-05-26 15:31:14 +01:00
committed by GitHub
parent dcfec0d23c
commit 2cb3f4a384
15 changed files with 0 additions and 5941 deletions
-2
View File
@@ -10,7 +10,6 @@ require (
github.com/docker/go-connections v0.6.0
github.com/fsnotify/fsnotify v1.6.0
github.com/gin-gonic/gin v1.9.1
github.com/github/copilot-sdk/go v0.1.18
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/jackc/pgx/v5 v5.9.0
@@ -61,7 +60,6 @@ require (
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/invopop/jsonschema v0.13.0 // indirect
-4
View File
@@ -109,8 +109,6 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/github/copilot-sdk/go v0.1.18 h1:S1ocOfTKxiNGtj+/qp4z+RZeOr9hniqy3UqIIYZxsuQ=
github.com/github/copilot-sdk/go v0.1.18/go.mod h1:0SYT+64k347IDT0Trn4JHVFlUhPtGSE6ab479tU/+tY=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@@ -172,8 +170,6 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
-306
View File
@@ -1,306 +0,0 @@
// Package amp provides a client wrapper for the Sourcegraph Amp CLI.
// This package handles communication with the Amp CLI via stream-json protocol.
package amp
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"sync"
"github.com/kandev/kandev/internal/common/logger"
"go.uber.org/zap"
)
// Message types for Amp stream-json protocol.
// Amp claims Claude Code compatibility via --stream-json, so these match Claude Code's types.
const (
MessageTypeSystem = "system"
MessageTypeAssistant = "assistant"
MessageTypeResult = "result"
MessageTypeUser = "user"
MessageTypeRateLimit = "rate_limit_event"
)
// Content block types.
const (
ContentTypeText = "text"
ContentTypeThinking = "thinking"
ContentTypeToolUse = "tool_use"
ContentTypeToolResult = "tool_result"
)
// Client wraps communication with Amp CLI via stdin/stdout.
type Client struct {
stdin io.Writer
stdout io.Reader
logger *logger.Logger
scanner *bufio.Scanner
// Message handler
messageHandler func(*Message)
handlerMu sync.RWMutex
// Context for lifecycle
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
// State
threadID string
mu sync.RWMutex
}
// Message represents a message from Amp.
// Amp uses Claude Code-compatible stream-json format, so fields match both protocols.
type Message struct {
Type string `json:"type"`
ThreadID string `json:"thread_id,omitempty"`
Message *Content `json:"message,omitempty"`
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
// Result fields (when Type == "result")
IsError bool `json:"is_error,omitempty"`
Error string `json:"error,omitempty"` // Single error message
Errors []string `json:"errors,omitempty"` // Multiple errors (Claude Code format)
Subtype string `json:"subtype,omitempty"` // e.g., "error_during_execution"
CostUSD float64 `json:"cost_usd,omitempty"`
TotalCostUSD float64 `json:"total_cost_usd,omitempty"` // Claude Code uses this field name
DurationMS int64 `json:"duration_ms,omitempty"`
NumTurns int `json:"num_turns,omitempty"`
TotalInputTokens int64 `json:"total_input_tokens,omitempty"`
TotalOutputTokens int64 `json:"total_output_tokens,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
ModelUsage map[string]*Usage `json:"model_usage,omitempty"`
// Rate limit fields (when Type == "rate_limit_event")
RateLimitInfo json.RawMessage `json:"rate_limit_info,omitempty"`
}
// GetCostUSD returns the cost, checking both total_cost_usd (Claude Code format)
// and cost_usd (Amp format).
func (m *Message) GetCostUSD() float64 {
if m.TotalCostUSD != 0 {
return m.TotalCostUSD
}
return m.CostUSD
}
// Content represents the message content.
type Content struct {
Model string `json:"model,omitempty"`
Content []ContentBlock `json:"content,omitempty"`
Usage *TokenUsage `json:"usage,omitempty"`
StopReason string `json:"stop_reason,omitempty"`
StopSequence string `json:"stop_sequence,omitempty"`
}
// ContentBlock represents a content block (text, tool_use, etc.).
type ContentBlock struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Thinking string `json:"thinking,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Input map[string]any `json:"input,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
Content any `json:"content,omitempty"`
IsError bool `json:"is_error,omitempty"`
}
// TokenUsage represents token usage information.
type TokenUsage struct {
InputTokens int64 `json:"input_tokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty"`
CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,omitempty"`
CacheReadInputTokens int64 `json:"cache_read_input_tokens,omitempty"`
}
// Usage represents model-specific usage stats.
type Usage struct {
InputTokens int64 `json:"input_tokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty"`
ContextWindow *int64 `json:"context_window,omitempty"`
}
// ResultData represents the result data structure.
type ResultData struct {
SessionID string `json:"session_id,omitempty"`
ThreadID string `json:"thread_id,omitempty"`
Text string `json:"text,omitempty"`
}
// UserMessage represents a user message to send (Claude Code-compatible format).
type UserMessage struct {
Type string `json:"type"` // "user"
Message UserMessageBody `json:"message"`
}
// UserMessageBody is the nested message body for user messages.
type UserMessageBody struct {
Role string `json:"role"` // "user"
Content []UserContentBlock `json:"content"`
}
// UserContentBlock represents a content block in user messages.
type UserContentBlock struct {
Type string `json:"type"` // "text"
Text string `json:"text"`
}
// NewClient creates a new Amp client.
func NewClient(stdin io.Writer, stdout io.Reader, log *logger.Logger) *Client {
ctx, cancel := context.WithCancel(context.Background())
return &Client{
stdin: stdin,
stdout: stdout,
logger: log.WithFields(zap.String("component", "amp-client")),
ctx: ctx,
cancel: cancel,
}
}
// SetMessageHandler sets the handler for incoming messages.
func (c *Client) SetMessageHandler(handler func(*Message)) {
c.handlerMu.Lock()
defer c.handlerMu.Unlock()
c.messageHandler = handler
}
// Start begins reading from stdout and dispatching messages.
func (c *Client) Start(ctx context.Context) {
c.scanner = bufio.NewScanner(c.stdout)
// Allow larger buffer for JSON messages
c.scanner.Buffer(make([]byte, 64*1024), 1024*1024)
c.wg.Add(1)
go c.readLoop(ctx)
}
// Stop stops the client and waits for goroutines to finish.
func (c *Client) Stop() {
c.cancel()
c.wg.Wait()
}
// readLoop reads JSON lines from stdout and dispatches them.
func (c *Client) readLoop(ctx context.Context) {
defer c.wg.Done()
for {
select {
case <-ctx.Done():
return
case <-c.ctx.Done():
return
default:
}
if !c.scanner.Scan() {
if err := c.scanner.Err(); err != nil {
c.logger.Error("scanner error", zap.Error(err))
}
return
}
line := c.scanner.Text()
if line == "" {
continue
}
c.handleLine(line)
}
}
// handleLine parses and dispatches a JSON line.
func (c *Client) handleLine(line string) {
var msg Message
if err := json.Unmarshal([]byte(line), &msg); err != nil {
c.logger.Debug("failed to parse message", zap.Error(err), zap.String("line", line))
return
}
// Update thread ID if provided
if msg.ThreadID != "" {
c.mu.Lock()
c.threadID = msg.ThreadID
c.mu.Unlock()
}
c.handlerMu.RLock()
handler := c.messageHandler
c.handlerMu.RUnlock()
if handler != nil {
handler(&msg)
}
}
// SendUserMessage sends a user message to Amp.
func (c *Client) SendUserMessage(message string) error {
msg := &UserMessage{
Type: "user",
Message: UserMessageBody{
Role: "user",
Content: []UserContentBlock{
{Type: "text", Text: message},
},
},
}
data, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("failed to marshal message: %w", err)
}
if _, err := c.stdin.Write(append(data, '\n')); err != nil {
return fmt.Errorf("failed to write message: %w", err)
}
return nil
}
// GetThreadID returns the current thread ID.
func (c *Client) GetThreadID() string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.threadID
}
// SetThreadID sets the current thread ID.
func (c *Client) SetThreadID(threadID string) {
c.mu.Lock()
defer c.mu.Unlock()
c.threadID = threadID
}
// GetResultData extracts ResultData from a result message.
func (m *Message) GetResultData() *ResultData {
if len(m.Result) == 0 {
return nil
}
var data ResultData
if err := json.Unmarshal(m.Result, &data); err != nil {
return nil
}
return &data
}
// GetResultString extracts a string result (for error messages).
func (m *Message) GetResultString() string {
if len(m.Result) == 0 {
return ""
}
var s string
if err := json.Unmarshal(m.Result, &s); err != nil {
return ""
}
return s
}
-353
View File
@@ -1,353 +0,0 @@
package claudecode
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"sync"
"time"
"github.com/google/uuid"
"github.com/kandev/kandev/internal/common/logger"
"go.uber.org/zap"
)
// RequestHandler handles incoming control requests from Claude Code CLI.
// It receives the request ID and control request, and should call SendControlResponse.
type RequestHandler func(requestID string, req *ControlRequest)
// CancelHandler handles control_cancel_request messages that cancel a pending request.
type CancelHandler func(requestID string)
// MessageHandler handles streaming messages from Claude Code CLI.
type MessageHandler func(msg *CLIMessage)
// pendingRequest tracks a control request waiting for a response.
type pendingRequest struct {
ch chan *IncomingControlResponse
}
// Client handles Claude Code CLI communication over stdin/stdout streams.
// It reads streaming JSON from stdout and writes control messages to stdin.
type Client struct {
stdin io.Writer
stdout io.Reader
logger *logger.Logger
// Handlers for incoming messages
requestHandler RequestHandler
cancelHandler CancelHandler
messageHandler MessageHandler
closeHandler func() // Called when readLoop exits (EOF or error)
// Pending control requests (requests we sent, waiting for responses)
pendingRequests map[string]*pendingRequest
pendingRequestsMu sync.Mutex
// Synchronization
mu sync.RWMutex
done chan struct{}
}
// NewClient creates a new Claude Code CLI client.
func NewClient(stdin io.Writer, stdout io.Reader, log *logger.Logger) *Client {
return &Client{
stdin: stdin,
stdout: stdout,
logger: log.WithFields(zap.String("component", "claudecode-client")),
done: make(chan struct{}),
pendingRequests: make(map[string]*pendingRequest),
}
}
// SetRequestHandler sets the handler for incoming control requests.
func (c *Client) SetRequestHandler(handler RequestHandler) {
c.mu.Lock()
defer c.mu.Unlock()
c.requestHandler = handler
}
// SetCancelHandler sets the handler for control_cancel_request messages.
func (c *Client) SetCancelHandler(handler CancelHandler) {
c.mu.Lock()
defer c.mu.Unlock()
c.cancelHandler = handler
}
// SetMessageHandler sets the handler for streaming messages.
func (c *Client) SetMessageHandler(handler MessageHandler) {
c.mu.Lock()
defer c.mu.Unlock()
c.messageHandler = handler
}
// SetCloseHandler sets a handler called when the read loop exits (EOF or error).
func (c *Client) SetCloseHandler(handler func()) {
c.mu.Lock()
defer c.mu.Unlock()
c.closeHandler = handler
}
// Start begins reading from stdout in a goroutine.
// Returns a channel that is closed when the read loop is ready.
func (c *Client) Start(ctx context.Context) <-chan struct{} {
ready := make(chan struct{})
go c.readLoop(ctx, ready)
return ready
}
// Stop stops the client and closes the done channel.
func (c *Client) Stop() {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.done:
// Already closed
default:
close(c.done)
}
}
// Initialize sends the initialize control request to Claude Code CLI and waits for the response.
// This must be called in streaming mode (input-format=stream-json) to get slash commands.
// hooks is optional — pass nil for no hooks.
func (c *Client) Initialize(ctx context.Context, timeout time.Duration, hooks map[string]any) (*InitializeResponseData, error) {
requestID := uuid.New().String()
// Create pending request channel
pending := &pendingRequest{
ch: make(chan *IncomingControlResponse, 1),
}
c.pendingRequestsMu.Lock()
c.pendingRequests[requestID] = pending
c.pendingRequestsMu.Unlock()
defer func() {
c.pendingRequestsMu.Lock()
delete(c.pendingRequests, requestID)
c.pendingRequestsMu.Unlock()
}()
// Send initialize control request
req := &SDKControlRequest{
Type: MessageTypeControlRequest,
RequestID: requestID,
Request: SDKControlRequestBody{
Subtype: SubtypeInitialize,
Hooks: hooks,
},
}
c.logger.Info("sending initialize control request", zap.String("request_id", requestID))
if err := c.send(req); err != nil {
return nil, fmt.Errorf("failed to send initialize request: %w", err)
}
// Wait for response with timeout
c.logger.Info("waiting for initialize response", zap.Duration("timeout", timeout))
select {
case <-ctx.Done():
c.logger.Warn("initialize cancelled by context")
return nil, ctx.Err()
case <-time.After(timeout):
c.logger.Warn("initialize request timed out", zap.Duration("timeout", timeout))
return nil, fmt.Errorf("initialize request timed out after %v", timeout)
case resp := <-pending.ch:
if resp.Subtype == "error" {
return nil, fmt.Errorf("initialize failed: %s", resp.Error)
}
c.logger.Info("initialize response received",
zap.Int("commands", len(resp.Response.Commands)),
zap.Int("agents", len(resp.Response.Agents)))
return resp.Response, nil
}
}
// SendControlRequest sends a control request to Claude Code CLI.
func (c *Client) SendControlRequest(req *SDKControlRequest) error {
return c.send(req)
}
// SendControlResponse sends a control response to Claude Code CLI.
func (c *Client) SendControlResponse(resp *ControlResponseMessage) error {
return c.send(resp)
}
// SendUserMessage sends a user message (prompt) to Claude Code CLI.
func (c *Client) SendUserMessage(content string) error {
msg := &UserMessage{
Type: MessageTypeUser,
Message: UserMessageBody{
Role: "user",
Content: content,
},
}
return c.send(msg)
}
func (c *Client) send(msg any) error {
data, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("failed to marshal message: %w", err)
}
data = append(data, '\n')
_, err = c.stdin.Write(data)
if err != nil {
return fmt.Errorf("failed to write message: %w", err)
}
c.logger.Debug("claudecode: sent message", zap.String("data", string(data)))
return nil
}
func (c *Client) readLoop(ctx context.Context, ready chan<- struct{}) {
scanner := bufio.NewScanner(c.stdout)
// Allow for large JSON messages (up to 10MB)
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, 10*1024*1024)
// Signal that we're ready to read
c.logger.Info("claudecode: read loop starting")
close(ready)
for scanner.Scan() {
select {
case <-ctx.Done():
return
case <-c.done:
return
default:
}
line := scanner.Bytes()
if len(line) == 0 {
continue
}
c.handleLine(line)
}
if err := scanner.Err(); err != nil {
c.logger.Error("read loop error", zap.Error(err))
}
// Notify close handler (e.g., to unblock Prompt on unexpected EOF)
c.mu.RLock()
handler := c.closeHandler
c.mu.RUnlock()
if handler != nil {
handler()
}
}
func (c *Client) handleLine(line []byte) {
// Log all incoming lines for debugging
c.logger.Debug("claudecode: received raw line",
zap.String("line", string(line)))
// First, parse the basic structure to determine message type
var msg CLIMessage
if err := json.Unmarshal(line, &msg); err != nil {
c.logger.Warn("failed to parse message", zap.Error(err), zap.String("line", string(line)))
return
}
c.logger.Debug("claudecode: parsed message",
zap.String("type", msg.Type),
zap.String("request_id", msg.RequestID),
zap.Bool("has_response", msg.Response != nil))
// Handle control requests (from Claude to us, e.g., permission requests)
if msg.Type == MessageTypeControlRequest && msg.Request != nil {
c.handleControlRequest(msg.RequestID, msg.Request)
return
}
// Handle control_cancel_request (cancels a pending permission/hook request)
if msg.Type == MessageTypeControlCancelRequest && msg.RequestID != "" {
c.mu.RLock()
handler := c.cancelHandler
c.mu.RUnlock()
if handler != nil {
handler(msg.RequestID)
} else {
c.logger.Warn("received control_cancel_request but no cancel handler registered",
zap.String("request_id", msg.RequestID))
}
return
}
// Handle control responses (from Claude back to us, e.g., initialize response)
// Note: request_id is inside the response object, not at the message level
if msg.Type == MessageTypeControlResponse && msg.Response != nil {
c.handleControlResponse(msg.Response)
return
}
// Forward other messages to the message handler
c.mu.RLock()
handler := c.messageHandler
c.mu.RUnlock()
if handler != nil {
// Store raw line for advanced parsing if needed
msg.RawContent = line
handler(&msg)
}
}
func (c *Client) handleControlRequest(requestID string, req *ControlRequest) {
c.mu.RLock()
handler := c.requestHandler
c.mu.RUnlock()
if handler != nil {
handler(requestID, req)
} else {
c.logger.Warn("received control request but no handler registered",
zap.String("request_id", requestID),
zap.String("subtype", req.Subtype))
// Auto-deny if no handler
if err := c.SendControlResponse(&ControlResponseMessage{
Type: MessageTypeControlResponse,
RequestID: requestID,
Response: &ControlResponse{
Subtype: "error",
Error: "no handler registered",
},
}); err != nil {
c.logger.Warn("failed to send error response", zap.Error(err))
}
}
}
func (c *Client) handleControlResponse(resp *IncomingControlResponse) {
requestID := resp.RequestID
c.pendingRequestsMu.Lock()
pending, ok := c.pendingRequests[requestID]
c.pendingRequestsMu.Unlock()
if !ok {
c.logger.Warn("received control response for unknown request",
zap.String("request_id", requestID),
zap.String("subtype", resp.Subtype))
return
}
c.logger.Info("received control response",
zap.String("request_id", requestID),
zap.String("subtype", resp.Subtype))
// Send response to waiting goroutine
select {
case pending.ch <- resp:
default:
c.logger.Warn("pending request channel full", zap.String("request_id", requestID))
}
}
-484
View File
@@ -1,484 +0,0 @@
package claudecode
import (
"bytes"
"context"
"encoding/json"
"io"
"strings"
"sync"
"testing"
"time"
"github.com/kandev/kandev/internal/common/logger"
)
// syncBuffer is a thread-safe bytes.Buffer for tests where a goroutine writes
// and the test goroutine reads.
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (sb *syncBuffer) Write(p []byte) (int, error) {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.Write(p)
}
func (sb *syncBuffer) Len() int {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.buf.Len()
}
func (sb *syncBuffer) Bytes() []byte {
sb.mu.Lock()
defer sb.mu.Unlock()
return append([]byte(nil), sb.buf.Bytes()...)
}
func newTestLogger() *logger.Logger {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json", OutputPath: "stdout"})
return log
}
func TestClient_SendUserMessage(t *testing.T) {
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(""), newTestLogger())
err := client.SendUserMessage("Hello, Claude!")
if err != nil {
t.Fatalf("SendUserMessage() error = %v", err)
}
// Parse what was written
var msg UserMessage
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &msg); err != nil {
t.Fatalf("failed to parse sent message: %v", err)
}
if msg.Type != MessageTypeUser {
t.Errorf("Type = %q, want %q", msg.Type, MessageTypeUser)
}
if msg.Message.Role != "user" {
t.Errorf("Message.Role = %q, want %q", msg.Message.Role, "user")
}
if msg.Message.Content != "Hello, Claude!" {
t.Errorf("Message.Content = %q, want %q", msg.Message.Content, "Hello, Claude!")
}
}
func TestClient_SendControlResponse(t *testing.T) {
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(""), newTestLogger())
resp := &ControlResponseMessage{
Type: MessageTypeControlResponse,
RequestID: "req123",
Response: &ControlResponse{
Subtype: "success",
Result: &PermissionResult{
Behavior: BehaviorAllow,
},
},
}
err := client.SendControlResponse(resp)
if err != nil {
t.Fatalf("SendControlResponse() error = %v", err)
}
// Parse what was written
var parsed ControlResponseMessage
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &parsed); err != nil {
t.Fatalf("failed to parse sent message: %v", err)
}
if parsed.RequestID != "req123" {
t.Errorf("RequestID = %q, want %q", parsed.RequestID, "req123")
}
}
func TestClient_SendControlRequest(t *testing.T) {
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(""), newTestLogger())
req := &SDKControlRequest{
Type: MessageTypeControlRequest,
RequestID: "init123",
Request: SDKControlRequestBody{
Subtype: SubtypeInitialize,
},
}
err := client.SendControlRequest(req)
if err != nil {
t.Fatalf("SendControlRequest() error = %v", err)
}
// Parse what was written
var parsed SDKControlRequest
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &parsed); err != nil {
t.Fatalf("failed to parse sent message: %v", err)
}
if parsed.Request.Subtype != SubtypeInitialize {
t.Errorf("Request.Subtype = %q, want %q", parsed.Request.Subtype, SubtypeInitialize)
}
}
func TestClient_HandleMessages(t *testing.T) {
// Create input with multiple messages
messages := []string{
`{"type":"system","session_id":"sess123"}`,
`{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Hello"}]}}`,
}
input := strings.Join(messages, "\n") + "\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(input), newTestLogger())
var received []CLIMessage
var mu sync.Mutex
client.SetMessageHandler(func(msg *CLIMessage) {
mu.Lock()
received = append(received, *msg)
mu.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond) // Give time for processing
mu.Lock()
count := len(received)
mu.Unlock()
if count != 2 {
t.Errorf("received %d messages, want 2", count)
}
}
func TestClient_HandleControlRequest(t *testing.T) {
// Create a control request message
input := `{"type":"control_request","request_id":"req123","request":{"subtype":"can_use_tool","tool_name":"Bash"}}` + "\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(input), newTestLogger())
var receivedReq *ControlRequest
var receivedID string
var mu sync.Mutex
client.SetRequestHandler(func(requestID string, req *ControlRequest) {
mu.Lock()
receivedID = requestID
receivedReq = req
mu.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond) // Give time for processing
mu.Lock()
defer mu.Unlock()
if receivedID != "req123" {
t.Errorf("requestID = %q, want %q", receivedID, "req123")
}
if receivedReq == nil {
t.Fatal("receivedReq is nil")
}
if receivedReq.Subtype != SubtypeCanUseTool {
t.Errorf("Subtype = %q, want %q", receivedReq.Subtype, SubtypeCanUseTool)
}
}
func TestClient_Stop(t *testing.T) {
// Use a pipe for continuous input
pr, _ := io.Pipe()
var buf bytes.Buffer
client := NewClient(&buf, pr, newTestLogger())
ctx := context.Background()
client.Start(ctx)
// Stop should not panic even if called multiple times
client.Stop()
client.Stop()
}
func TestClient_NoHandlerAutoReject(t *testing.T) {
// Create a control request message
input := `{"type":"control_request","request_id":"req123","request":{"subtype":"can_use_tool","tool_name":"Bash"}}` + "\n"
buf := &syncBuffer{}
client := NewClient(buf, strings.NewReader(input), newTestLogger())
// No request handler set - should auto-reject
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond) // Give time for processing
// Should have sent an error response
if buf.Len() == 0 {
t.Error("expected error response to be sent")
}
var resp ControlResponseMessage
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &resp); err != nil {
t.Fatalf("failed to parse response: %v", err)
}
if resp.Response == nil || resp.Response.Subtype != "error" {
t.Error("expected error response")
}
}
func TestClient_EmptyLines(t *testing.T) {
// Test that empty lines are skipped
input := "\n\n{\"type\":\"system\",\"session_id\":\"abc\"}\n\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(input), newTestLogger())
var count int
var mu sync.Mutex
client.SetMessageHandler(func(msg *CLIMessage) {
mu.Lock()
count++
mu.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
if count != 1 {
t.Errorf("count = %d, want 1", count)
}
}
func TestClient_InvalidJSON(t *testing.T) {
// Test that invalid JSON is handled gracefully
input := "{invalid json}\n{\"type\":\"system\"}\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(input), newTestLogger())
var count int
var mu sync.Mutex
client.SetMessageHandler(func(msg *CLIMessage) {
mu.Lock()
count++
mu.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
// Should still process the valid message
if count != 1 {
t.Errorf("count = %d, want 1", count)
}
}
func TestClient_HandleControlResponse(t *testing.T) {
// Simulate a control response coming back from Claude Code CLI
responseJSON := `{"type":"control_response","response":{"subtype":"success","request_id":"test-req-123","response":{"commands":[{"name":"cost","description":"Show cost"}],"agents":["Bash"]}}}` + "\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(responseJSON), newTestLogger())
// Register a pending request
pending := &pendingRequest{
ch: make(chan *IncomingControlResponse, 1),
}
client.pendingRequestsMu.Lock()
client.pendingRequests["test-req-123"] = pending
client.pendingRequestsMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
// Wait for the response
select {
case resp := <-pending.ch:
if resp.Subtype != "success" {
t.Errorf("Subtype = %q, want %q", resp.Subtype, "success")
}
if resp.RequestID != "test-req-123" {
t.Errorf("RequestID = %q, want %q", resp.RequestID, "test-req-123")
}
if resp.Response == nil {
t.Fatal("Response is nil")
}
if len(resp.Response.Commands) != 1 {
t.Errorf("Commands count = %d, want %d", len(resp.Response.Commands), 1)
}
if resp.Response.Commands[0].Name != "cost" {
t.Errorf("Commands[0].Name = %q, want %q", resp.Response.Commands[0].Name, "cost")
}
case <-time.After(50 * time.Millisecond):
t.Error("timeout waiting for control response")
}
}
func TestClient_HandleControlResponse_UnknownRequest(t *testing.T) {
// Simulate a control response for an unknown request ID (should be ignored)
responseJSON := `{"type":"control_response","response":{"subtype":"success","request_id":"unknown-req","response":{"commands":[]}}}` + "\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(responseJSON), newTestLogger())
// Don't register any pending request - response should be ignored
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond)
// Test passes if no panic occurs - the unknown response is just logged and ignored
}
func TestClient_HandleControlCancelRequest(t *testing.T) {
input := `{"type":"control_cancel_request","request_id":"cancel-req-123"}` + "\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(input), newTestLogger())
var receivedID string
var mu sync.Mutex
client.SetCancelHandler(func(requestID string) {
mu.Lock()
receivedID = requestID
mu.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
if receivedID != "cancel-req-123" {
t.Errorf("cancel handler received ID = %q, want %q", receivedID, "cancel-req-123")
}
}
func TestClient_HandleControlCancelRequest_NoHandler(t *testing.T) {
// Without a cancel handler, the cancel request should be logged and ignored
input := `{"type":"control_cancel_request","request_id":"cancel-req-456"}` + "\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(input), newTestLogger())
// Don't register a cancel handler
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond)
// Test passes if no panic occurs
}
func TestClient_CloseHandler_CalledOnEOF(t *testing.T) {
// Reader that immediately returns EOF
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(""), newTestLogger())
var called bool
var mu sync.Mutex
client.SetCloseHandler(func() {
mu.Lock()
called = true
mu.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(100 * time.Millisecond) // Give time for readLoop to exit
mu.Lock()
defer mu.Unlock()
if !called {
t.Error("close handler was not called on EOF")
}
}
func TestClient_CloseHandler_NotSetNoPanic(t *testing.T) {
// Verify no panic when close handler is not set
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(""), newTestLogger())
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(100 * time.Millisecond)
// Test passes if no panic occurs
}
func TestClient_HandleControlCancelRequest_NotForwardedAsMessage(t *testing.T) {
// control_cancel_request should be handled by the cancel handler,
// not forwarded to the message handler
input := `{"type":"control_cancel_request","request_id":"cancel-req-789"}` + "\n"
var buf bytes.Buffer
client := NewClient(&buf, strings.NewReader(input), newTestLogger())
var messageCount int
var mu sync.Mutex
client.SetCancelHandler(func(requestID string) {})
client.SetMessageHandler(func(msg *CLIMessage) {
mu.Lock()
messageCount++
mu.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
client.Start(ctx)
time.Sleep(50 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
if messageCount != 0 {
t.Errorf("message handler received %d messages, want 0", messageCount)
}
}
-450
View File
@@ -1,450 +0,0 @@
// Package claudecode provides types and client for the Claude Code CLI stream-json protocol.
// Claude Code uses a streaming JSON format over stdin/stdout with control requests for permissions.
package claudecode
import "encoding/json"
// Message types from Claude Code CLI
const (
// MessageTypeSystem is the initial system message with session info
MessageTypeSystem = "system"
// MessageTypeAssistant contains text or thinking from the assistant
MessageTypeAssistant = "assistant"
// MessageTypeResult is the final result message
MessageTypeResult = "result"
// MessageTypeControlRequest is a control request (permission, hook)
MessageTypeControlRequest = "control_request"
// MessageTypeControlResponse is a response to a control request
MessageTypeControlResponse = "control_response"
// MessageTypeControlCancelRequest cancels a pending control request (e.g., permission dialog)
MessageTypeControlCancelRequest = "control_cancel_request"
// MessageTypeUser is a user message (prompt)
MessageTypeUser = "user"
// MessageTypeRateLimit is emitted when the Anthropic API rate-limits the agent.
// Claude Code uses "rate_limit_event" as the message type.
MessageTypeRateLimit = "rate_limit_event"
)
// Control request subtypes
const (
// SubtypeCanUseTool is a permission request for tool use
SubtypeCanUseTool = "can_use_tool"
// SubtypeHookCallback is a hook callback request
SubtypeHookCallback = "hook_callback"
// SubtypeInitialize initializes the session
SubtypeInitialize = "initialize"
// SubtypeInterrupt interrupts the current operation
SubtypeInterrupt = "interrupt"
// SubtypeSetPermissionMode sets the permission mode
SubtypeSetPermissionMode = "set_permission_mode"
)
// Permission behaviors
const (
// BehaviorAllow allows the tool use
BehaviorAllow = "allow"
// BehaviorDeny denies the tool use
BehaviorDeny = "deny"
)
// CLIMessage represents messages from Claude Code CLI stdout.
// The message type determines which fields are populated.
type CLIMessage struct {
// Type is the message type (system, assistant, result, control_request, control_response, etc.)
Type string `json:"type"`
// UUID is a unique identifier for this message, used for --resume-session-at
UUID string `json:"uuid,omitempty"`
// For control_request messages (from Claude to us)
RequestID string `json:"request_id,omitempty"`
Request *ControlRequest `json:"request,omitempty"`
// For control_response messages (from Claude back to us after we send a control_request)
Response *IncomingControlResponse `json:"response,omitempty"`
// For system messages
SessionID string `json:"session_id,omitempty"`
SessionStatus string `json:"session_status,omitempty"`
SlashCommands []string `json:"slash_commands,omitempty"` // System message uses string array
PermissionMode string `json:"permissionMode,omitempty"` // From system status messages (e.g. "plan", "bypassPermissions")
// For subagent context (when running inside a Task tool call)
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
// For assistant messages
Message *AssistantMessage `json:"message,omitempty"`
// For result messages
// Result can be either a string (error message) or an object (ResultData)
Result json.RawMessage `json:"result,omitempty"`
Subtype string `json:"subtype,omitempty"`
CostUSD float64 `json:"total_cost_usd,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
DurationAPIMS int64 `json:"duration_api_ms,omitempty"`
IsError bool `json:"is_error,omitempty"`
Errors []string `json:"errors,omitempty"`
NumTurns int `json:"num_turns,omitempty"`
TotalInputTokens int64 `json:"total_input_tokens,omitempty"`
TotalOutputTokens int64 `json:"total_output_tokens,omitempty"`
ModelUsage map[string]ModelUsageStats `json:"model_usage,omitempty"`
// For rate_limit messages
RateLimitInfo json.RawMessage `json:"rate_limit_info,omitempty"`
// For user messages: replay/synthetic flags.
// IsReplay is true when the message is historical context echoed on resume.
// IsSynthetic is true for Claude-generated internal messages (checkpoint, injected context).
IsReplay bool `json:"isReplay,omitempty"`
IsSynthetic bool `json:"isSynthetic,omitempty"`
// For user messages: rich metadata about tool execution results.
// Contains structured data like {stdout, stderr} for Bash, {oldTodos, newTodos} for TodoWrite,
// or {status, agentId, totalDurationMs, totalTokens, totalToolUseCount} for Task (sub-agent).
ToolUseResult json.RawMessage `json:"tool_use_result,omitempty"`
// Raw message for parsing content blocks
RawContent json.RawMessage `json:"-"`
}
// AssistantMessage contains the assistant's response content.
// Note: For user messages (type="user"), Content may be a plain string instead of []ContentBlock.
// Use RawContent and GetContentBlocks()/GetContentString() for flexible parsing.
type AssistantMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content,omitempty"` // Can be string or []ContentBlock
Model string `json:"model,omitempty"`
StopReason string `json:"stop_reason,omitempty"`
Usage *Usage `json:"usage,omitempty"`
}
// GetContentBlocks attempts to parse Content as []ContentBlock.
// Returns nil if Content is a string or cannot be parsed.
func (m *AssistantMessage) GetContentBlocks() []ContentBlock {
if len(m.Content) == 0 {
return nil
}
var blocks []ContentBlock
if err := json.Unmarshal(m.Content, &blocks); err != nil {
return nil
}
return blocks
}
// GetContentString attempts to parse Content as a plain string.
// Returns empty string if Content is []ContentBlock or cannot be parsed.
func (m *AssistantMessage) GetContentString() string {
if len(m.Content) == 0 {
return ""
}
var s string
if err := json.Unmarshal(m.Content, &s); err != nil {
return ""
}
return s
}
// ContentBlock represents a block of content in an assistant message.
type ContentBlock struct {
Type string `json:"type"`
// For text blocks
Text string `json:"text,omitempty"`
// For thinking blocks
Thinking string `json:"thinking,omitempty"`
// For tool_use blocks
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Input map[string]any `json:"input,omitempty"`
// For tool_result blocks.
// Content can be a string or an array of text blocks (sub-agent results use arrays).
// Use GetContentString() to get the text regardless of format.
ToolUseID string `json:"tool_use_id,omitempty"`
RawContent json.RawMessage `json:"content,omitempty"`
IsError bool `json:"is_error,omitempty"`
}
// GetContentString returns tool_result content as a string.
// If content is a plain string, returns it directly.
// If content is an array of text blocks [{type, text}], concatenates all text values.
func (b *ContentBlock) GetContentString() string {
if len(b.RawContent) == 0 {
return ""
}
// Try as plain string first
var s string
if err := json.Unmarshal(b.RawContent, &s); err == nil {
return s
}
// Try as array of text blocks
var blocks []struct {
Text string `json:"text"`
}
if err := json.Unmarshal(b.RawContent, &blocks); err == nil {
var result string
for i, block := range blocks {
if i > 0 {
result += "\n"
}
result += block.Text
}
return result
}
return ""
}
// Usage contains token usage information.
type Usage struct {
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CacheCreationInputTokens int64 `json:"cache_creation_input_tokens,omitempty"`
CacheReadInputTokens int64 `json:"cache_read_input_tokens,omitempty"`
}
// ResultData contains the final result information.
type ResultData struct {
Text string `json:"text,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
// GetResultData attempts to parse the Result field as a ResultData object.
// Returns nil if Result is empty, a string, or cannot be parsed as ResultData.
func (m *CLIMessage) GetResultData() *ResultData {
if len(m.Result) == 0 {
return nil
}
var data ResultData
if err := json.Unmarshal(m.Result, &data); err != nil {
return nil
}
return &data
}
// GetResultString returns the Result field as a string.
// This is used when the result is an error message string.
func (m *CLIMessage) GetResultString() string {
if len(m.Result) == 0 {
return ""
}
var s string
if err := json.Unmarshal(m.Result, &s); err != nil {
// Not a string, return empty
return ""
}
return s
}
// ModelUsageStats contains per-model usage statistics from result message.
// The context_window field provides the actual model context window size.
type ModelUsageStats struct {
ContextWindow *int64 `json:"context_window,omitempty"`
}
// ControlRequest represents a control request from Claude Code CLI.
// This is used for permission requests (can_use_tool) and hook callbacks.
type ControlRequest struct {
// Subtype identifies the type of control request
Subtype string `json:"subtype"`
// For can_use_tool requests
ToolName string `json:"tool_name,omitempty"`
Input map[string]any `json:"input,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
BlockedPaths string `json:"blocked_paths,omitempty"`
// For hook_callback requests.
// Note: hook data (tool_name, tool_input, hook_event_name) is in the Input field,
// not a separate field — Claude Code sends it under "input" for both can_use_tool
// and hook_callback subtypes.
CallbackID string `json:"callback_id,omitempty"`
// Permission suggestions from Claude
PermissionSuggestions []PermissionUpdate `json:"permission_suggestions,omitempty"`
}
// PermissionUpdate represents a permission rule update.
type PermissionUpdate struct {
Tool string `json:"tool"`
Pattern string `json:"pattern,omitempty"`
Allow bool `json:"allow"`
}
// ControlResponseMessage is the message sent to respond to control requests.
type ControlResponseMessage struct {
Type string `json:"type"` // "control_response"
RequestID string `json:"request_id"`
Response *ControlResponse `json:"response"`
}
// IncomingControlResponse represents a control_response message from Claude Code CLI
// (response to a control_request we sent, like initialize).
type IncomingControlResponse struct {
// Subtype is the response type (success, error)
Subtype string `json:"subtype"`
// RequestID is the ID of the control_request this responds to
RequestID string `json:"request_id"`
// Response contains the response data (e.g., slash_commands for initialize)
Response *InitializeResponseData `json:"response,omitempty"`
// Error message if subtype is "error"
Error string `json:"error,omitempty"`
}
// InitializeResponseData contains the response data from an initialize control request.
type InitializeResponseData struct {
// Commands are the available commands (Claude Code uses "commands" not "slash_commands")
Commands []Command `json:"commands,omitempty"`
// Agents are the available agent names
Agents []string `json:"agents,omitempty"`
}
// Command represents an available command from the initialize response.
type Command struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
ArgumentHint string `json:"argumentHint,omitempty"`
}
// ControlResponse is the response to a control request.
type ControlResponse struct {
// Subtype is the response type (success, error)
Subtype string `json:"subtype"`
// For success responses — holds a *PermissionResult for can_use_tool,
// or a map[string]any for hook callbacks (hookSpecificOutput, decision/reason).
Result any `json:"result,omitempty"`
// For error responses
Error string `json:"error,omitempty"`
}
// PermissionResult is the result for tool approval responses.
type PermissionResult struct {
// Behavior is "allow" or "deny"
Behavior string `json:"behavior"`
// UpdatedInput allows modifying the tool input
UpdatedInput any `json:"updatedInput,omitempty"`
// UpdatedPermissions adds permission rules for future requests
UpdatedPermissions []PermissionUpdate `json:"updatedPermissions,omitempty"`
// Message provides feedback to the model
Message string `json:"message,omitempty"`
// Interrupt stops the current operation (for deny)
Interrupt *bool `json:"interrupt,omitempty"`
}
// SDKControlRequest is a control request sent to Claude Code CLI.
// Used for initialize, interrupt, and other control operations.
type SDKControlRequest struct {
Type string `json:"type"` // "control_request"
RequestID string `json:"request_id"`
Request SDKControlRequestBody `json:"request"`
}
// SDKControlRequestBody contains the body of an SDK control request.
type SDKControlRequestBody struct {
// Subtype identifies the operation (initialize, interrupt, set_permission_mode)
Subtype string `json:"subtype"`
// For initialize requests
Hooks map[string]any `json:"hooks,omitempty"`
// For set_permission_mode requests
Mode string `json:"mode,omitempty"`
}
// HookConfig defines hook configuration passed during initialize.
type HookConfig struct {
PreToolUse []HookEntry `json:"PreToolUse,omitempty"`
Stop []HookEntry `json:"Stop,omitempty"`
}
// HookEntry defines a single hook entry with a matcher pattern and callback IDs.
type HookEntry struct {
Matcher string `json:"matcher,omitempty"`
HookCallbackIDs []string `json:"hookCallbackIds"`
}
// ToMap converts HookConfig to map[string]any for use in SDKControlRequestBody.Hooks.
func (h *HookConfig) ToMap() map[string]any {
result := make(map[string]any)
if len(h.PreToolUse) > 0 {
result["PreToolUse"] = h.PreToolUse
}
if len(h.Stop) > 0 {
result["Stop"] = h.Stop
}
return result
}
// UserMessage is sent to provide a prompt to Claude Code.
type UserMessage struct {
Type string `json:"type"` // "user"
Message UserMessageBody `json:"message"`
}
// UserMessageBody contains the user message content.
type UserMessageBody struct {
Role string `json:"role"` // "user"
Content string `json:"content"`
}
// StreamEvent represents a streaming event from Claude Code.
// These are partial content updates during processing.
type StreamEvent struct {
Type string `json:"type"`
// Content stream events
Index int `json:"index,omitempty"`
ContentType string `json:"content_type,omitempty"`
// For text_delta events
Delta *TextDelta `json:"delta,omitempty"`
// For thinking_delta events
ThinkingDelta string `json:"thinking_delta,omitempty"`
}
// TextDelta contains a partial text update.
type TextDelta struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
}
// ToolApprovalOptions represents the available options for tool approval.
type ToolApprovalOptions struct {
Allow bool `json:"allow"`
AlwaysAllow bool `json:"always_allow"`
Deny bool `json:"deny"`
}
// Common tool names used by Claude Code
const (
ToolBash = "Bash"
ToolWrite = "Write"
ToolEdit = "Edit"
ToolNotebookEdit = "NotebookEdit"
ToolRead = "Read"
ToolGlob = "Glob"
ToolGrep = "Grep"
ToolTask = "Task"
ToolTaskCreate = "TaskCreate"
ToolTaskUpdate = "TaskUpdate"
ToolTaskList = "TaskList"
ToolTaskGet = "TaskGet"
ToolTodoWrite = "TodoWrite"
ToolWebFetch = "WebFetch"
ToolWebSearch = "WebSearch"
)
-684
View File
@@ -1,684 +0,0 @@
package claudecode
import (
"encoding/json"
"testing"
)
func TestCLIMessage_GetResultData(t *testing.T) {
tests := []struct {
name string
result json.RawMessage
wantNil bool
wantText string
}{
{
name: "empty result",
result: nil,
wantNil: true,
},
{
name: "string result (error)",
result: json.RawMessage(`"error message"`),
wantNil: true, // GetResultData returns nil for strings
},
{
name: "object result with text",
result: json.RawMessage(`{"text":"success message","session_id":"abc123"}`),
wantNil: false,
wantText: "success message",
},
{
name: "invalid JSON",
result: json.RawMessage(`{invalid`),
wantNil: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
msg := &CLIMessage{Result: tt.result}
got := msg.GetResultData()
switch {
case tt.wantNil:
if got != nil {
t.Errorf("GetResultData() = %v, want nil", got)
}
case got == nil:
t.Fatalf("GetResultData() = nil, want non-nil")
case got.Text != tt.wantText:
t.Errorf("GetResultData().Text = %q, want %q", got.Text, tt.wantText)
}
})
}
}
func TestCLIMessage_GetResultString(t *testing.T) {
tests := []struct {
name string
result json.RawMessage
want string
}{
{
name: "empty result",
result: nil,
want: "",
},
{
name: "string result",
result: json.RawMessage(`"error message"`),
want: "error message",
},
{
name: "object result",
result: json.RawMessage(`{"text":"success"}`),
want: "", // GetResultString returns empty for objects
},
{
name: "invalid JSON",
result: json.RawMessage(`{invalid`),
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
msg := &CLIMessage{Result: tt.result}
got := msg.GetResultString()
if got != tt.want {
t.Errorf("GetResultString() = %q, want %q", got, tt.want)
}
})
}
}
func TestCLIMessage_JSONParsing(t *testing.T) {
// Test parsing a system message
systemJSON := `{"type":"system","session_id":"abc123","session_status":"active"}`
var systemMsg CLIMessage
if err := json.Unmarshal([]byte(systemJSON), &systemMsg); err != nil {
t.Fatalf("failed to parse system message: %v", err)
}
if systemMsg.Type != MessageTypeSystem {
t.Errorf("Type = %q, want %q", systemMsg.Type, MessageTypeSystem)
}
if systemMsg.SessionID != "abc123" {
t.Errorf("SessionID = %q, want %q", systemMsg.SessionID, "abc123")
}
// Test parsing an assistant message
assistantJSON := `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Hello"}],"model":"claude-3"}}`
var assistantMsg CLIMessage
if err := json.Unmarshal([]byte(assistantJSON), &assistantMsg); err != nil {
t.Fatalf("failed to parse assistant message: %v", err)
}
if assistantMsg.Type != MessageTypeAssistant {
t.Errorf("Type = %q, want %q", assistantMsg.Type, MessageTypeAssistant)
}
if assistantMsg.Message == nil {
t.Fatal("Message is nil")
}
if assistantMsg.Message.Model != "claude-3" {
t.Errorf("Message.Model = %q, want %q", assistantMsg.Message.Model, "claude-3")
}
}
func TestControlRequest_JSONParsing(t *testing.T) {
// Test can_use_tool request
jsonStr := `{"subtype":"can_use_tool","tool_name":"Bash","input":{"command":"ls -la"},"tool_use_id":"tool123"}`
var req ControlRequest
if err := json.Unmarshal([]byte(jsonStr), &req); err != nil {
t.Fatalf("failed to parse control request: %v", err)
}
if req.Subtype != SubtypeCanUseTool {
t.Errorf("Subtype = %q, want %q", req.Subtype, SubtypeCanUseTool)
}
if req.ToolName != ToolBash {
t.Errorf("ToolName = %q, want %q", req.ToolName, ToolBash)
}
if req.Input["command"] != "ls -la" {
t.Errorf("Input[command] = %v, want %q", req.Input["command"], "ls -la")
}
}
func TestControlResponseMessage_JSONMarshal(t *testing.T) {
resp := &ControlResponseMessage{
Type: MessageTypeControlResponse,
RequestID: "req123",
Response: &ControlResponse{
Subtype: "success",
Result: &PermissionResult{
Behavior: BehaviorAllow,
},
},
}
data, err := json.Marshal(resp)
if err != nil {
t.Fatalf("failed to marshal: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal(data, &parsed); err != nil {
t.Fatalf("failed to parse result: %v", err)
}
if parsed["type"] != MessageTypeControlResponse {
t.Errorf("type = %v, want %q", parsed["type"], MessageTypeControlResponse)
}
if parsed["request_id"] != "req123" {
t.Errorf("request_id = %v, want %q", parsed["request_id"], "req123")
}
}
func TestUserMessage_JSONMarshal(t *testing.T) {
msg := &UserMessage{
Type: MessageTypeUser,
Message: UserMessageBody{
Role: "user",
Content: "Hello, Claude!",
},
}
data, err := json.Marshal(msg)
if err != nil {
t.Fatalf("failed to marshal: %v", err)
}
expected := `{"type":"user","message":{"role":"user","content":"Hello, Claude!"}}`
if string(data) != expected {
t.Errorf("Marshal() = %s, want %s", string(data), expected)
}
}
func TestContentBlock_Types(t *testing.T) {
tests := []struct {
name string
json string
check func(t *testing.T, block ContentBlock)
}{
{
name: "text block",
json: `{"type":"text","text":"Hello world"}`,
check: func(t *testing.T, block ContentBlock) {
if block.Type != "text" {
t.Errorf("Type = %q, want %q", block.Type, "text")
}
if block.Text != "Hello world" {
t.Errorf("Text = %q, want %q", block.Text, "Hello world")
}
},
},
{
name: "thinking block",
json: `{"type":"thinking","thinking":"Let me analyze..."}`,
check: func(t *testing.T, block ContentBlock) {
if block.Type != "thinking" {
t.Errorf("Type = %q, want %q", block.Type, "thinking")
}
if block.Thinking != "Let me analyze..." {
t.Errorf("Thinking = %q, want %q", block.Thinking, "Let me analyze...")
}
},
},
{
name: "tool_use block",
json: `{"type":"tool_use","id":"tool123","name":"Bash","input":{"command":"ls"}}`,
check: func(t *testing.T, block ContentBlock) {
if block.Type != "tool_use" {
t.Errorf("Type = %q, want %q", block.Type, "tool_use")
}
if block.ID != "tool123" {
t.Errorf("ID = %q, want %q", block.ID, "tool123")
}
if block.Name != "Bash" {
t.Errorf("Name = %q, want %q", block.Name, "Bash")
}
},
},
{
name: "tool_result block",
json: `{"type":"tool_result","tool_use_id":"tool123","content":"output","is_error":false}`,
check: func(t *testing.T, block ContentBlock) {
if block.Type != "tool_result" {
t.Errorf("Type = %q, want %q", block.Type, "tool_result")
}
if block.ToolUseID != "tool123" {
t.Errorf("ToolUseID = %q, want %q", block.ToolUseID, "tool123")
}
if block.GetContentString() != "output" {
t.Errorf("Content = %q, want %q", block.GetContentString(), "output")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var block ContentBlock
if err := json.Unmarshal([]byte(tt.json), &block); err != nil {
t.Fatalf("failed to parse: %v", err)
}
tt.check(t, block)
})
}
}
func TestModelUsageStats_ContextWindow(t *testing.T) {
jsonStr := `{"context_window": 200000}`
var stats ModelUsageStats
if err := json.Unmarshal([]byte(jsonStr), &stats); err != nil {
t.Fatalf("failed to parse: %v", err)
}
if stats.ContextWindow == nil {
t.Fatal("ContextWindow is nil")
}
if *stats.ContextWindow != 200000 {
t.Errorf("ContextWindow = %d, want %d", *stats.ContextWindow, 200000)
}
// Test nil context window
jsonStr2 := `{}`
var stats2 ModelUsageStats
if err := json.Unmarshal([]byte(jsonStr2), &stats2); err != nil {
t.Fatalf("failed to parse: %v", err)
}
if stats2.ContextWindow != nil {
t.Errorf("ContextWindow = %v, want nil", stats2.ContextWindow)
}
}
func TestAssistantMessage_GetContentBlocks(t *testing.T) {
tests := []struct {
name string
content string
wantCount int
wantType string
}{
{
name: "array of content blocks",
content: `[{"type":"text","text":"Hello"},{"type":"text","text":"World"}]`,
wantCount: 2,
wantType: "text",
},
{
name: "single content block",
content: `[{"type":"thinking","thinking":"Let me think..."}]`,
wantCount: 1,
wantType: "thinking",
},
{
name: "empty array",
content: `[]`,
wantCount: 0,
wantType: "",
},
{
name: "string content (not blocks)",
content: `"This is a string"`,
wantCount: 0,
wantType: "",
},
{
name: "empty content",
content: ``,
wantCount: 0,
wantType: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
msg := &AssistantMessage{
Content: json.RawMessage(tt.content),
}
blocks := msg.GetContentBlocks()
if len(blocks) != tt.wantCount {
t.Errorf("GetContentBlocks() returned %d blocks, want %d", len(blocks), tt.wantCount)
}
if tt.wantCount > 0 && blocks[0].Type != tt.wantType {
t.Errorf("GetContentBlocks()[0].Type = %q, want %q", blocks[0].Type, tt.wantType)
}
})
}
}
func TestAssistantMessage_GetContentString(t *testing.T) {
tests := []struct {
name string
content string
want string
}{
{
name: "plain string content",
content: `"Hello, World!"`,
want: "Hello, World!",
},
{
name: "string with local-command-stdout tags",
content: `"<local-command-stdout>Command output here</local-command-stdout>"`,
want: "<local-command-stdout>Command output here</local-command-stdout>",
},
{
name: "empty string",
content: `""`,
want: "",
},
{
name: "array content (not string)",
content: `[{"type":"text","text":"Hello"}]`,
want: "",
},
{
name: "empty content",
content: ``,
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
msg := &AssistantMessage{
Content: json.RawMessage(tt.content),
}
got := msg.GetContentString()
if got != tt.want {
t.Errorf("GetContentString() = %q, want %q", got, tt.want)
}
})
}
}
func TestIncomingControlResponse_JSONParsing(t *testing.T) {
// Test successful initialize response
jsonStr := `{
"subtype": "success",
"request_id": "req-123",
"response": {
"commands": [
{"name": "cost", "description": "Show cost"},
{"name": "context", "description": "Show context"}
],
"agents": ["Bash", "Explore"]
}
}`
var resp IncomingControlResponse
if err := json.Unmarshal([]byte(jsonStr), &resp); err != nil {
t.Fatalf("failed to parse: %v", err)
}
if resp.Subtype != "success" {
t.Errorf("Subtype = %q, want %q", resp.Subtype, "success")
}
if resp.RequestID != "req-123" {
t.Errorf("RequestID = %q, want %q", resp.RequestID, "req-123")
}
if resp.Response == nil {
t.Fatal("Response is nil")
}
if len(resp.Response.Commands) != 2 {
t.Errorf("Commands count = %d, want %d", len(resp.Response.Commands), 2)
}
if resp.Response.Commands[0].Name != "cost" {
t.Errorf("Commands[0].Name = %q, want %q", resp.Response.Commands[0].Name, "cost")
}
if len(resp.Response.Agents) != 2 {
t.Errorf("Agents count = %d, want %d", len(resp.Response.Agents), 2)
}
// Test error response
errorJSON := `{"subtype": "error", "request_id": "req-456", "error": "Something went wrong"}`
var errorResp IncomingControlResponse
if err := json.Unmarshal([]byte(errorJSON), &errorResp); err != nil {
t.Fatalf("failed to parse error response: %v", err)
}
if errorResp.Subtype != "error" {
t.Errorf("Subtype = %q, want %q", errorResp.Subtype, "error")
}
if errorResp.Error != "Something went wrong" {
t.Errorf("Error = %q, want %q", errorResp.Error, "Something went wrong")
}
}
func TestCLIMessage_IsReplay_IsSynthetic(t *testing.T) {
tests := []struct {
name string
json string
wantReplay bool
wantSynthetic bool
}{
{
name: "replay user message",
json: `{"type":"user","uuid":"abc","session_id":"sess-1","isReplay":true,"message":{"role":"user","content":"hello"}}`,
wantReplay: true,
wantSynthetic: false,
},
{
name: "synthetic user message",
json: `{"type":"user","uuid":"abc","session_id":"sess-1","isSynthetic":true,"message":{"role":"user","content":"checkpoint"}}`,
wantReplay: false,
wantSynthetic: true,
},
{
name: "replay and synthetic",
json: `{"type":"user","uuid":"abc","isReplay":true,"isSynthetic":true,"message":{"role":"user","content":"old"}}`,
wantReplay: true,
wantSynthetic: true,
},
{
name: "neither replay nor synthetic",
json: `{"type":"user","uuid":"abc","message":{"role":"user","content":"hello"}}`,
wantReplay: false,
wantSynthetic: false,
},
{
name: "assistant message has no replay fields",
json: `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"hi"}]}}`,
wantReplay: false,
wantSynthetic: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var msg CLIMessage
if err := json.Unmarshal([]byte(tt.json), &msg); err != nil {
t.Fatalf("failed to parse: %v", err)
}
if msg.IsReplay != tt.wantReplay {
t.Errorf("IsReplay = %v, want %v", msg.IsReplay, tt.wantReplay)
}
if msg.IsSynthetic != tt.wantSynthetic {
t.Errorf("IsSynthetic = %v, want %v", msg.IsSynthetic, tt.wantSynthetic)
}
})
}
}
func TestHookConfig_ToMap(t *testing.T) {
tests := []struct {
name string
config HookConfig
wantKeys []string
absentKeys []string
}{
{
name: "empty config",
config: HookConfig{},
wantKeys: nil,
absentKeys: []string{"PreToolUse", "Stop"},
},
{
name: "PreToolUse only",
config: HookConfig{
PreToolUse: []HookEntry{
{Matcher: `^Bash$`, HookCallbackIDs: []string{"tool_approval"}},
},
},
wantKeys: []string{"PreToolUse"},
absentKeys: []string{"Stop"},
},
{
name: "Stop only",
config: HookConfig{
Stop: []HookEntry{
{HookCallbackIDs: []string{"stop_git_check"}},
},
},
wantKeys: []string{"Stop"},
absentKeys: []string{"PreToolUse"},
},
{
name: "both hooks",
config: HookConfig{
PreToolUse: []HookEntry{
{Matcher: `^Bash$`, HookCallbackIDs: []string{"tool_approval"}},
},
Stop: []HookEntry{
{HookCallbackIDs: []string{"stop_git_check"}},
},
},
wantKeys: []string{"PreToolUse", "Stop"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.config.ToMap()
for _, key := range tt.wantKeys {
if _, ok := result[key]; !ok {
t.Errorf("ToMap() missing key %q", key)
}
}
for _, key := range tt.absentKeys {
if _, ok := result[key]; ok {
t.Errorf("ToMap() should not have key %q", key)
}
}
})
}
}
func TestHookConfig_ToMap_PreservesEntries(t *testing.T) {
cfg := HookConfig{
PreToolUse: []HookEntry{
{Matcher: `^Bash$`, HookCallbackIDs: []string{"tool_approval"}},
{Matcher: `^Edit$`, HookCallbackIDs: []string{"auto_approve"}},
},
}
result := cfg.ToMap()
entries, ok := result["PreToolUse"].([]HookEntry)
if !ok {
t.Fatal("PreToolUse is not []HookEntry")
}
if len(entries) != 2 {
t.Errorf("PreToolUse has %d entries, want 2", len(entries))
}
if entries[0].Matcher != `^Bash$` {
t.Errorf("entries[0].Matcher = %q, want %q", entries[0].Matcher, `^Bash$`)
}
if entries[1].HookCallbackIDs[0] != "auto_approve" {
t.Errorf("entries[1].HookCallbackIDs[0] = %q, want %q", entries[1].HookCallbackIDs[0], "auto_approve")
}
}
func TestContentBlock_GetContentString(t *testing.T) {
tests := []struct {
name string
json string
want string
}{
{
name: "string content",
json: `{"type":"tool_result","tool_use_id":"t1","content":"hello world"}`,
want: "hello world",
},
{
name: "array of text blocks",
json: `{"type":"tool_result","tool_use_id":"t1","content":[{"type":"text","text":"line 1"},{"type":"text","text":"line 2"}]}`,
want: "line 1\nline 2",
},
{
name: "single text block array",
json: `{"type":"tool_result","tool_use_id":"t1","content":[{"type":"text","text":"only line"}]}`,
want: "only line",
},
{
name: "empty content",
json: `{"type":"tool_result","tool_use_id":"t1"}`,
want: "",
},
{
name: "empty string content",
json: `{"type":"tool_result","tool_use_id":"t1","content":""}`,
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var block ContentBlock
if err := json.Unmarshal([]byte(tt.json), &block); err != nil {
t.Fatalf("failed to parse: %v", err)
}
got := block.GetContentString()
if got != tt.want {
t.Errorf("GetContentString() = %q, want %q", got, tt.want)
}
})
}
}
func TestCLIMessage_RateLimitEventType(t *testing.T) {
// Claude Code sends "rate_limit_event", not "rate_limit"
jsonStr := `{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"session_id":"sess-1"}`
var msg CLIMessage
if err := json.Unmarshal([]byte(jsonStr), &msg); err != nil {
t.Fatalf("failed to parse: %v", err)
}
if msg.Type != MessageTypeRateLimit {
t.Errorf("Type = %q, want %q (MessageTypeRateLimit)", msg.Type, MessageTypeRateLimit)
}
}
func TestCLIMessage_TotalCostUSD(t *testing.T) {
// Claude Code sends "total_cost_usd", not "cost_usd"
jsonStr := `{"type":"result","total_cost_usd":0.123,"session_id":"sess-1"}`
var msg CLIMessage
if err := json.Unmarshal([]byte(jsonStr), &msg); err != nil {
t.Fatalf("failed to parse: %v", err)
}
if msg.CostUSD != 0.123 {
t.Errorf("CostUSD = %f, want %f", msg.CostUSD, 0.123)
}
}
func TestCLIMessage_ToolUseResult(t *testing.T) {
// Sub-agent task result with rich metadata
jsonStr := `{
"type":"user",
"message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"result"}]},
"tool_use_result":{"status":"completed","agentId":"abc","totalDurationMs":1500,"totalTokens":4000,"totalToolUseCount":2},
"session_id":"sess-1"
}`
var msg CLIMessage
if err := json.Unmarshal([]byte(jsonStr), &msg); err != nil {
t.Fatalf("failed to parse: %v", err)
}
if len(msg.ToolUseResult) == 0 {
t.Fatal("ToolUseResult is empty")
}
var result map[string]any
if err := json.Unmarshal(msg.ToolUseResult, &result); err != nil {
t.Fatalf("failed to parse ToolUseResult: %v", err)
}
if result["status"] != "completed" {
t.Errorf("status = %v, want %q", result["status"], "completed")
}
if result["agentId"] != "abc" {
t.Errorf("agentId = %v, want %q", result["agentId"], "abc")
}
if result["totalDurationMs"].(float64) != 1500 {
t.Errorf("totalDurationMs = %v, want %v", result["totalDurationMs"], 1500)
}
}
-250
View File
@@ -1,250 +0,0 @@
package codex
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"sync"
"sync/atomic"
"github.com/kandev/kandev/internal/common/logger"
"go.uber.org/zap"
)
// Client handles Codex JSON-RPC communication over stdin/stdout streams.
// Unlike standard JSON-RPC 2.0, Codex omits the "jsonrpc":"2.0" field.
type Client struct {
stdin io.Writer
stdout io.Reader
requestID atomic.Int64
pending map[interface{}]chan *Response
mu sync.Mutex
onNotification func(method string, params json.RawMessage)
onRequest func(id interface{}, method string, params json.RawMessage)
logger *logger.Logger
done chan struct{}
}
// NewClient creates a new Codex JSON-RPC client
func NewClient(stdin io.Writer, stdout io.Reader, log *logger.Logger) *Client {
return &Client{
stdin: stdin,
stdout: stdout,
pending: make(map[interface{}]chan *Response),
logger: log.WithFields(zap.String("component", "codex-client")),
done: make(chan struct{}),
}
}
// SetNotificationHandler sets the handler for incoming notifications
func (c *Client) SetNotificationHandler(handler func(method string, params json.RawMessage)) {
c.onNotification = handler
}
// SetRequestHandler sets the handler for incoming requests from the agent
func (c *Client) SetRequestHandler(handler func(id interface{}, method string, params json.RawMessage)) {
c.onRequest = handler
}
// SendResponse sends a response to an agent request
func (c *Client) SendResponse(id interface{}, result interface{}, err *Error) error {
var resultJSON json.RawMessage
if result != nil && err == nil {
var marshalErr error
resultJSON, marshalErr = json.Marshal(result)
if marshalErr != nil {
return fmt.Errorf("failed to marshal result: %w", marshalErr)
}
}
resp := &Response{ID: id, Result: resultJSON, Error: err}
c.logger.Info("sending response to codex",
zap.Any("id", id),
zap.String("result", string(resultJSON)),
zap.Any("error", err))
return c.send(resp)
}
// Start begins reading responses from stdout
func (c *Client) Start(ctx context.Context) {
go c.readLoop(ctx)
}
// Stop stops the client
func (c *Client) Stop() {
close(c.done)
}
// Call sends a request and waits for a response
func (c *Client) Call(ctx context.Context, method string, params interface{}) (*Response, error) {
id := c.requestID.Add(1)
var paramsJSON json.RawMessage
if params != nil {
var err error
paramsJSON, err = json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("failed to marshal params: %w", err)
}
}
req := &Request{ID: id, Method: method, Params: paramsJSON}
respCh := make(chan *Response, 1)
c.mu.Lock()
c.pending[id] = respCh
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, id)
c.mu.Unlock()
}()
if err := c.send(req); err != nil {
return nil, err
}
select {
case resp := <-respCh:
return resp, nil
case <-ctx.Done():
return nil, ctx.Err()
case <-c.done:
return nil, fmt.Errorf("client closed")
}
}
// Notify sends a notification (no response expected)
func (c *Client) Notify(method string, params interface{}) error {
var paramsJSON json.RawMessage
if params != nil {
var err error
paramsJSON, err = json.Marshal(params)
if err != nil {
return fmt.Errorf("failed to marshal params: %w", err)
}
}
notif := &Notification{Method: method, Params: paramsJSON}
return c.send(notif)
}
func (c *Client) send(msg interface{}) error {
data, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("failed to marshal message: %w", err)
}
data = append(data, '\n')
_, err = c.stdin.Write(data)
if err != nil {
return fmt.Errorf("failed to write message: %w", err)
}
c.logger.Debug("codex: sent message", zap.String("data", string(data)))
return nil
}
func (c *Client) readLoop(ctx context.Context) {
scanner := bufio.NewScanner(c.stdout)
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, 1024*1024)
for scanner.Scan() {
select {
case <-ctx.Done():
return
case <-c.done:
return
default:
}
line := scanner.Bytes()
if len(line) == 0 {
continue
}
c.processCodexMessage(line)
}
if err := scanner.Err(); err != nil {
c.logger.Error("read loop error", zap.Error(err))
}
}
// processCodexMessage parses a single JSON line and routes it as a response, request, or notification.
func (c *Client) processCodexMessage(line []byte) {
var msg struct {
ID interface{} `json:"id"`
Method string `json:"method"`
Result json.RawMessage `json:"result"`
Error *Error `json:"error"`
Params json.RawMessage `json:"params"`
}
if err := json.Unmarshal(line, &msg); err != nil {
c.logger.Warn("failed to parse message", zap.Error(err))
return
}
hasID := msg.ID != nil
hasMethod := msg.Method != ""
hasResult := msg.Result != nil
hasError := msg.Error != nil
c.logger.Info("codex: received message",
zap.Bool("hasID", hasID),
zap.Bool("hasMethod", hasMethod),
zap.String("method", msg.Method))
switch {
case hasID && !hasMethod && (hasResult || hasError):
c.handleResponse(&Response{ID: msg.ID, Result: msg.Result, Error: msg.Error})
case hasID && hasMethod:
c.logger.Info("codex: routing as request", zap.Any("id", msg.ID), zap.String("method", msg.Method))
c.handleRequest(msg.ID, msg.Method, msg.Params)
case hasMethod && !hasID:
c.handleNotification(msg.Method, msg.Params)
}
}
func (c *Client) handleResponse(resp *Response) {
id := normalizeID(resp.ID)
c.mu.Lock()
ch, ok := c.pending[id]
c.mu.Unlock()
if ok {
ch <- resp
} else {
c.logger.Warn("received response for unknown request", zap.Any("id", resp.ID))
}
}
func normalizeID(id interface{}) interface{} {
switch v := id.(type) {
case float64:
return int64(v)
case json.Number:
if i, err := v.Int64(); err == nil {
return i
}
}
return id
}
func (c *Client) handleNotification(method string, params json.RawMessage) {
if c.onNotification != nil {
c.onNotification(method, params)
}
}
func (c *Client) handleRequest(id interface{}, method string, params json.RawMessage) {
if c.onRequest != nil {
c.onRequest(id, method, params)
} else {
c.logger.Warn("received request but no handler registered", zap.String("method", method))
if err := c.SendResponse(id, nil, &Error{Code: MethodNotFound, Message: "Method not found"}); err != nil {
c.logger.Warn("failed to send method not found response", zap.Error(err))
}
}
}
-422
View File
@@ -1,422 +0,0 @@
// Package codex provides types and client for the OpenAI Codex app-server protocol.
// Codex uses a JSON-RPC 2.0 variant over stdio, but omits the "jsonrpc":"2.0" header.
package codex
import "encoding/json"
// Request represents a Codex JSON-RPC request (without jsonrpc field)
type Request struct {
ID interface{} `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
// Response represents a Codex JSON-RPC response
type Response struct {
ID interface{} `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
// Notification represents a Codex notification (no id field)
type Notification struct {
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
// Error represents a JSON-RPC error
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
// Standard error codes
const (
ParseError = -32700
InvalidRequest = -32600
MethodNotFound = -32601
InvalidParams = -32602
InternalError = -32603
)
// Codex method names
const (
MethodInitialize = "initialize"
MethodInitialized = "initialized" // Notification
MethodThreadStart = "thread/start"
MethodThreadResume = "thread/resume"
MethodThreadFork = "thread/fork"
MethodThreadList = "thread/list"
MethodThreadArchive = "thread/archive"
MethodTurnStart = "turn/start"
MethodTurnInterrupt = "turn/interrupt"
MethodCommandExec = "command/exec"
MethodModelList = "model/list"
MethodSkillsList = "skills/list"
MethodAccountRead = "account/read"
MethodAccountLogout = "account/logout"
MethodReviewStart = "review/start"
MethodConfigRead = "config/read"
)
// Codex notification methods (server → client)
const (
NotifyThreadStarted = "thread/started"
NotifyTurnStarted = "turn/started"
NotifyTurnCompleted = "turn/completed"
NotifyTurnDiffUpdated = "turn/diff/updated"
NotifyTurnPlanUpdated = "turn/plan/updated"
NotifyItemStarted = "item/started"
NotifyItemCompleted = "item/completed"
NotifyItemAgentMessageDelta = "item/agentMessage/delta"
NotifyItemReasoningSummaryDelta = "item/reasoning/summaryTextDelta"
NotifyItemReasoningTextDelta = "item/reasoning/textDelta"
NotifyItemCmdExecOutputDelta = "item/commandExecution/outputDelta"
NotifyItemCmdExecRequestApproval = "item/commandExecution/requestApproval"
NotifyItemFileChangeRequestApproval = "item/fileChange/requestApproval"
NotifyAccountUpdated = "account/updated"
NotifyAccountLoginCompleted = "account/login/completed"
NotifyError = "error"
NotifyTokenCount = "token_count"
NotifyThreadTokenUsageUpdated = "thread/tokenUsage/updated"
NotifyContextCompacted = "context_compacted"
)
// InitializeParams for initialize request
type InitializeParams struct {
ClientInfo *ClientInfo `json:"clientInfo"`
}
// ClientInfo identifies the client
type ClientInfo struct {
Name string `json:"name"`
Title string `json:"title,omitempty"`
Version string `json:"version"`
}
// InitializeResult from initialize
type InitializeResult struct {
UserAgent string `json:"userAgent,omitempty"`
}
// ThreadStartParams for thread/start
type ThreadStartParams struct {
Model string `json:"model,omitempty"`
Cwd string `json:"cwd,omitempty"`
ApprovalPolicy string `json:"approvalPolicy,omitempty"` // "untrusted", "on-failure", "on-request", "never"
Sandbox string `json:"sandbox,omitempty"` // "workspaceWrite", "readOnly", etc.
SandboxPolicy *SandboxPolicy `json:"sandboxPolicy,omitempty"`
}
// SandboxPolicy configures sandbox behavior.
// Type must use kebab-case values per Codex documentation:
// - "read-only": prevents edits, command execution, and network access
// - "workspace-write": allows reads, edits, and commands within the active workspace
// - "danger-full-access": removes all sandbox constraints (not recommended)
type SandboxPolicy struct {
Type string `json:"type"` // "workspace-write", "read-only", "danger-full-access"
WritableRoots []string `json:"writableRoots,omitempty"`
NetworkAccess bool `json:"networkAccess,omitempty"`
}
// Thread represents a Codex thread (conversation)
type Thread struct {
ID string `json:"id"`
Preview string `json:"preview,omitempty"`
ModelProvider string `json:"modelProvider,omitempty"`
CreatedAt int64 `json:"createdAt,omitempty"`
}
// ThreadStartResult from thread/start
type ThreadStartResult struct {
Thread *Thread `json:"thread"`
}
// ThreadResumeParams for thread/resume
type ThreadResumeParams struct {
ThreadID string `json:"threadId"`
Cwd string `json:"cwd,omitempty"`
ApprovalPolicy string `json:"approvalPolicy,omitempty"` // "untrusted", "on-failure", "on-request", "never"
SandboxPolicy *SandboxPolicy `json:"sandboxPolicy,omitempty"`
}
// ThreadResumeResult from thread/resume
type ThreadResumeResult struct {
Thread *Thread `json:"thread"`
}
// UserInput represents input to a turn
type UserInput struct {
Type string `json:"type"` // "text", "image", "localImage", "skill"
Text string `json:"text,omitempty"`
URL string `json:"url,omitempty"`
Path string `json:"path,omitempty"`
Name string `json:"name,omitempty"`
}
// TurnStartParams for turn/start
type TurnStartParams struct {
ThreadID string `json:"threadId"`
Input []UserInput `json:"input"`
}
// Turn represents a Codex turn within a thread
type Turn struct {
ID string `json:"id"`
Status string `json:"status"` // "inProgress", "completed", "failed"
Items []Item `json:"items"`
Error *Error `json:"error,omitempty"`
}
// TurnStartResult from turn/start
type TurnStartResult struct {
Turn *Turn `json:"turn"`
}
// Item represents a Codex item (message, command, file change, etc.)
type Item struct {
ID string `json:"id"`
Type string `json:"type"` // "userMessage", "agentMessage", "commandExecution", "fileChange", "reasoning", "mcpToolCall"
Status string `json:"status"` // "inProgress", "completed", "failed"
// For commandExecution type
Command string `json:"command,omitempty"`
Cwd string `json:"cwd,omitempty"`
AggregatedOutput string `json:"aggregatedOutput,omitempty"`
ExitCode *int `json:"exitCode,omitempty"`
DurationMs *int `json:"durationMs,omitempty"`
// For fileChange type
Changes []FileChange `json:"changes,omitempty"`
// For reasoning type - content can be objects like [{type: "text", text: "..."}]
// or plain strings. FlexibleContent handles both formats.
Summary FlexibleContent `json:"summary,omitempty"`
Content FlexibleContent `json:"content,omitempty"`
// For mcpToolCall type
Server string `json:"server,omitempty"`
Tool string `json:"tool,omitempty"`
Arguments json.RawMessage `json:"arguments,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
ToolError string `json:"error,omitempty"` // Named ToolError to avoid conflict with Error type
}
// ContentPart represents a content part in a Codex item.
// This handles the OpenAI responses format where content is an array of typed objects.
type ContentPart struct {
Type string `json:"type,omitempty"` // "text", "output_text", "refusal", "input_text", etc.
Text string `json:"text,omitempty"`
}
// FlexibleContent is a type that can unmarshal from either a string or []ContentPart.
// Codex sometimes sends summary/content as a plain string, other times as an array.
type FlexibleContent []ContentPart
// UnmarshalJSON implements custom unmarshaling for FlexibleContent.
// It handles both string and array formats from Codex.
func (fc *FlexibleContent) UnmarshalJSON(data []byte) error {
// Try to unmarshal as array first (most common case)
var parts []ContentPart
if err := json.Unmarshal(data, &parts); err == nil {
*fc = parts
return nil
}
// Try to unmarshal as string
var str string
if err := json.Unmarshal(data, &str); err == nil {
*fc = []ContentPart{{Type: "text", Text: str}}
return nil
}
// If both fail, return empty (don't fail parsing)
*fc = nil
return nil
}
// FileChange represents a file change in a fileChange item
type FileChange struct {
Path string `json:"path"`
Kind FileChangeKind `json:"kind"`
Diff string `json:"diff,omitempty"`
}
// FileChangeKind represents the type of file change
type FileChangeKind struct {
Type string `json:"type"` // "add", "modify", "delete"
}
// ItemStartedParams for item/started notification
type ItemStartedParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
Item *Item `json:"item"`
}
// ItemCompletedParams for item/completed notification
type ItemCompletedParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
Item *Item `json:"item"`
}
// AgentMessageDeltaParams for item/agentMessage/delta
type AgentMessageDeltaParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
ItemID string `json:"itemId"`
Delta string `json:"delta"`
}
// ReasoningDeltaParams for item/reasoning/textDelta and summaryTextDelta
type ReasoningDeltaParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
ItemID string `json:"itemId"`
Delta string `json:"delta"`
}
// CommandOutputDeltaParams for item/commandExecution/outputDelta
type CommandOutputDeltaParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
ItemID string `json:"itemId"`
Delta string `json:"delta"`
}
// CommandApprovalParams for item/commandExecution/requestApproval
type CommandApprovalParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
ItemID string `json:"itemId"`
Command string `json:"command"`
Cwd string `json:"cwd,omitempty"`
Reasoning string `json:"reasoning,omitempty"`
Options []string `json:"options,omitempty"` // e.g., ["approve", "reject", "approveAlways"]
}
// FileChangeApprovalParams for item/fileChange/requestApproval
type FileChangeApprovalParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
ItemID string `json:"itemId"`
Path string `json:"path"`
Diff string `json:"diff,omitempty"`
Reasoning string `json:"reasoning,omitempty"`
Options []string `json:"options,omitempty"`
}
// TurnCompletedParams for turn/completed notification
type TurnCompletedParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
// TurnDiffUpdatedParams for turn/diff/updated notification
type TurnDiffUpdatedParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
Diff string `json:"diff"`
}
// TurnPlanUpdatedParams for turn/plan/updated notification
type TurnPlanUpdatedParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
Plan []PlanEntry `json:"plan"`
}
// PlanEntry represents a single plan item
type PlanEntry struct {
Description string `json:"description"`
Status string `json:"status"` // "pending", "in_progress", "completed", "failed"
}
// CommandApprovalResponse for responding to command execution approval requests
// Decision values: "accept", "acceptForSession", "decline", "cancel"
type CommandApprovalResponse struct {
Decision string `json:"decision"`
}
// FileChangeApprovalResponse for responding to file change approval requests
// Decision values: "accept", "acceptForSession", "decline", "cancel"
type FileChangeApprovalResponse struct {
Decision string `json:"decision"`
}
// ErrorParams for error notification
type ErrorParams struct {
Code int `json:"code,omitempty"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
// TokenCountParams for token_count notification
// This is emitted by Codex after each turn to report token usage.
type TokenCountParams struct {
Info *TokenUsageInfo `json:"info,omitempty"`
RateLimits *RateLimitSnapshot `json:"rateLimits,omitempty"`
}
// TokenUsageInfo contains detailed token usage information.
type TokenUsageInfo struct {
TotalTokenUsage *TokenUsage `json:"totalTokenUsage,omitempty"`
LastTokenUsage *TokenUsage `json:"lastTokenUsage,omitempty"`
ModelContextWindow *int64 `json:"modelContextWindow,omitempty"`
}
// TokenUsage contains token counts for a request/response cycle.
type TokenUsage struct {
InputTokens int32 `json:"inputTokens"`
CachedInputTokens int32 `json:"cachedInputTokens"`
OutputTokens int32 `json:"outputTokens"`
ReasoningOutputTokens int32 `json:"reasoningOutputTokens"`
TotalTokens int32 `json:"totalTokens"`
}
// ThreadTokenUsageUpdatedParams for thread/tokenUsage/updated notification.
// This is emitted by Codex after each turn completes with token usage info.
type ThreadTokenUsageUpdatedParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
TokenUsage *ThreadTokenUsage `json:"tokenUsage"`
}
// ThreadTokenUsage contains the token usage summary for a thread.
type ThreadTokenUsage struct {
Total *TokenUsage `json:"total,omitempty"`
Last *TokenUsage `json:"last,omitempty"`
ModelContextWindow int64 `json:"modelContextWindow"`
}
// RateLimitSnapshot contains rate limit information.
type RateLimitSnapshot struct {
Primary *RateLimitWindow `json:"primary,omitempty"`
Secondary *RateLimitWindow `json:"secondary,omitempty"`
Credits *CreditsSnapshot `json:"credits,omitempty"`
PlanType *string `json:"planType,omitempty"`
}
// RateLimitWindow contains rate limit window information.
type RateLimitWindow struct {
UsedPercent int32 `json:"usedPercent"`
WindowDurationMins *int64 `json:"windowDurationMins,omitempty"`
ResetsAt *int64 `json:"resetsAt,omitempty"`
}
// CreditsSnapshot contains credits information (placeholder for future use).
type CreditsSnapshot struct {
Remaining *int64 `json:"remaining,omitempty"`
Used *int64 `json:"used,omitempty"`
}
// ContextCompactedParams for context_compacted notification.
// Emitted when the context has been compacted due to reaching limits.
type ContextCompactedParams struct {
ThreadID string `json:"threadId"`
TurnID string `json:"turnId"`
}
-389
View File
@@ -1,389 +0,0 @@
// Package copilot provides integration with the GitHub Copilot SDK.
// This is a thin wrapper around github.com/github/copilot-sdk/go that
// provides a consistent interface for the kandev agent system.
//
// When CLIUrl is configured, the SDK connects to an externally managed
// Copilot CLI server via TCP (JSON-RPC). Otherwise, the SDK spawns and
// manages the CLI process internally via stdio.
package copilot
import (
"context"
"fmt"
"sync"
"time"
"github.com/github/copilot-sdk/go"
"github.com/kandev/kandev/internal/common/logger"
"go.uber.org/zap"
)
// Re-export SDK types for convenience
type (
SessionEvent = copilot.SessionEvent
SessionEventType = copilot.SessionEventType
SessionConfig = copilot.SessionConfig
MessageOptions = copilot.MessageOptions
Data = copilot.Data
// Permission types
PermissionHandler = copilot.PermissionHandler
PermissionRequest = copilot.PermissionRequest
PermissionInvocation = copilot.PermissionInvocation
PermissionRequestResult = copilot.PermissionRequestResult
// MCP types
MCPServerConfig = copilot.MCPServerConfig
)
// Re-export event type constants
const (
EventTypeSessionStart = copilot.SessionStart
EventTypeSessionResume = copilot.SessionResume
EventTypeSessionIdle = copilot.SessionIdle
EventTypeSessionError = copilot.SessionError
EventTypeSessionUsageInfo = copilot.SessionUsageInfo
EventTypeAssistantMessage = copilot.AssistantMessage
EventTypeAssistantMessageDelta = copilot.AssistantMessageDelta
EventTypeAssistantReasoning = copilot.AssistantReasoning
EventTypeAssistantReasoningDelta = copilot.AssistantReasoningDelta
EventTypeAssistantTurnStart = copilot.AssistantTurnStart
EventTypeAssistantTurnEnd = copilot.AssistantTurnEnd
EventTypeAssistantUsage = copilot.AssistantUsage
EventTypeToolStart = copilot.ToolExecutionStart
EventTypeToolComplete = copilot.ToolExecutionComplete
EventTypeToolProgress = copilot.ToolExecutionProgress
EventTypeAbort = copilot.Abort
)
// Client wraps the Copilot SDK client with additional functionality.
type Client struct {
sdkClient *copilot.Client
session *copilot.Session
logger *logger.Logger
// Configuration
cliURL string
model string
// Event handler
eventHandler func(SessionEvent)
unsubscribe func()
handlerMu sync.RWMutex
// Permission handler
permissionHandler PermissionHandler
permissionMu sync.RWMutex
// State
sessionID string
mu sync.RWMutex
started bool
}
// ClientConfig holds configuration for creating a Client.
type ClientConfig struct {
// CLIUrl is the address of an externally managed Copilot CLI server (e.g. "localhost:12345").
// When set, the SDK connects via TCP instead of spawning its own process.
CLIUrl string
Model string
}
// NewClient creates a new Copilot client wrapper.
func NewClient(cfg ClientConfig, log *logger.Logger) *Client {
if cfg.Model == "" {
cfg.Model = "gpt-4.1"
}
return &Client{
cliURL: cfg.CLIUrl,
model: cfg.Model,
logger: log.WithFields(zap.String("component", "copilot-sdk-client")),
}
}
// SetEventHandler sets the handler for session events.
func (c *Client) SetEventHandler(handler func(SessionEvent)) {
c.handlerMu.Lock()
defer c.handlerMu.Unlock()
c.eventHandler = handler
}
// SetPermissionHandler sets the handler for permission requests.
func (c *Client) SetPermissionHandler(handler PermissionHandler) {
c.permissionMu.Lock()
defer c.permissionMu.Unlock()
c.permissionHandler = handler
}
// Start initializes the Copilot SDK client.
// When CLIUrl is configured, the SDK connects to an external CLI server via TCP.
// Otherwise, the SDK spawns and manages the CLI process internally via stdio.
// The actual connection is deferred to the first CreateSession call via AutoStart.
func (c *Client) Start(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.started {
return fmt.Errorf("client already started")
}
c.logger.Info("starting Copilot SDK client",
zap.String("model", c.model),
zap.String("cli_url", c.cliURL))
if c.cliURL != "" {
// Connect to externally managed CLI server via TCP
c.sdkClient = copilot.NewClient(&copilot.ClientOptions{
CLIUrl: c.cliURL,
LogLevel: "error",
})
} else {
// SDK spawns and manages the CLI process internally (stdio)
c.sdkClient = copilot.NewClient(nil)
}
// SDK AutoStart (default: true) defers the actual connection
// to the first CreateSession call, so no explicit Start() needed.
c.started = true
c.logger.Info("Copilot SDK client initialized")
return nil
}
// Stop shuts down the Copilot SDK client.
func (c *Client) Stop() error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.started {
return nil
}
c.logger.Info("stopping Copilot SDK client")
// Unsubscribe from events
c.handlerMu.Lock()
if c.unsubscribe != nil {
c.unsubscribe()
c.unsubscribe = nil
}
c.handlerMu.Unlock()
// Destroy session if active
if c.session != nil {
if err := c.session.Destroy(); err != nil {
c.logger.Warn("error destroying session", zap.Error(err))
}
c.session = nil
}
// Stop the SDK client
if c.sdkClient != nil {
errs := c.sdkClient.Stop()
for _, err := range errs {
c.logger.Warn("error stopping SDK client", zap.Error(err))
}
c.sdkClient = nil
}
c.started = false
return nil
}
// CreateSession creates a new Copilot session.
// mcpServers configures MCP servers for the session (nil if none).
func (c *Client) CreateSession(ctx context.Context, mcpServers map[string]MCPServerConfig) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if !c.started {
return "", fmt.Errorf("client not started")
}
// Unsubscribe from previous session events
c.handlerMu.Lock()
if c.unsubscribe != nil {
c.unsubscribe()
c.unsubscribe = nil
}
c.handlerMu.Unlock()
// Destroy existing session if any
if c.session != nil {
if err := c.session.Destroy(); err != nil {
c.logger.Warn("error destroying previous session", zap.Error(err))
}
c.session = nil
}
c.logger.Info("creating new session",
zap.String("model", c.model),
zap.Int("mcp_servers", len(mcpServers)))
// Get permission handler
c.permissionMu.RLock()
permHandler := c.permissionHandler
c.permissionMu.RUnlock()
// Create session with configuration
session, err := c.sdkClient.CreateSession(&copilot.SessionConfig{
Model: c.model,
Streaming: true,
OnPermissionRequest: permHandler,
MCPServers: mcpServers,
})
if err != nil {
return "", fmt.Errorf("failed to create session: %w", err)
}
// Register event handler BEFORE storing the session so no events are lost
// between session creation and handler registration.
c.handlerMu.Lock()
if c.eventHandler != nil {
c.unsubscribe = session.On(c.eventHandler)
}
c.handlerMu.Unlock()
c.session = session
c.sessionID = session.SessionID
c.logger.Info("session created", zap.String("session_id", c.sessionID))
return c.sessionID, nil
}
// ResumeSession resumes an existing session with streaming enabled.
// mcpServers configures MCP servers for the resumed session (nil if none).
func (c *Client) ResumeSession(ctx context.Context, sessionID string, mcpServers map[string]MCPServerConfig) error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.started {
return fmt.Errorf("client not started")
}
// Unsubscribe from previous session events
c.handlerMu.Lock()
if c.unsubscribe != nil {
c.unsubscribe()
c.unsubscribe = nil
}
c.handlerMu.Unlock()
// Destroy existing session if any
if c.session != nil {
if err := c.session.Destroy(); err != nil {
c.logger.Warn("error destroying previous session", zap.Error(err))
}
c.session = nil
}
c.logger.Info("resuming session",
zap.String("session_id", sessionID),
zap.Int("mcp_servers", len(mcpServers)))
// Get permission handler
c.permissionMu.RLock()
permHandler := c.permissionHandler
c.permissionMu.RUnlock()
// Use ResumeSessionWithOptions to enable streaming on resumed sessions
session, err := c.sdkClient.ResumeSessionWithOptions(sessionID, &copilot.ResumeSessionConfig{
Streaming: true,
OnPermissionRequest: permHandler,
MCPServers: mcpServers,
})
if err != nil {
return fmt.Errorf("failed to resume session: %w", err)
}
// Register event handler BEFORE storing the session so no events are lost.
c.handlerMu.Lock()
if c.eventHandler != nil {
c.unsubscribe = session.On(c.eventHandler)
}
c.handlerMu.Unlock()
c.session = session
c.sessionID = sessionID
c.logger.Info("session resumed", zap.String("session_id", sessionID))
return nil
}
// Send sends a message to the current session (non-blocking).
func (c *Client) Send(ctx context.Context, message string) (string, error) {
c.mu.RLock()
session := c.session
c.mu.RUnlock()
if session == nil {
return "", fmt.Errorf("no active session")
}
c.logger.Info("sending message to session")
messageID, err := session.Send(copilot.MessageOptions{
Prompt: message,
})
if err != nil {
return "", fmt.Errorf("failed to send message: %w", err)
}
return messageID, nil
}
// SendAndWait sends a message and waits for completion.
func (c *Client) SendAndWait(ctx context.Context, message string, timeout time.Duration) (*SessionEvent, error) {
c.mu.RLock()
session := c.session
c.mu.RUnlock()
if session == nil {
return nil, fmt.Errorf("no active session")
}
if timeout == 0 {
timeout = 5 * time.Minute
}
c.logger.Info("sending message and waiting for completion")
result, err := session.SendAndWait(copilot.MessageOptions{
Prompt: message,
}, timeout)
if err != nil {
return nil, fmt.Errorf("failed to send message: %w", err)
}
return result, nil
}
// Abort cancels the current operation.
func (c *Client) Abort(ctx context.Context) error {
c.mu.RLock()
session := c.session
c.mu.RUnlock()
if session == nil {
return nil
}
c.logger.Info("aborting current operation")
return session.Abort()
}
// GetSessionID returns the current session ID.
func (c *Client) GetSessionID() string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.sessionID
}
// IsStarted returns whether the client has been started.
func (c *Client) IsStarted() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.started
}
-814
View File
@@ -1,814 +0,0 @@
package opencode
import (
"bufio"
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/common/logger"
)
// SSE reconnection constants
const (
sseReconnectBaseDelay = 3 * time.Second
sseReconnectMaxDelay = 30 * time.Second
sseMaxRetries = 20
)
// Client manages HTTP communication with OpenCode server
type Client struct {
baseURL string
directory string
password string
httpClient *http.Client
logger *logger.Logger
// Event handling
eventHandler EventHandler
controlCh chan ControlEvent
// SSE connection tracking - prevents multiple concurrent connections
sseCancel context.CancelFunc
sseActive bool
lastEventID string // Last-Event-ID for reconnection
mu sync.RWMutex
closed bool
}
// EventHandler is called for each SDK event from the SSE stream
type EventHandler func(event *SDKEventEnvelope)
// ControlEvent represents control flow events
type ControlEvent struct {
Type string // "idle", "auth_required", "session_error", "disconnected"
Message string
}
// NewClient creates a new OpenCode HTTP client
func NewClient(baseURL, directory, password string, log *logger.Logger) *Client {
return &Client{
baseURL: strings.TrimSuffix(baseURL, "/"),
directory: directory,
password: password,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
logger: log,
controlCh: make(chan ControlEvent, 10),
}
}
// GenerateServerPassword generates a cryptographically secure random password
func GenerateServerPassword() string {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
// Fallback to a timestamp-based string if random fails
return fmt.Sprintf("opencode-%d", time.Now().UnixNano())
}
return base64.RawURLEncoding.EncodeToString(bytes)
}
// SetEventHandler sets the handler for SDK events
func (c *Client) SetEventHandler(handler EventHandler) {
c.mu.Lock()
defer c.mu.Unlock()
c.eventHandler = handler
}
// ControlChannel returns the channel for control events
func (c *Client) ControlChannel() <-chan ControlEvent {
return c.controlCh
}
// buildAuthHeader creates the Basic auth header value
func (c *Client) buildAuthHeader() string {
credentials := base64.StdEncoding.EncodeToString([]byte("opencode:" + c.password))
return "Basic " + credentials
}
// doRequest performs an HTTP request with auth headers
func (c *Client) doRequest(ctx context.Context, method, path string, body io.Reader) (*http.Response, error) {
url := c.baseURL + path
if strings.Contains(path, "?") {
url += "&directory=" + c.directory
} else {
url += "?directory=" + c.directory
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Authorization", c.buildAuthHeader())
req.Header.Set("X-OpenCode-Directory", c.directory)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
return c.httpClient.Do(req)
}
// doPromptRequest performs an HTTP request with a longer timeout suitable for prompts.
// Prompts can take minutes to complete, so we use a 60-minute timeout.
func (c *Client) doPromptRequest(ctx context.Context, method, path string, body io.Reader) (*http.Response, error) {
url := c.baseURL + path
if strings.Contains(path, "?") {
url += "&directory=" + c.directory
} else {
url += "?directory=" + c.directory
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Authorization", c.buildAuthHeader())
req.Header.Set("X-OpenCode-Directory", c.directory)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
// Use a client with extended timeout for prompts
promptClient := &http.Client{
Timeout: 60 * time.Minute,
}
return promptClient.Do(req)
}
// WaitForHealth waits for the OpenCode server to be healthy
func (c *Client) WaitForHealth(ctx context.Context) error {
deadline := time.Now().Add(20 * time.Second)
var lastErr error
for time.Now().Before(deadline) {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
resp, err := c.doRequest(ctx, http.MethodGet, "/global/health", nil)
if err != nil {
lastErr = err
c.logger.Debug("health check request failed", zap.Error(err))
time.Sleep(150 * time.Millisecond)
continue
}
// Read body for logging and parsing
bodyBytes, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
lastErr = fmt.Errorf("read health response: %w", err)
time.Sleep(150 * time.Millisecond)
continue
}
c.logger.Debug("health check response",
zap.Int("status", resp.StatusCode),
zap.String("body", string(bodyBytes)))
// Check HTTP status first
if resp.StatusCode != http.StatusOK {
lastErr = fmt.Errorf("health check HTTP %d: %s", resp.StatusCode, string(bodyBytes))
time.Sleep(150 * time.Millisecond)
continue
}
var health HealthResponse
if err := json.Unmarshal(bodyBytes, &health); err != nil {
lastErr = fmt.Errorf("parse health response (got: %q): %w", string(bodyBytes), err)
time.Sleep(150 * time.Millisecond)
continue
}
if health.Healthy {
c.logger.Info("OpenCode server healthy", zap.String("version", health.Version))
return nil
}
lastErr = fmt.Errorf("server unhealthy (version %s)", health.Version)
time.Sleep(150 * time.Millisecond)
}
if lastErr != nil {
return fmt.Errorf("health check timeout: %w", lastErr)
}
return fmt.Errorf("health check timeout")
}
// CreateSession creates a new OpenCode session
func (c *Client) CreateSession(ctx context.Context) (string, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/session", strings.NewReader("{}"))
if err != nil {
return "", fmt.Errorf("create session request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("create session failed: HTTP %d: %s", resp.StatusCode, string(body))
}
var session SessionResponse
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
return "", fmt.Errorf("parse session response: %w", err)
}
return session.ID, nil
}
// ForkSession forks an existing session for follow-up prompts
func (c *Client) ForkSession(ctx context.Context, sessionID string) (string, error) {
path := fmt.Sprintf("/session/%s/fork", sessionID)
resp, err := c.doRequest(ctx, http.MethodPost, path, strings.NewReader("{}"))
if err != nil {
return "", fmt.Errorf("fork session request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("fork session failed: HTTP %d: %s", resp.StatusCode, string(body))
}
var session SessionResponse
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
return "", fmt.Errorf("parse session response: %w", err)
}
return session.ID, nil
}
// SendPrompt sends a prompt to the session.
// This call blocks until OpenCode finishes processing the prompt.
func (c *Client) SendPrompt(ctx context.Context, sessionID, prompt string, model *ModelSpec, agent, variant string) error {
req := PromptRequest{
Model: model,
Agent: agent,
Variant: variant,
Parts: []TextPartInput{
{Type: "text", Text: prompt},
},
}
body, err := json.Marshal(req)
if err != nil {
return fmt.Errorf("marshal prompt request: %w", err)
}
c.logger.Debug("sending prompt HTTP request",
zap.String("session_id", sessionID),
zap.Int("body_len", len(body)))
path := fmt.Sprintf("/session/%s/message", sessionID)
resp, err := c.doPromptRequest(ctx, http.MethodPost, path, strings.NewReader(string(body)))
if err != nil {
return fmt.Errorf("send prompt request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read prompt response: %w", err)
}
c.logger.Debug("prompt HTTP response received",
zap.Int("status", resp.StatusCode),
zap.Int("body_len", len(respBody)))
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("prompt failed: HTTP %d: %s", resp.StatusCode, string(respBody))
}
trimmed := strings.TrimSpace(string(respBody))
if trimmed == "" {
return fmt.Errorf("prompt returned empty response")
}
var parsed map[string]any
if err := json.Unmarshal([]byte(trimmed), &parsed); err != nil {
return fmt.Errorf("parse prompt response: %w", err)
}
if _, hasInfo := parsed["info"]; hasInfo {
if _, hasParts := parsed["parts"]; hasParts {
return nil
}
}
if name, ok := parsed["name"].(string); ok {
message := "unknown error"
if data, ok := parsed["data"].(map[string]any); ok {
if msg, ok := data["message"].(string); ok {
message = msg
}
}
return fmt.Errorf("prompt error: %s: %s", name, message)
}
return nil
}
// Abort sends an abort request to stop the current operation
func (c *Client) Abort(ctx context.Context, sessionID string) error {
path := fmt.Sprintf("/session/%s/abort", sessionID)
// Use a short timeout for abort
abortCtx, cancel := context.WithTimeout(ctx, 800*time.Millisecond)
defer cancel()
resp, err := c.doRequest(abortCtx, http.MethodPost, path, nil)
if err != nil {
return nil // Ignore abort errors
}
defer func() { _ = resp.Body.Close() }()
// Drain body
_, _ = io.ReadAll(resp.Body)
return nil
}
// ReplyPermission sends a permission reply
func (c *Client) ReplyPermission(ctx context.Context, requestID, reply string, message *string) error {
payload := PermissionReplyRequest{
Reply: reply,
}
if message != nil {
payload.Message = *message
} else if reply == PermissionReplyReject {
// If rejecting without message, provide default
payload.Message = "User denied this tool use request"
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal permission reply: %w", err)
}
path := fmt.Sprintf("/permission/%s/reply", requestID)
resp, err := c.doRequest(ctx, http.MethodPost, path, strings.NewReader(string(body)))
if err != nil {
return fmt.Errorf("permission reply request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Drain body
_, _ = io.ReadAll(resp.Body)
return nil
}
// Summarize triggers compaction/summarization for a session.
func (c *Client) Summarize(ctx context.Context, sessionID string, model *ModelSpec) error {
payload := map[string]any{}
if model != nil {
payload["model"] = model
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal summarize request: %w", err)
}
path := fmt.Sprintf("/session/%s/summarize", sessionID)
resp, err := c.doPromptRequest(ctx, http.MethodPost, path, strings.NewReader(string(body)))
if err != nil {
return fmt.Errorf("summarize request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("summarize failed: HTTP %d: %s", resp.StatusCode, string(respBody))
}
_, _ = io.ReadAll(resp.Body)
return nil
}
// ListProviders fetches provider information including model context windows.
func (c *Client) ListProviders(ctx context.Context) (*ProviderListResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/provider", nil)
if err != nil {
return nil, fmt.Errorf("list providers request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("list providers failed: HTTP %d: %s", resp.StatusCode, string(body))
}
var result ProviderListResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("parse providers response: %w", err)
}
return &result, nil
}
// ListCommands fetches available slash commands from the server.
func (c *Client) ListCommands(ctx context.Context) ([]CommandInfo, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/command", nil)
if err != nil {
return nil, fmt.Errorf("list commands request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("list commands failed: HTTP %d: %s", resp.StatusCode, string(body))
}
var result []CommandInfo
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("parse commands response: %w", err)
}
return result, nil
}
// RunSessionCommand executes a slash command in a session.
func (c *Client) RunSessionCommand(ctx context.Context, sessionID, command string) error {
payload := map[string]string{"command": command}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal command request: %w", err)
}
path := fmt.Sprintf("/session/%s/command", sessionID)
resp, err := c.doPromptRequest(ctx, http.MethodPost, path, strings.NewReader(string(body)))
if err != nil {
return fmt.Errorf("run command request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
respBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("run command failed: HTTP %d: %s", resp.StatusCode, string(respBody))
}
_, _ = io.ReadAll(resp.Body)
return nil
}
// StartEventStream starts the SSE event stream and processes events.
// It ensures only one SSE connection is active at a time to prevent duplicate events.
// Supports automatic reconnection with Last-Event-ID for event resumption.
func (c *Client) StartEventStream(ctx context.Context, sessionID string) error {
c.mu.Lock()
if c.sseActive {
c.mu.Unlock()
c.logger.Debug("SSE stream already active, skipping duplicate connection",
zap.String("session_id", sessionID))
return nil
}
c.sseActive = true
c.mu.Unlock()
sseCtx, sseCancel := context.WithCancel(ctx)
c.mu.Lock()
c.sseCancel = sseCancel
c.mu.Unlock()
// Connect and start processing with reconnect support
if err := c.connectSSE(sseCtx, sessionID); err != nil {
c.mu.Lock()
c.sseActive = false
c.sseCancel = nil
c.mu.Unlock()
sseCancel()
return err
}
return nil
}
// connectSSE establishes the SSE connection and starts the event loop.
func (c *Client) connectSSE(ctx context.Context, sessionID string) error {
resp, err := c.dialSSE(ctx)
if err != nil {
return err
}
c.logger.Debug("SSE stream connected", zap.String("session_id", sessionID))
go c.sseEventLoop(ctx, sessionID, resp.Body)
return nil
}
// dialSSE creates and executes an SSE HTTP request, including Last-Event-ID if available.
func (c *Client) dialSSE(ctx context.Context) (*http.Response, error) {
url := c.baseURL + "/event?directory=" + c.directory
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("create event stream request: %w", err)
}
req.Header.Set("Authorization", c.buildAuthHeader())
req.Header.Set("X-OpenCode-Directory", c.directory)
req.Header.Set("Accept", "text/event-stream")
c.mu.RLock()
lastID := c.lastEventID
c.mu.RUnlock()
if lastID != "" {
req.Header.Set("Last-Event-ID", lastID)
}
sseClient := &http.Client{}
resp, err := sseClient.Do(req)
if err != nil {
return nil, fmt.Errorf("connect event stream: %w", err)
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return nil, fmt.Errorf("event stream failed: HTTP %d: %s", resp.StatusCode, string(body))
}
return resp, nil
}
// sseEventLoop reads SSE events, dispatches them, and reconnects on disconnect.
func (c *Client) sseEventLoop(ctx context.Context, sessionID string, body io.ReadCloser) {
defer func() {
c.mu.Lock()
c.sseActive = false
c.sseCancel = nil
c.mu.Unlock()
}()
for attempt := 0; ; attempt++ {
disconnectReason := c.readSSEStream(ctx, sessionID, body)
_ = body.Close()
if disconnectReason == sseDisconnectCancelled || disconnectReason == sseDisconnectClosed {
return
}
// Attempt reconnection with exponential backoff
if attempt >= sseMaxRetries {
c.logger.Warn("SSE max retries reached, giving up",
zap.Int("retries", attempt))
c.sendControlEvent("disconnected")
return
}
delay := sseBackoff(attempt)
c.logger.Info("SSE stream disconnected, reconnecting",
zap.Int("attempt", attempt+1),
zap.Duration("delay", delay))
select {
case <-ctx.Done():
return
case <-time.After(delay):
}
resp, err := c.dialSSE(ctx)
if err != nil {
c.logger.Warn("SSE reconnect failed", zap.Error(err), zap.Int("attempt", attempt+1))
continue
}
body = resp.Body
c.logger.Info("SSE stream reconnected", zap.Int("attempt", attempt+1))
}
}
// sseDisconnectReason indicates why the SSE stream ended.
type sseDisconnectReason int
const (
sseDisconnectError sseDisconnectReason = iota // network/scan error, should reconnect
sseDisconnectCancelled // context cancelled, no reconnect
sseDisconnectClosed // client closed, no reconnect
)
// readSSEStream reads events from a single SSE connection until it ends.
func (c *Client) readSSEStream(ctx context.Context, sessionID string, body io.Reader) sseDisconnectReason {
scanner := bufio.NewScanner(body)
buf := make([]byte, 0, 64*1024)
scanner.Buffer(buf, 1024*1024)
var dataBuffer strings.Builder
var currentID string
for scanner.Scan() {
select {
case <-ctx.Done():
return sseDisconnectCancelled
default:
}
line := scanner.Text()
// Track event ID for reconnection
if strings.HasPrefix(line, "id: ") {
currentID = strings.TrimPrefix(line, "id: ")
continue
}
if strings.HasPrefix(line, "data: ") {
dataBuffer.WriteString(strings.TrimPrefix(line, "data: "))
continue
}
if line == "" && dataBuffer.Len() > 0 {
data := strings.TrimSpace(dataBuffer.String())
dataBuffer.Reset()
// Update Last-Event-ID
if currentID != "" {
c.mu.Lock()
c.lastEventID = currentID
c.mu.Unlock()
currentID = ""
}
if data == "" {
continue
}
c.dispatchSSEEvent(data, sessionID)
}
}
if err := scanner.Err(); err != nil {
c.logger.Error("event stream error", zap.Error(err))
}
c.mu.RLock()
closed := c.closed
c.mu.RUnlock()
if closed {
return sseDisconnectClosed
}
return sseDisconnectError
}
// dispatchSSEEvent parses and dispatches a single SSE event.
func (c *Client) dispatchSSEEvent(data, sessionID string) {
event, err := ParseSDKEvent([]byte(data))
if err != nil {
c.logger.Warn("failed to parse SDK event", zap.Error(err))
return
}
c.logger.Debug("SSE event received",
zap.String("type", event.Type),
zap.String("session_id", sessionID))
if !c.eventMatchesSession(event, sessionID) {
c.logger.Debug("SSE event filtered (session mismatch)", zap.String("type", event.Type))
return
}
c.processControlEvent(event, sessionID)
c.mu.RLock()
handler := c.eventHandler
c.mu.RUnlock()
if handler != nil {
handler(event)
}
}
// sendControlEvent sends a control event if the client is not closed.
func (c *Client) sendControlEvent(eventType string) {
c.mu.RLock()
closed := c.closed
c.mu.RUnlock()
if !closed {
select {
case c.controlCh <- ControlEvent{Type: eventType}:
default:
}
}
}
// sseBackoff computes exponential backoff delay for SSE reconnection.
func sseBackoff(attempt int) time.Duration {
delay := sseReconnectBaseDelay
for i := 0; i < attempt; i++ {
delay *= 2
if delay > sseReconnectMaxDelay {
delay = sseReconnectMaxDelay
break
}
}
return delay
}
// eventMatchesSession checks if an event belongs to the specified session
func (c *Client) eventMatchesSession(event *SDKEventEnvelope, sessionID string) bool {
// Try to extract sessionID from properties
var props map[string]any
if event.Properties != nil {
if err := json.Unmarshal(event.Properties, &props); err != nil {
return true // If we can't parse, let it through
}
}
// Check various paths where sessionID might be
extractedID := ""
switch event.Type {
case SDKEventMessageUpdated:
if info, ok := props["info"].(map[string]any); ok {
if id, ok := info["sessionID"].(string); ok {
extractedID = id
}
}
case SDKEventMessagePartUpdated:
if part, ok := props["part"].(map[string]any); ok {
if id, ok := part["sessionID"].(string); ok {
extractedID = id
}
}
default:
if id, ok := props["sessionID"].(string); ok {
extractedID = id
}
}
if extractedID == "" {
return true // No sessionID in event, let it through
}
return extractedID == sessionID
}
// processControlEvent handles control flow events
func (c *Client) processControlEvent(event *SDKEventEnvelope, sessionID string) {
// Check if closed first to avoid panic on closed channel
c.mu.RLock()
closed := c.closed
c.mu.RUnlock()
if closed {
return
}
switch event.Type {
case SDKEventSessionIdle:
select {
case c.controlCh <- ControlEvent{Type: "idle"}:
default:
}
case SDKEventSessionError:
props, err := ParseSessionError(event.Properties)
if err != nil {
return
}
if props.Error != nil {
kind := props.Error.GetKind()
message := props.Error.GetMessage()
if kind == "ProviderAuthError" {
select {
case c.controlCh <- ControlEvent{Type: "auth_required", Message: message}:
default:
}
} else {
select {
case c.controlCh <- ControlEvent{Type: "session_error", Message: message}:
default:
}
}
}
}
}
// Close closes the client and terminates any active SSE connection
func (c *Client) Close() {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return
}
c.closed = true
// Cancel any active SSE connection
if c.sseCancel != nil {
c.sseCancel()
c.sseCancel = nil
}
c.sseActive = false
close(c.controlCh)
}
-465
View File
@@ -1,465 +0,0 @@
package opencode
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/kandev/kandev/internal/common/logger"
)
func newTestLogger() *logger.Logger {
log, _ := logger.NewLogger(logger.LoggingConfig{
Level: "error",
Format: "json",
})
return log
}
func TestGenerateServerPassword(t *testing.T) {
// Generate multiple passwords and ensure they're unique
passwords := make(map[string]bool)
for i := 0; i < 10; i++ {
pw := GenerateServerPassword()
if pw == "" {
t.Error("generated empty password")
}
if passwords[pw] {
t.Error("generated duplicate password")
}
passwords[pw] = true
}
}
func TestClient_BuildAuthHeader(t *testing.T) {
client := NewClient("http://localhost:8080", "/workspace", "test-password", newTestLogger())
header := client.buildAuthHeader()
if !strings.HasPrefix(header, "Basic ") {
t.Errorf("expected header to start with 'Basic ', got %s", header)
}
}
func TestClient_WaitForHealth(t *testing.T) {
tests := []struct {
name string
responses []HealthResponse
delays []time.Duration
wantError bool
}{
{
name: "healthy immediately",
responses: []HealthResponse{{Healthy: true, Version: "1.0.0"}},
delays: []time.Duration{0},
wantError: false,
},
{
name: "healthy after retry",
responses: []HealthResponse{
{Healthy: false, Version: "1.0.0"},
{Healthy: true, Version: "1.0.0"},
},
delays: []time.Duration{0, 0},
wantError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
callCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, "/global/health") {
http.Error(w, "not found", http.StatusNotFound)
return
}
if callCount < len(tt.delays) {
time.Sleep(tt.delays[callCount])
}
resp := tt.responses[callCount%len(tt.responses)]
callCount++
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}))
defer server.Close()
client := NewClient(server.URL, "/workspace", "test-password", newTestLogger())
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := client.WaitForHealth(ctx)
if tt.wantError && err == nil {
t.Error("expected error, got nil")
}
if !tt.wantError && err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
}
func TestClient_CreateSession(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !strings.Contains(r.URL.Path, "/session") {
http.Error(w, "not found", http.StatusNotFound)
return
}
// Check auth header
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Basic ") {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(SessionResponse{ID: "sess-123"})
}))
defer server.Close()
client := NewClient(server.URL, "/workspace", "test-password", newTestLogger())
ctx := context.Background()
sessionID, err := client.CreateSession(ctx)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if sessionID != "sess-123" {
t.Errorf("expected session ID 'sess-123', got %s", sessionID)
}
}
func TestClient_ForkSession(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !strings.Contains(r.URL.Path, "/session/sess-123/fork") {
http.Error(w, "not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(SessionResponse{ID: "sess-456"})
}))
defer server.Close()
client := NewClient(server.URL, "/workspace", "test-password", newTestLogger())
ctx := context.Background()
newSessionID, err := client.ForkSession(ctx, "sess-123")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if newSessionID != "sess-456" {
t.Errorf("expected session ID 'sess-456', got %s", newSessionID)
}
}
func TestClient_SendPrompt(t *testing.T) {
tests := []struct {
name string
statusCode int
response string
wantError bool
}{
{
name: "success",
statusCode: http.StatusOK,
response: `{"info":{},"parts":[]}`,
wantError: false,
},
{
name: "error response",
statusCode: http.StatusOK,
response: `{"name":"SomeError","data":{"message":"something went wrong"}}`,
wantError: true,
},
{
name: "http error",
statusCode: http.StatusInternalServerError,
response: `{"error":"internal error"}`,
wantError: true,
},
{
name: "empty response",
statusCode: http.StatusOK,
response: ``,
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tt.statusCode)
_, _ = fmt.Fprint(w, tt.response)
}))
defer server.Close()
client := NewClient(server.URL, "/workspace", "test-password", newTestLogger())
ctx := context.Background()
err := client.SendPrompt(ctx, "sess-123", "Hello", nil, "", "")
if tt.wantError && err == nil {
t.Error("expected error, got nil")
}
if !tt.wantError && err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
}
func TestClient_SendPrompt_WithModel(t *testing.T) {
var receivedBody PromptRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewDecoder(r.Body).Decode(&receivedBody)
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprint(w, `{"info":{},"parts":[]}`)
}))
defer server.Close()
client := NewClient(server.URL, "/workspace", "test-password", newTestLogger())
ctx := context.Background()
model := &ModelSpec{ProviderID: "anthropic", ModelID: "claude-3-sonnet"}
err := client.SendPrompt(ctx, "sess-123", "Hello", model, "coder", "default")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if receivedBody.Model == nil {
t.Error("expected model to be set")
} else if receivedBody.Model.ProviderID != "anthropic" {
t.Errorf("expected providerID 'anthropic', got %s", receivedBody.Model.ProviderID)
}
if receivedBody.Agent != "coder" {
t.Errorf("expected agent 'coder', got %s", receivedBody.Agent)
}
if receivedBody.Variant != "default" {
t.Errorf("expected variant 'default', got %s", receivedBody.Variant)
}
}
func TestClient_Abort(t *testing.T) {
aborted := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/abort") {
aborted = true
w.WriteHeader(http.StatusOK)
return
}
http.Error(w, "not found", http.StatusNotFound)
}))
defer server.Close()
client := NewClient(server.URL, "/workspace", "test-password", newTestLogger())
ctx := context.Background()
err := client.Abort(ctx, "sess-123")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !aborted {
t.Error("expected abort endpoint to be called")
}
}
func TestClient_ReplyPermission(t *testing.T) {
tests := []struct {
name string
reply string
message *string
}{
{
name: "allow once",
reply: PermissionReplyOnce,
message: nil,
},
{
name: "reject with message",
reply: PermissionReplyReject,
message: strPtr("User denied"),
},
{
name: "reject without message",
reply: PermissionReplyReject,
message: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var receivedBody PermissionReplyRequest
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewDecoder(r.Body).Decode(&receivedBody)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := NewClient(server.URL, "/workspace", "test-password", newTestLogger())
ctx := context.Background()
err := client.ReplyPermission(ctx, "perm-123", tt.reply, tt.message)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if receivedBody.Reply != tt.reply {
t.Errorf("expected reply %s, got %s", tt.reply, receivedBody.Reply)
}
if tt.message != nil {
if receivedBody.Message != *tt.message {
t.Errorf("expected message %s, got %s", *tt.message, receivedBody.Message)
}
} else if tt.reply == PermissionReplyReject {
// Should have default message
if receivedBody.Message == "" {
t.Error("expected default message for reject without message")
}
}
})
}
}
func TestClient_ControlChannel(t *testing.T) {
client := NewClient("http://localhost:8080", "/workspace", "test-password", newTestLogger())
ch := client.ControlChannel()
if ch == nil {
t.Error("expected control channel to be non-nil")
}
}
func TestClient_SetEventHandler(t *testing.T) {
client := NewClient("http://localhost:8080", "/workspace", "test-password", newTestLogger())
handler := func(event *SDKEventEnvelope) {
// Handler logic
}
client.SetEventHandler(handler)
// Access handler through the client - this is internal but we can test it works
client.mu.RLock()
h := client.eventHandler
client.mu.RUnlock()
if h == nil {
t.Error("expected event handler to be set")
}
}
func TestClient_Close(t *testing.T) {
client := NewClient("http://localhost:8080", "/workspace", "test-password", newTestLogger())
// First close should succeed
client.Close()
// Second close should be a no-op
client.Close()
// Client should be marked as closed
client.mu.RLock()
closed := client.closed
client.mu.RUnlock()
if !closed {
t.Error("expected client to be closed")
}
}
func TestClient_EventMatchesSession(t *testing.T) {
client := NewClient("http://localhost:8080", "/workspace", "test-password", newTestLogger())
tests := []struct {
name string
eventType string
props string
sessionID string
want bool
}{
{
name: "message.updated matches",
eventType: SDKEventMessageUpdated,
props: `{"info":{"sessionID":"sess-123"}}`,
sessionID: "sess-123",
want: true,
},
{
name: "message.updated doesn't match",
eventType: SDKEventMessageUpdated,
props: `{"info":{"sessionID":"sess-456"}}`,
sessionID: "sess-123",
want: false,
},
{
name: "message.part.updated matches",
eventType: SDKEventMessagePartUpdated,
props: `{"part":{"sessionID":"sess-123"}}`,
sessionID: "sess-123",
want: true,
},
{
name: "other event matches",
eventType: SDKEventSessionIdle,
props: `{"sessionID":"sess-123"}`,
sessionID: "sess-123",
want: true,
},
{
name: "no sessionID in event - matches",
eventType: SDKEventSessionIdle,
props: `{}`,
sessionID: "sess-123",
want: true,
},
{
name: "nil properties - matches",
eventType: SDKEventSessionIdle,
props: "",
sessionID: "sess-123",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var props json.RawMessage
if tt.props != "" {
props = json.RawMessage(tt.props)
}
event := &SDKEventEnvelope{
Type: tt.eventType,
Properties: props,
}
got := client.eventMatchesSession(event, tt.sessionID)
if got != tt.want {
t.Errorf("expected %v, got %v", tt.want, got)
}
})
}
}
func strPtr(s string) *string {
return &s
}
-365
View File
@@ -1,365 +0,0 @@
// Package opencode provides types and client for the OpenCode CLI protocol.
// OpenCode uses a REST API + Server-Sent Events (SSE) pattern for communication.
package opencode
import (
"encoding/json"
)
// ExecutorEvent types written to adapter output
const (
EventTypeStartupLog = "startup_log"
EventTypeSessionStart = "session_start"
EventTypeSDKEvent = "sdk_event"
EventTypeTokenUsage = "token_usage"
EventTypeApprovalResponse = "approval_response"
EventTypeError = "error"
EventTypeDone = "done"
)
// SDK Event types from /event SSE stream
const (
SDKEventMessageUpdated = "message.updated"
SDKEventMessagePartUpdated = "message.part.updated"
SDKEventMessageRemoved = "message.removed"
SDKEventMessagePartRemoved = "message.part.removed"
SDKEventPermissionAsked = "permission.asked"
SDKEventPermissionReplied = "permission.replied"
SDKEventSessionIdle = "session.idle"
SDKEventSessionStatus = "session.status"
SDKEventSessionDiff = "session.diff"
SDKEventSessionCompacted = "session.compacted"
SDKEventSessionError = "session.error"
SDKEventTodoUpdated = "todo.updated"
)
// Part types
const (
PartTypeText = "text"
PartTypeReasoning = "reasoning"
PartTypeTool = "tool"
)
// Tool status values
const (
ToolStatusPending = "pending"
ToolStatusRunning = "running"
ToolStatusCompleted = "completed"
ToolStatusError = "error"
)
// Permission reply values
const (
PermissionReplyOnce = "once"
PermissionReplyReject = "reject"
)
// ExecutorEvent represents events written to stdout by the adapter
type ExecutorEvent struct {
Type string `json:"type"`
// Variant fields based on type
Message string `json:"message,omitempty"`
SessionID string `json:"session_id,omitempty"`
Event json.RawMessage `json:"event,omitempty"`
TotalTokens int `json:"total_tokens,omitempty"`
ModelContextWindow int `json:"model_context_window,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
Status string `json:"status,omitempty"`
}
// HealthResponse from GET /global/health
type HealthResponse struct {
Healthy bool `json:"healthy"`
Version string `json:"version"`
}
// SessionResponse from POST /session or POST /session/{id}/fork
type SessionResponse struct {
ID string `json:"id"`
}
// ModelSpec for prompt requests
type ModelSpec struct {
ProviderID string `json:"providerID"`
ModelID string `json:"modelID"`
}
// TextPartInput for prompt request parts
type TextPartInput struct {
Type string `json:"type"`
Text string `json:"text"`
}
// PromptRequest for POST /session/{id}/message
type PromptRequest struct {
Model *ModelSpec `json:"model,omitempty"`
Agent string `json:"agent,omitempty"`
Variant string `json:"variant,omitempty"`
Parts []TextPartInput `json:"parts"`
}
// PermissionReplyRequest for POST /permission/{id}/reply
type PermissionReplyRequest struct {
Reply string `json:"reply"`
Message string `json:"message,omitempty"`
}
// SDKEventEnvelope is the base structure for all SSE events
type SDKEventEnvelope struct {
Type string `json:"type"`
Properties json.RawMessage `json:"properties,omitempty"`
}
// MessageUpdatedProperties for message.updated events
type MessageUpdatedProperties struct {
Info MessageInfo `json:"info"`
}
// MessageInfo contains message metadata
type MessageInfo struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Role string `json:"role"` // "user", "assistant"
Model *MessageModelInfo `json:"model,omitempty"`
ProviderID string `json:"providerID,omitempty"`
ModelID string `json:"modelID,omitempty"`
Tokens *MessageTokensInfo `json:"tokens,omitempty"`
}
// MessageModelInfo contains model information
type MessageModelInfo struct {
ProviderID string `json:"providerID"`
ModelID string `json:"modelID"`
}
// MessageTokensInfo contains token usage information
type MessageTokensInfo struct {
Input int `json:"input"`
Output int `json:"output"`
Cache *MessageTokensCacheInfo `json:"cache,omitempty"`
}
// MessageTokensCacheInfo contains cache token information
type MessageTokensCacheInfo struct {
Read int `json:"read"`
}
// MessagePartUpdatedProperties for message.part.updated events
type MessagePartUpdatedProperties struct {
Part Part `json:"part"`
Delta string `json:"delta,omitempty"`
}
// Part represents a message part (text, reasoning, or tool)
type Part struct {
ID string `json:"id"` // Unique part identifier for tracking updates
Type string `json:"type"` // "text", "reasoning", "tool"
MessageID string `json:"messageID"`
SessionID string `json:"sessionID"`
Text string `json:"text,omitempty"` // For text/reasoning
CallID string `json:"callID,omitempty"` // For tool
Tool string `json:"tool,omitempty"` // For tool
State *ToolStateUpdate `json:"state,omitempty"` // For tool
}
// ToolStateUpdate represents tool execution state
type ToolStateUpdate struct {
Status string `json:"status"` // "pending", "running", "completed", "error"
Input json.RawMessage `json:"input,omitempty"`
Output string `json:"output,omitempty"`
Title string `json:"title,omitempty"`
Error string `json:"error,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
// PermissionAskedProperties for permission.asked events
type PermissionAskedProperties struct {
ID string `json:"id"`
SessionID string `json:"sessionID"`
Permission string `json:"permission"`
Patterns []string `json:"patterns,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Tool *PermissionToolInfo `json:"tool,omitempty"`
}
// PermissionToolInfo contains tool information for permission requests
type PermissionToolInfo struct {
CallID string `json:"callID"`
}
// SessionIdleProperties for session.idle events
type SessionIdleProperties struct {
SessionID string `json:"sessionID"`
}
// SessionErrorProperties for session.error events
type SessionErrorProperties struct {
SessionID string `json:"sessionID"`
Error *SDKError `json:"error,omitempty"`
}
// SDKError represents an error from the SDK
type SDKError struct {
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Message string `json:"message,omitempty"`
Data *struct {
Message string `json:"message,omitempty"`
} `json:"data,omitempty"`
}
// GetMessage returns the error message
func (e *SDKError) GetMessage() string {
if e.Data != nil && e.Data.Message != "" {
return e.Data.Message
}
return e.Message
}
// GetKind returns the error kind/type
func (e *SDKError) GetKind() string {
if e.Name != "" {
return e.Name
}
if e.Type != "" {
return e.Type
}
return "unknown"
}
// SessionStatusProperties for session.status events
type SessionStatusProperties struct {
Status SessionStatus `json:"status"`
}
// SessionStatus represents session status
type SessionStatus struct {
Type string `json:"type"` // "idle", "busy", "retry"
Attempt int `json:"attempt,omitempty"`
Message string `json:"message,omitempty"`
Next int64 `json:"next,omitempty"`
}
// TodoUpdatedProperties for todo.updated events
type TodoUpdatedProperties struct {
Todos []SDKTodo `json:"todos"`
}
// SDKTodo represents a todo item
type SDKTodo struct {
ID string `json:"id"`
Content string `json:"content"`
Status string `json:"status"`
Priority string `json:"priority"`
}
// CommandInfo represents a slash command from GET /command.
type CommandInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
// Some commands have structured input
Input *CommandInputInfo `json:"input,omitempty"`
}
// CommandInputInfo describes command input expectations.
type CommandInputInfo struct {
Hint string `json:"hint,omitempty"`
}
// ProviderListResponse from GET /provider
type ProviderListResponse struct {
All []ProviderInfo `json:"all"`
}
// ProviderInfo contains provider information
type ProviderInfo struct {
ID string `json:"id"`
Models map[string]ProviderModelInfo `json:"models,omitempty"`
}
// ProviderModelInfo contains model information from provider
type ProviderModelInfo struct {
Limit ProviderModelLimit `json:"limit"`
}
// ProviderModelLimit contains model limits
type ProviderModelLimit struct {
Context int `json:"context"`
}
// SessionCompactedProperties for session.compacted events
type SessionCompactedProperties struct {
SessionID string `json:"sessionID"`
}
// ParseSessionCompacted parses session.compacted properties
func ParseSessionCompacted(data json.RawMessage) (*SessionCompactedProperties, error) {
var props SessionCompactedProperties
if err := json.Unmarshal(data, &props); err != nil {
return nil, err
}
return &props, nil
}
// ParseTodoUpdated parses todo.updated properties
func ParseTodoUpdated(data json.RawMessage) (*TodoUpdatedProperties, error) {
var props TodoUpdatedProperties
if err := json.Unmarshal(data, &props); err != nil {
return nil, err
}
return &props, nil
}
// ParseSDKEvent parses an SDK event from JSON
func ParseSDKEvent(data []byte) (*SDKEventEnvelope, error) {
var env SDKEventEnvelope
if err := json.Unmarshal(data, &env); err != nil {
return nil, err
}
return &env, nil
}
// ParseMessageUpdated parses message.updated properties
func ParseMessageUpdated(data json.RawMessage) (*MessageUpdatedProperties, error) {
var props MessageUpdatedProperties
if err := json.Unmarshal(data, &props); err != nil {
return nil, err
}
return &props, nil
}
// ParseMessagePartUpdated parses message.part.updated properties
func ParseMessagePartUpdated(data json.RawMessage) (*MessagePartUpdatedProperties, error) {
var props MessagePartUpdatedProperties
if err := json.Unmarshal(data, &props); err != nil {
return nil, err
}
return &props, nil
}
// ParsePermissionAsked parses permission.asked properties
func ParsePermissionAsked(data json.RawMessage) (*PermissionAskedProperties, error) {
var props PermissionAskedProperties
if err := json.Unmarshal(data, &props); err != nil {
return nil, err
}
return &props, nil
}
// ParseSessionIdle parses session.idle properties
func ParseSessionIdle(data json.RawMessage) (*SessionIdleProperties, error) {
var props SessionIdleProperties
if err := json.Unmarshal(data, &props); err != nil {
return nil, err
}
return &props, nil
}
// ParseSessionError parses session.error properties
func ParseSessionError(data json.RawMessage) (*SessionErrorProperties, error) {
var props SessionErrorProperties
if err := json.Unmarshal(data, &props); err != nil {
return nil, err
}
return &props, nil
}
-366
View File
@@ -1,366 +0,0 @@
package opencode
import (
"encoding/json"
"testing"
)
func TestSDKEventEnvelope_ParseSDKEvent(t *testing.T) {
tests := []struct {
name string
input string
wantType string
wantError bool
}{
{
name: "message.updated event",
input: `{"type":"message.updated","properties":{"info":{"id":"123","sessionID":"sess-1","role":"assistant"}}}`,
wantType: SDKEventMessageUpdated,
},
{
name: "message.part.updated event",
input: `{"type":"message.part.updated","properties":{"part":{"type":"text","text":"hello"}}}`,
wantType: SDKEventMessagePartUpdated,
},
{
name: "permission.asked event",
input: `{"type":"permission.asked","properties":{"id":"perm-1","sessionID":"sess-1","permission":"edit"}}`,
wantType: SDKEventPermissionAsked,
},
{
name: "session.idle event",
input: `{"type":"session.idle","properties":{"sessionID":"sess-1"}}`,
wantType: SDKEventSessionIdle,
},
{
name: "session.error event",
input: `{"type":"session.error","properties":{"sessionID":"sess-1","error":{"message":"something went wrong"}}}`,
wantType: SDKEventSessionError,
},
{
name: "invalid JSON",
input: `{invalid`,
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
event, err := ParseSDKEvent([]byte(tt.input))
if tt.wantError {
if err == nil {
t.Error("expected error, got nil")
}
return
}
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
if event.Type != tt.wantType {
t.Errorf("expected type %s, got %s", tt.wantType, event.Type)
}
})
}
}
func TestParseMessageUpdated(t *testing.T) {
input := `{"info":{"id":"msg-123","sessionID":"sess-456","role":"assistant","model":{"providerID":"anthropic","modelID":"claude-3-sonnet"},"tokens":{"input":100,"output":50,"cache":{"read":20}}}}`
props, err := ParseMessageUpdated(json.RawMessage(input))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if props.Info.ID != "msg-123" {
t.Errorf("expected ID 'msg-123', got %s", props.Info.ID)
}
if props.Info.SessionID != "sess-456" {
t.Errorf("expected sessionID 'sess-456', got %s", props.Info.SessionID)
}
if props.Info.Role != "assistant" {
t.Errorf("expected role 'assistant', got %s", props.Info.Role)
}
if props.Info.Model == nil {
t.Error("expected model to be set")
} else if props.Info.Model.ProviderID != "anthropic" {
t.Errorf("expected providerID 'anthropic', got %s", props.Info.Model.ProviderID)
}
if props.Info.Tokens == nil {
t.Error("expected tokens to be set")
} else {
if props.Info.Tokens.Input != 100 {
t.Errorf("expected input tokens 100, got %d", props.Info.Tokens.Input)
}
if props.Info.Tokens.Output != 50 {
t.Errorf("expected output tokens 50, got %d", props.Info.Tokens.Output)
}
if props.Info.Tokens.Cache == nil || props.Info.Tokens.Cache.Read != 20 {
t.Error("expected cache read 20")
}
}
}
func TestParseMessagePartUpdated(t *testing.T) {
tests := []struct {
name string
input string
wantType string
wantText string
wantID string
}{
{
name: "text part with ID",
input: `{"part":{"id":"part-123","type":"text","messageID":"msg-1","sessionID":"sess-1","text":"Hello world"},"delta":"Hello"}`,
wantType: PartTypeText,
wantText: "Hello world",
wantID: "part-123",
},
{
name: "text part without ID (backwards compatibility)",
input: `{"part":{"type":"text","messageID":"msg-1","sessionID":"sess-1","text":"Hello world"},"delta":"Hello"}`,
wantType: PartTypeText,
wantText: "Hello world",
wantID: "",
},
{
name: "reasoning part",
input: `{"part":{"id":"reason-1","type":"reasoning","messageID":"msg-1","sessionID":"sess-1","text":"Let me think..."}}`,
wantType: PartTypeReasoning,
wantText: "Let me think...",
wantID: "reason-1",
},
{
name: "tool part",
input: `{"part":{"id":"tool-1","type":"tool","messageID":"msg-1","sessionID":"sess-1","callID":"call-1","tool":"bash","state":{"status":"running","title":"Running command"}}}`,
wantType: PartTypeTool,
wantID: "tool-1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
props, err := ParseMessagePartUpdated(json.RawMessage(tt.input))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if props.Part.Type != tt.wantType {
t.Errorf("expected type %s, got %s", tt.wantType, props.Part.Type)
}
if tt.wantText != "" && props.Part.Text != tt.wantText {
t.Errorf("expected text %q, got %q", tt.wantText, props.Part.Text)
}
if props.Part.ID != tt.wantID {
t.Errorf("expected ID %q, got %q", tt.wantID, props.Part.ID)
}
})
}
}
func TestParsePermissionAsked(t *testing.T) {
input := `{"id":"perm-123","sessionID":"sess-456","permission":"bash","patterns":["npm run *"],"metadata":{"command":"npm run test"},"tool":{"callID":"call-789"}}`
props, err := ParsePermissionAsked(json.RawMessage(input))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if props.ID != "perm-123" {
t.Errorf("expected ID 'perm-123', got %s", props.ID)
}
if props.SessionID != "sess-456" {
t.Errorf("expected sessionID 'sess-456', got %s", props.SessionID)
}
if props.Permission != "bash" {
t.Errorf("expected permission 'bash', got %s", props.Permission)
}
if len(props.Patterns) != 1 || props.Patterns[0] != "npm run *" {
t.Errorf("expected patterns [npm run *], got %v", props.Patterns)
}
if props.Tool == nil || props.Tool.CallID != "call-789" {
t.Error("expected tool with callID 'call-789'")
}
if cmd, ok := props.Metadata["command"].(string); !ok || cmd != "npm run test" {
t.Errorf("expected metadata command 'npm run test', got %v", props.Metadata)
}
}
func TestParseSessionIdle(t *testing.T) {
input := `{"sessionID":"sess-123"}`
props, err := ParseSessionIdle(json.RawMessage(input))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if props.SessionID != "sess-123" {
t.Errorf("expected sessionID 'sess-123', got %s", props.SessionID)
}
}
func TestParseSessionError(t *testing.T) {
tests := []struct {
name string
input string
wantKind string
wantMessage string
}{
{
name: "error with name and data.message",
input: `{"sessionID":"sess-1","error":{"name":"ProviderAuthError","data":{"message":"API key invalid"}}}`,
wantKind: "ProviderAuthError",
wantMessage: "API key invalid",
},
{
name: "error with type and message",
input: `{"sessionID":"sess-1","error":{"type":"RateLimitError","message":"Rate limit exceeded"}}`,
wantKind: "RateLimitError",
wantMessage: "Rate limit exceeded",
},
{
name: "no error",
input: `{"sessionID":"sess-1"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
props, err := ParseSessionError(json.RawMessage(tt.input))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tt.wantKind == "" {
if props.Error != nil {
t.Error("expected no error, but got one")
}
return
}
if props.Error == nil {
t.Fatal("expected error, got nil")
}
if props.Error.GetKind() != tt.wantKind {
t.Errorf("expected kind %s, got %s", tt.wantKind, props.Error.GetKind())
}
if props.Error.GetMessage() != tt.wantMessage {
t.Errorf("expected message %s, got %s", tt.wantMessage, props.Error.GetMessage())
}
})
}
}
func TestSDKError_GetKind(t *testing.T) {
tests := []struct {
name string
err SDKError
wantKind string
}{
{
name: "name takes precedence",
err: SDKError{Name: "AuthError", Type: "SomeType"},
wantKind: "AuthError",
},
{
name: "falls back to type",
err: SDKError{Type: "SomeType"},
wantKind: "SomeType",
},
{
name: "returns unknown",
err: SDKError{},
wantKind: "unknown",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.err.GetKind(); got != tt.wantKind {
t.Errorf("expected kind %s, got %s", tt.wantKind, got)
}
})
}
}
func TestSDKError_GetMessage(t *testing.T) {
tests := []struct {
name string
err SDKError
wantMessage string
}{
{
name: "data.message takes precedence",
err: SDKError{
Message: "outer message",
Data: &struct {
Message string `json:"message,omitempty"`
}{Message: "inner message"},
},
wantMessage: "inner message",
},
{
name: "falls back to message",
err: SDKError{Message: "outer message"},
wantMessage: "outer message",
},
{
name: "returns empty",
err: SDKError{},
wantMessage: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.err.GetMessage(); got != tt.wantMessage {
t.Errorf("expected message %s, got %s", tt.wantMessage, got)
}
})
}
}
func TestToolStateUpdate_Statuses(t *testing.T) {
tests := []struct {
status string
}{
{ToolStatusPending},
{ToolStatusRunning},
{ToolStatusCompleted},
{ToolStatusError},
}
for _, tt := range tests {
t.Run(tt.status, func(t *testing.T) {
state := ToolStateUpdate{Status: tt.status}
if state.Status != tt.status {
t.Errorf("expected status %s, got %s", tt.status, state.Status)
}
})
}
}
func TestExecutorEvent_JSON(t *testing.T) {
event := ExecutorEvent{
Type: EventTypeSessionStart,
SessionID: "sess-123",
}
data, err := json.Marshal(event)
if err != nil {
t.Fatalf("failed to marshal: %v", err)
}
var parsed ExecutorEvent
if err := json.Unmarshal(data, &parsed); err != nil {
t.Fatalf("failed to unmarshal: %v", err)
}
if parsed.Type != event.Type {
t.Errorf("expected type %s, got %s", event.Type, parsed.Type)
}
if parsed.SessionID != event.SessionID {
t.Errorf("expected sessionID %s, got %s", event.SessionID, parsed.SessionID)
}
}
-587
View File
@@ -1,587 +0,0 @@
# Claude Code Integration
Technical reference for Kandev's Claude Code CLI integration. Covers the stream-json protocol, message lifecycle, control plane, tool normalization, session resume, and permission hooks.
## Protocol Overview
Kandev communicates with Claude Code via the **stream-json** protocol: newline-delimited JSON over stdin/stdout. The CLI runs as a subprocess managed by agentctl.
```
┌─────────────┐ stdin (JSON lines) ┌──────────────────┐
│ agentctl │ ──────────────────► │ Claude Code CLI │
│ (adapter) │ ◄────────────────── │ (subprocess) │
└─────────────┘ stdout (JSON lines) └──────────────────┘
```
**CLI invocation:**
```
npx -y @anthropic-ai/claude-code@<version>
-p # Print mode (non-interactive)
--output-format=stream-json # Streaming JSON output
--input-format=stream-json # Streaming JSON input
--permission-prompt-tool=stdio # Permission prompts via stdio control messages
--include-partial-messages # Stream in-progress assistant messages
--replay-user-messages # Replay user messages on session resume
--verbose # Extended logging
--model <model> # Model selection
--resume <session-id> # Resume existing session
```
---
## Architecture
```
pkg/claudecode/
├── types.go # Protocol message types, constants, structs
└── client.go # stdin/stdout client, read loop, control request handling
internal/agentctl/server/adapter/transport/streamjson/
├── adapter.go # Main adapter: state, dispatch, sendUpdate
├── streamjson_init.go # Initialize, hooks, MCP config
├── streamjson_session.go # NewSession / LoadSession
├── streamjson_prompt.go # Prompt sending, image attachments, Cancel
├── streamjson_messages.go # System, assistant, user, rate-limit handlers
├── streamjson_result.go # Result handler, deduplication, completion
├── streamjson_permissions.go # Permission requests, hook callbacks, timeout
├── streamjson_tracing.go # OTel tracing helpers for control messages
└── normalize.go # Tool data → NormalizedPayload conversion
```
---
## Message Types
Every line on stdout is a JSON object with a `type` field. The client dispatches based on this type:
| Type | Direction | Description |
|------|-----------|-------------|
| `system` | CLI → Adapter | Session initialization (session_id, status, slash commands) |
| `assistant` | CLI → Adapter | Assistant response with content blocks (text, thinking, tool_use) |
| `user` | CLI → Adapter | Tool results (tool_result blocks) or slash command output |
| `result` | CLI → Adapter | Turn completion with stats (cost, tokens, duration, errors) |
| `rate_limit` | CLI → Adapter | API rate limit notification |
| `control_request` | CLI → Adapter | Permission request or hook callback |
| `control_cancel_request` | CLI → Adapter | Cancels a pending permission/hook request |
| `control_response` | Adapter → CLI | Response to a control_request |
---
## Message Lifecycle
### Client Layer (`pkg/claudecode/client.go`)
The `Client` reads stdout via `bufio.Scanner` (10 MB buffer), parses each line into a `CLIMessage`, and dispatches:
```
stdout line
│
├── type=control_request → RequestHandler(requestID, *ControlRequest)
├── type=control_cancel_request → CancelHandler(requestID)
├── type=control_response → matches pending request by ID, unblocks goroutine
└── (all other types) → MessageHandler(*CLIMessage)
```
Control messages are handled immediately. All other messages are forwarded to the adapter's `handleMessage()`.
### Adapter Layer (`streamjson/adapter.go`)
The adapter's `handleMessage()` marshals the message for debug logging/tracing, then dispatches:
```
handleMessage(msg)
│
├── system → handleSystemMessage → session_status, available_commands
├── assistant → handleAssistantMessage → message_chunk, reasoning, tool_call, context_window
├── user → handleUserMessage → tool_update (complete/error), message_chunk (slash cmds)
├── result → handleResultMessage → complete, error (+ auto-complete pending tools)
└── rate_limit → handleRateLimitMessage → rate_limit
```
Every dispatched event goes through `sendUpdate()`, which:
1. Logs the normalized event (JSONL debug file)
2. Creates an OTel span (child of the active prompt span)
3. Sends to the `updatesCh` channel for WebSocket delivery
---
## Turn Anatomy
A single turn (prompt → result) produces this message sequence:
```
Adapter Claude Code CLI
│ │
│ ── user message (prompt) ──────────► │
│ │
│ ◄── system (session_id, status) ──── │ (first prompt only)
│ ◄── assistant (text blocks) ──────── │ (streaming chunks)
│ ◄── assistant (thinking blocks) ──── │ (reasoning, if enabled)
│ ◄── assistant (tool_use block) ───── │ (tool invocation)
│ │
│ ◄── control_request (can_use_tool) ─ │ (if hooks require approval)
│ ── control_response (allow/deny) ──► │
│ │
│ ◄── user (tool_result block) ─────── │ (tool output)
│ ◄── assistant (text blocks) ──────── │ (more streaming)
│ ◄── result ───────────────────────── │ (turn complete)
│ │
```
### Text Deduplication
The `result` message may contain a `text` field that duplicates already-streamed assistant text. The adapter tracks `streamingTextSentThisTurn`:
- Set to `true` when any `message_chunk` event is sent from assistant text blocks
- If `true` when result arrives, `result.text` is skipped
- Reset to `false` after each result
### Message UUIDs
Each message has a `uuid` field used for session truncation on resume:
- **Assistant UUIDs** are held as `pendingAssistantUUID` until the result message commits them to `lastMessageUUID`
- **User UUIDs** are committed immediately (safe to resume from)
- `lastMessageUUID` is included in the `complete` event and persisted for `--resume-session-at`
---
## Content Blocks
Assistant messages contain an array of content blocks:
### Text Block
```json
{ "type": "text", "text": "Here's the implementation..." }
```
Emitted as `message_chunk` events for real-time streaming.
### Thinking Block
```json
{ "type": "thinking", "thinking": "Let me analyze the code structure..." }
```
Emitted as `reasoning` events. Only present when extended thinking is enabled.
### Tool Use Block
```json
{
"type": "tool_use",
"id": "toolu_abc123",
"name": "Edit",
"input": { "file_path": "/src/main.go", "old_string": "...", "new_string": "..." }
}
```
Normalized into a `NormalizedPayload` and emitted as a `tool_call` event with status `"running"`.
### Tool Result Block (in user messages)
```json
{
"type": "tool_result",
"tool_use_id": "toolu_abc123",
"content": "File edited successfully",
"is_error": false
}
```
Enriches the pending `NormalizedPayload` with output data and emits a `tool_update` event with status `"complete"` or `"error"`.
---
## Control Plane
### Initialize
Sent once after the subprocess starts. Registers hooks and retrieves available slash commands.
```
Adapter → CLI:
{
"type": "control_request",
"request_id": "<uuid>",
"request": {
"subtype": "initialize",
"hooks": {
"PreToolUse": [{ "matcher": "^Bash$", "hookCallbackIds": ["tool_approval"] }],
"Stop": [{ "hookCallbackIds": ["stop_git_check"] }]
}
}
}
CLI → Adapter:
{
"type": "control_response",
"response": {
"subtype": "success",
"request_id": "<uuid>",
"response": {
"commands": [
{ "name": "commit", "description": "Create a git commit" },
{ "name": "review-pr", "description": "Review a pull request" }
]
}
}
}
```
### Permission Request (can_use_tool)
When the CLI needs approval for a tool call:
```
CLI → Adapter:
{
"type": "control_request",
"request_id": "req_123",
"request": {
"subtype": "can_use_tool",
"tool_name": "Bash",
"tool_use_id": "toolu_abc",
"input": { "command": "rm -rf /tmp/test" },
"blocked_paths": "/etc,/usr"
}
}
Adapter → CLI:
{
"type": "control_response",
"request_id": "req_123",
"response": {
"subtype": "success",
"result": {
"behavior": "allow",
"updatedPermissions": [],
"message": ""
}
}
}
```
The `behavior` field is `"allow"` or `"deny"`. On deny, an optional `interrupt: true` stops the current operation.
### Hook Callbacks
Hooks are registered during initialize and fire before tool execution. The response format differs from permission responses:
**PreToolUse hook response:**
```json
{
"type": "control_response",
"request_id": "req_456",
"response": {
"subtype": "success",
"result": {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "Auto-approved by SDK"
}
}
}
}
```
`permissionDecision` values:
- `"allow"` — approve the tool call
- `"deny"` — reject the tool call
- `"ask"` — trigger a separate `can_use_tool` permission request
**Stop hook response:**
```json
{
"type": "control_response",
"request_id": "req_789",
"response": {
"subtype": "success",
"result": {
"decision": "approve",
"reason": ""
}
}
}
```
### Cancel Request
The CLI can cancel a pending permission dialog (e.g., when the tool call is superseded):
```
CLI → Adapter:
{
"type": "control_cancel_request",
"request_id": "req_123"
}
```
The adapter emits a `permission_cancelled` event so the frontend closes the dialog.
### Interrupt
Sent by the adapter to cancel the current operation:
```
Adapter → CLI:
{
"type": "control_request",
"request_id": "<uuid>",
"request": { "subtype": "interrupt" }
}
```
---
## Permission Modes
The adapter supports three permission policies, configured via hooks at initialize:
### Autonomous (default)
No hooks registered. `--dangerously-skip-permissions` flag bypasses all checks. Agent runs freely.
### Supervised
Uses `--permission-mode=bypassPermissions` with hooks:
- **PreToolUse hook**: Matches all tools except safe read-only ones (`Glob`, `Grep`, `NotebookRead`, `Read`, `Task`, `TodoWrite`). Responds with `permissionDecision: "ask"` which triggers a `can_use_tool` flow, forwarding to the frontend for user approval.
- **Stop hook**: Checks for uncommitted changes before agent exit.
- Non-matching tools (read-only) are implicitly auto-approved by Claude Code.
### Plan
Uses `--permission-mode=bypassPermissions` with hooks:
- **PreToolUse hook (ExitPlanMode)**: Requires approval to exit plan mode.
- **PreToolUse hook (everything else)**: Auto-approved.
- **Stop hook**: Same as supervised.
---
## Result Message
The result message signals turn completion and contains aggregate statistics:
```json
{
"type": "result",
"subtype": "success",
"cost_usd": 0.0234,
"duration_ms": 15234,
"duration_api_ms": 12100,
"is_error": false,
"num_turns": 3,
"total_input_tokens": 45000,
"total_output_tokens": 2300,
"model_usage": {
"claude-sonnet-4-5": { "context_window": 200000 }
},
"result": {
"text": "I've implemented the changes...",
"session_id": "sess_abc123"
}
}
```
On result, the adapter:
1. Auto-completes any pending tool calls that never received a `tool_result`
2. Updates context window size from `model_usage` if available
3. Emits result text only if no streaming text was sent this turn
4. Commits the pending assistant UUID as `lastMessageUUID`
5. Emits `complete` event with cost/token/duration stats
6. Signals completion to unblock the `Prompt()` goroutine
7. Emits `error` event if `is_error: true`
---
## Session Resume
### Resume by Session ID
```
--resume <session-id>
```
Resumes the conversation from the last message. The session ID is stored in the `executors_running` table as the resume token.
### Resume at Message UUID
```
--resume-session-at <message-uuid>
```
Truncates the conversation to the specified message UUID and resumes from there. Used for retry — when a turn fails, resume from the last known-good message instead of replaying the failed context.
The `lastMessageUUID` is:
- Tracked from message `uuid` fields during the conversation
- Committed on result messages (assistant UUIDs are pending until result confirms success)
- Included in the `complete` event's `data.last_message_uuid` field
- Persisted in the `executors_running.last_message_uuid` column
---
## Tool Normalization
The normalizer converts Claude Code tool calls into protocol-agnostic `NormalizedPayload` structs. This allows the frontend to render tools uniformly regardless of which agent produced them.
### Tool → Kind Mapping
| Claude Code Tool | NormalizedPayload Kind | Frontend Renderer |
|-----------------|----------------------|-------------------|
| `Edit`, `Write`, `NotebookEdit` | `modify_file` | `tool_edit` |
| `Read` | `read_file` | `tool_read` |
| `Glob`, `Grep` | `code_search` | `tool_search` |
| `Bash` | `shell_exec` | `tool_execute` |
| `WebFetch`, `WebSearch` | `http_request` | `tool_call` |
| `Task` | `subagent_task` | `tool_call` |
| `TaskCreate` | `create_task` | `tool_call` |
| `TaskUpdate`, `TaskList`, `TodoWrite` | `manage_todos` | `todo` |
| (unknown) | `generic` | `tool_call` |
### Normalization Flow
```
tool_use block (name, id, input)
│
├── NormalizeToolCall(name, input) → NormalizedPayload
│ stored in pendingToolCalls[id]
│
├── emit tool_call event (status: "running", payload attached)
│
... (tool executes) ...
│
├── tool_result block (tool_use_id, content, is_error)
│
├── NormalizeToolResult(payload, content) → enriches payload with output
│
└── emit tool_update event (status: "complete" or "error", payload attached)
```
### NormalizedPayload Structure
A discriminated union — exactly one kind-specific field is populated:
```
NormalizedPayload
├── kind: ToolKind (read_file, modify_file, shell_exec, ...)
├── read_file: { file_path, offset, limit, output: { content, line_count, truncated } }
├── modify_file: { file_path, mutations: [{ type, content, old_content, new_content, diff }] }
├── shell_exec: { command, work_dir, description, timeout, background, output: { exit_code, stdout, stderr } }
├── code_search: { query, pattern, path, glob, output: { files, file_count, truncated } }
├── http_request: { url, method, response, is_error }
├── subagent_task: { description, prompt, subagent_type }
├── create_task: { title, description }
├── manage_todos: { operation, items: [{ id, description, status }] }
├── generic: { name, input, output }
└── misc: { label, details }
```
---
## Agent Events
Events emitted through the `updatesCh` channel to the frontend via WebSocket:
| Event Type | When | Key Fields |
|-----------|------|------------|
| `session_status` | First system message | `session_id`, `data.session_status` ("new"/"resumed") |
| `available_commands` | After initialize or system message | `available_commands[]` (name, description) |
| `message_chunk` | Assistant text or slash command output | `text` |
| `reasoning` | Thinking/chain-of-thought | `reasoning_text` |
| `tool_call` | Tool invocation starts | `tool_call_id`, `tool_name`, `tool_title`, `tool_status: "running"`, `normalized` |
| `tool_update` | Tool result received | `tool_call_id`, `tool_status: "complete"/"error"`, `normalized` |
| `context_window` | Token usage update | `context_window_size`, `context_window_used`, `context_window_remaining`, `context_efficiency` |
| `complete` | Turn finished | `data` (cost_usd, duration_ms, num_turns, input/output_tokens, last_message_uuid) |
| `error` | Turn failed | `error` message |
| `rate_limit` | API rate limited | `rate_limit_message` |
| `permission_cancelled` | Permission dialog cancelled | `pending_id` |
### Subagent Nesting
When Claude Code uses the `Task` tool, it spawns subagents. Messages from subagents include `parent_tool_use_id`, which maps to the parent `tool_call_id`. The frontend uses this for visual nesting.
---
## Context Window Tracking
Context usage is tracked from two sources:
1. **Assistant messages** — `usage` field provides per-message token counts:
```
context_used = input_tokens + output_tokens + cache_creation_input_tokens + cache_read_input_tokens
```
2. **Result messages** — `model_usage` map provides the actual context window size per model:
```json
{ "claude-sonnet-4-5": { "context_window": 200000 } }
```
The adapter tracks `mainModelName` (first model seen, excluding subagent models) and updates `mainModelContextWindow` from result stats. The default fallback is 200,000 tokens.
---
## MCP Server Configuration
MCP servers are passed to Claude Code via the `--mcp-config` flag:
```
--mcp-config '{"mcpServers":{"my-server":{"command":"node","args":["server.js"]}}}'
```
Supported transports:
- **stdio**: `{ "command": "...", "args": [...] }`
- **SSE/HTTP**: `{ "url": "...", "type": "sse" }`
Configuration is built from `cfg.McpServers` in `PrepareCommandArgs()`.
---
## Image Attachments
Since stream-json doesn't support multimodal content blocks in prompts, image attachments are handled by:
1. Saving base64-decoded images to `.kandev/temp/images/` in the workspace
2. Prepending file references to the prompt text
3. Claude Code reads the images via its `Read` tool
Supported formats: PNG, JPEG, GIF, WebP.
---
## Debug & Tracing
Enabled via `KANDEV_DEBUG_AGENT_MESSAGES=true`.
### Debug Logging
Writes JSONL files in the working directory:
- `raw-streamjson-<agentId>.jsonl` — raw protocol messages as received
- `normalized-streamjson-<agentId>.jsonl` — normalized AgentEvents
### OTel Tracing
Requires `OTEL_EXPORTER_OTLP_ENDPOINT` in addition to the debug flag.
**Span hierarchy:**
```
streamjson.prompt (parent span, covers entire turn)
├── streamjson.system (session init)
├── streamjson.message_chunk (streaming text)
├── streamjson.reasoning (thinking)
├── streamjson.tool_call (tool invocation)
├── streamjson.tool_update (tool result)
├── streamjson.context_window (token usage)
├── streamjson.control.control_request.can_use_tool (incoming permission request)
├── streamjson.control.permission_response (outgoing permission response)
├── streamjson.control.hook_response.pre_tool_use (outgoing hook response)
└── streamjson.complete (turn completion)
```
Each span carries `raw` and `normalized` events for side-by-side comparison in Jaeger/Tempo.
---
## Key Source Files
| File | Package | Purpose |
|------|---------|---------|
| `pkg/claudecode/types.go` | `claudecode` | Protocol message types and constants |
| `pkg/claudecode/client.go` | `claudecode` | stdin/stdout client, read loop, control requests |
| `streamjson/adapter.go` | `streamjson` | Main adapter state, message dispatch, sendUpdate |
| `streamjson/streamjson_init.go` | `streamjson` | Initialize, hook building, MCP config |
| `streamjson/streamjson_session.go` | `streamjson` | Session create/resume |
| `streamjson/streamjson_prompt.go` | `streamjson` | Prompt send, wait, cancel, image attachments |
| `streamjson/streamjson_messages.go` | `streamjson` | System, assistant, user, rate-limit handlers |
| `streamjson/streamjson_result.go` | `streamjson` | Result processing, text dedup, completion signaling |
| `streamjson/streamjson_permissions.go` | `streamjson` | Permissions, hooks, timeout, cancel |
| `streamjson/normalize.go` | `streamjson` | Tool call/result → NormalizedPayload |
| `streams/tool_payload.go` | `streams` | NormalizedPayload discriminated union |
| `streams/agent.go` | `streams` | AgentEvent types and structure |
| `agents/claude_code.go` | `agents` | Agent definition, CLI flags, models |