Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
75.1 KB
Raw Blame
package agent

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"maps"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/google/uuid"
	"github.com/multica-ai/multica/server/pkg/taskfailure"
)

// claudeTerminateGraceNanos optionally overrides, in nanoseconds, how long a
// cancelled claude process group is given to exit after SIGTERM before it is
// SIGKILLed. Set via atomic store in tests; zero keeps the default.
var claudeTerminateGraceNanos atomic.Int64

func claudeTerminateGrace() time.Duration {
	if n := claudeTerminateGraceNanos.Load(); n > 0 {
		return time.Duration(n)
	}
	return 5 * time.Second
}

// claudeErrorResultGraceNanos optionally overrides, in nanoseconds, how long
// claude may keep running after it reported an error result. Set via atomic
// store in tests; zero keeps the default.
var claudeErrorResultGraceNanos atomic.Int64

// claudeErrorResultGrace bounds the wait for claude to exit after an error
// result. With stdin closed the CLI still stays alive while any background
// task it started is running, then opens a new turn when the task ends. After
// an error result (a spent session limit, an API failure) that turn cannot
// change the outcome, so the daemon stops waiting instead of holding the run
// open for the task's lifetime.
func claudeErrorResultGrace() time.Duration {
	if n := claudeErrorResultGraceNanos.Load(); n > 0 {
		return time.Duration(n)
	}
	return 10 * time.Second
}

// claudeBackend implements Backend by spawning the Claude Code CLI
// with --output-format stream-json.
type claudeBackend struct {
	cfg Config
}

func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
	execPath := b.cfg.ExecutablePath
	if execPath == "" {
		execPath = "claude"
	}
	if _, err := exec.LookPath(execPath); err != nil {
		return nil, fmt.Errorf("claude executable not found at %q: %w", execPath, err)
	}

	timeout := opts.Timeout
	runCtx, cancel := runContext(ctx, timeout)

	// Getting a process is the only step that depends on the warm pool. A
	// pooled spawn must outlive runCtx so it can be parked after the turn; a
	// one-shot spawn is bound to it.
	pooled := b.cfg.WarmPool != nil
	var proc *claudeProcess
	var fingerprint string
	if pooled {
		fingerprint = b.warmFingerprint(execPath, opts)
		proc = b.acquireWarmProcess(opts.ResumeSessionID, fingerprint)
	}
	warmHit := proc != nil
	var usageSnapshot *claudeUsageSnapshot
	if !warmHit {
		spawnCtx := runCtx
		if pooled {
			spawnCtx = context.Background()
		}
		var err error
		proc, usageSnapshot, err = b.spawnClaudeProcess(spawnCtx, execPath, opts, pooled, fingerprint)
		if err != nil {
			cancel()
			return nil, err
		}
	}

	msgCh := make(chan Message, 256)
	resCh := make(chan Result, 1)

	var supplements *claudeSupplementSession
	if opts.EnableTaskSupplement {
		supplements = newClaudeSupplementSession(runCtx)
	}
	initializer := supplements
	if initializer == nil && opts.SkillInvocation != nil {
		initializer = newClaudeSupplementSession(runCtx)
	}

	// A reused process reports cumulative session totals, so its result usage
	// is measured against what the previous turn already reported.
	var baselineUsage map[string]TokenUsage
	if warmHit && len(proc.lastCumulativeModelUsage) > 0 {
		baselineUsage = maps.Clone(proc.lastCumulativeModelUsage)
	}

	turn := &claudeTurn{
		backend:       b,
		proc:          proc,
		cancel:        cancel,
		opts:          opts,
		msgCh:         msgCh,
		coalescer:     newClaudeStreamCoalescer(msgCh, nil),
		supplements:   supplements,
		initializer:   initializer,
		usageSnapshot: usageSnapshot,
		baselineUsage: baselineUsage,
		rateLimits:    newRateLimitTracker(opts.OnRateLimits),
		commandUUID:   uuid.NewString(),
		controlErrors: make(chan error, 1),
		resultCh:      make(chan struct{}),
		usage:         make(map[string]TokenUsage),
		seenUsage:     make(map[string]struct{}),
	}
	if warmHit {
		turn.sessionID = proc.sessionID
	}
	proc.setActiveTurn(turn)
	if warmHit {
		b.cfg.Logger.Info("claude warm session reused",
			"pid", proc.cmd.Process.Pid,
			"session_id", proc.sessionID,
			"cwd", opts.Cwd,
			"model", opts.Model,
		)
		trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: proc.sessionID})
	} else {
		// Start reading only once the turn is attached so no early event is
		// dropped.
		go proc.readStdout()
	}

	// writeClaudeInput runs in its own goroutine so it cannot deadlock
	// against the stdout reader. With --verbose --output-format stream-json
	// the CLI emits a startup banner before reading its first stdin frame;
	// if nothing is draining stdout while we write the prompt, claude blocks
	// writing stdout, never reads stdin, and our Write blocks until runCtx
	// fires. The field symptom is "write |1: The pipe has been ended."
	// surfacing exactly at the per-task timeout when the kill invalidates
	// the still-blocked pipe.
	//
	// Keep stdin open after the initial user message. Claude's stream-json
	// protocol can emit control_request events mid-run and expects matching
	// control_response frames on the same input stream; closing stdin here
	// leaves the child stuck waiting for a response until its own fallback
	// timeout.
	writeDone := make(chan error, 1)
	go func() {
		slashCommandsAllowed := !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs)
		var commands map[string]bool
		switch {
		case warmHit:
			// The process answered initialize on its first turn; it does not
			// accept a second handshake.
			if proc.initialized && slashCommandsAllowed {
				commands = proc.initializedCommands
			}
		case initializer != nil:
			if initErr := initializer.initialize(proc.inputWriter, opts.HandshakeTimeout, opts.EnableTaskSupplement); initErr != nil {
				b.cfg.Logger.Warn("Claude initialization unavailable; continuing with text input", "error", initErr)
				initializer.end()
			} else {
				proc.initialized = true
				proc.initializedCommands = initializer.availableCommands()
				if slashCommandsAllowed {
					commands = proc.initializedCommands
				}
			}
		}
		blocks := []string{prompt}
		if opts.SkillInvocation != nil {
			blocks = opts.SkillInvocation.claudeTextBlocks(commands)
		}
		err := writeClaudeInput(proc.inputWriter, turn.commandUUID, blocks...)
		if err != nil {
			turn.closeInput()
			if supplements != nil {
				cancel()
			}
		}
		writeDone <- err
	}()

	go func() {
		defer cancel()
		defer close(msgCh)
		defer close(resCh)

		startTime := time.Now()

		// A pooled process stays up between turns, so its turn ends at the
		// result event. A one-shot process closes stdin after its result and
		// the turn lasts until it exits, so anything it emits meanwhile still
		// streams.
		var resultSeen <-chan struct{}
		if proc.pooled {
			resultSeen = turn.resultCh
		}
		cancelledOrTimedOut := false
		select {
		case <-resultSeen:
		case <-proc.procDone:
		case <-runCtx.Done():
			cancelledOrTimedOut = true
			proc.terminate()
			<-proc.procDone
		}
		turn.endInitializer()
		// Detach before reading the turn's state or waiting on its control
		// writes: a pooled process keeps emitting after its result event.
		proc.setActiveTurn(nil)

		turn.mu.Lock()
		turn.coalescer.flushAll()
		sawResult := turn.sawResult
		resultIsError := turn.resultIsError
		terminalReasonError := turn.terminalReasonError
		sawAsyncLaunch := turn.sawAsyncLaunch
		sessionID := turn.sessionID
		lastAssistantText := turn.lastAssistantText
		finalResultText := turn.finalResultText
		lastUsageResult := turn.lastUsageResult
		lastRawModelUsage := turn.lastRawModelUsage
		usage := turn.usage
		eventCount := turn.eventCount
		invalidEventCount := turn.invalidEventCount
		assistantEventCount := turn.assistantEventCount
		toolUseCount := turn.toolUseCount
		unreadableAssistantCount := turn.unreadableAssistantCount
		turn.mu.Unlock()

		// writeDone is buffered (cap 1) and the writer always sends — by now
		// the prompt write has either succeeded, hit a broken pipe, or been
		// unblocked by the kill that ended the process.
		turn.controlWrites.Wait()
		writeErr := <-writeDone
		if writeErr == nil {
			select {
			case writeErr = <-turn.controlErrors:
			default:
			}
		}
		// Internal protocol failures cancel the process to unblock its pipes.
		// Preserve the actual failure instead of reporting a user cancellation.
		if supplements != nil && writeErr != nil && ctx.Err() == nil && terminalReasonError == "" && !errors.Is(runCtx.Err(), context.DeadlineExceeded) {
			terminalReasonError = fmt.Sprintf("claude input/control protocol failed: %v", writeErr)
		}

		proc.clearTaskEnv()

		scanErr, exitErr := proc.getErrors()
		parked := proc.pooled &&
			sawResult &&
			!resultIsError &&
			terminalReasonError == "" &&
			!sawAsyncLaunch &&
			!cancelledOrTimedOut &&
			writeErr == nil &&
			scanErr == nil &&
			runCtx.Err() == nil &&
			sessionID != "" &&
			proc.Alive()
		if parked {
			proc.sessionID = sessionID
			if len(lastRawModelUsage) > 0 {
				proc.lastCumulativeModelUsage = lastRawModelUsage
			}
			b.cfg.WarmPool.Park("claude", sessionID, proc)
		} else {
			// A pooled CLI still waiting for its next user frame exits on this
			// stdin EOF instead of blocking for the error result grace window.
			// A one-shot process has already exited; this releases its temp files.
			proc.Close()
			scanErr, exitErr = proc.getErrors()
		}

		duration := time.Since(startTime)

		if !sawResult && usageSnapshot != nil {
			appendedUsage, found, snapshotErr := usageSnapshot.appendedCostStateUsage()
			switch {
			case snapshotErr != nil:
				b.cfg.Logger.Warn("claude final cost state unavailable; keeping stream usage fallback", "error", snapshotErr)
			case found:
				usage = subtractClaudeUsage(appendedUsage, usageSnapshot.baseline)
			}
		}

		completionGuardError := ""
		if sawAsyncLaunch {
			completionGuardError = "claude launched an async background task; Multica-managed runs require foreground execution"
		}
		finalStatus, finalOutput, finalError := finalizeStreamResult(
			"claude",
			timeout,
			runCtx.Err(),
			writeErr,
			exitErr,
			sessionID,
			streamTerminalState{
				lastAssistantText:   lastAssistantText,
				finalResultText:     finalResultText,
				sawResult:           sawResult,
				resultIsError:       resultIsError,
				scanErr:             scanErr,
				terminalReasonError: terminalReasonError,
			},
			completionGuardError,
		)

		// Attach the stderr tail to any non-empty failure message; callers
		// upstream surface this as the task's error field, which is the only
		// place users see it. A process that exited has been reaped, so
		// os/exec's stderr copy goroutine has observed every byte.
		stderrTail := proc.stderrBuf.Tail()
		if finalError != "" {
			finalError = withAgentStderr(finalError, "claude", stderrTail)
		}
		logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{
			provider:                   "claude",
			cliVersion:                 b.cfg.CLIVersion,
			model:                      opts.Model,
			exitCode:                   streamProcessExitCode(exitErr),
			eventCount:                 eventCount,
			invalidEventCount:          invalidEventCount,
			assistantEventCount:        assistantEventCount,
			toolUseCount:               toolUseCount,
			sawResult:                  sawResult,
			resultIsError:              resultIsError,
			resultBytes:                len(finalResultText),
			lastAssistantBytes:         len(lastAssistantText),
			scannerError:               scanErr != nil,
			unreadableAssistantCount:   unreadableAssistantCount,
			anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",
		})

		b.cfg.Logger.Info("claude finished",
			"pid", proc.cmd.Process.Pid,
			"warm_hit", warmHit,
			"parked", parked,
			"status", finalStatus,
			"duration", duration.Round(time.Millisecond).String(),
		)

		// The account-binding 400 arrives in the result event (finalError);
		// "no conversation found" is printed to stderr. Check both.
		resumeRejected := resumeWasRejected(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
		reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
		if resumeRejected {
			// A rejected resume may emit usage for a newly-created session. Its
			// totals do not share the requested session's baseline.
			if lastUsageResult != nil {
				if resultUsage, authoritative := claudeResultUsageSince(*lastUsageResult, opts.Model, nil); authoritative {
					usage = resultUsage
				}
			}
			b.cfg.Logger.Info("claude resume was rejected; dropping session id and signalling fresh-session retry",
				"requested_resume", opts.ResumeSessionID,
				"emitted_session", sessionID,
			)
		}

		resCh <- Result{
			Status:         finalStatus,
			Output:         finalOutput,
			Error:          finalError,
			DurationMs:     duration.Milliseconds(),
			SessionID:      reportedSessionID,
			Usage:          usage,
			ResumeRejected: resumeRejected,
		}
	}()

	session := &Session{Messages: msgCh, Result: resCh}
	if supplements != nil {
		session.Supplement = supplements.supplement
		session.SupplementReady = supplements.ready
	}
	return session, nil
}

// claudeTurn is one turn's stream state. The process's stdout reader feeds it
// events; Execute's lifecycle goroutine reads the outcome once the turn ends.
type claudeTurn struct {
	backend                  *claudeBackend
	proc                     *claudeProcess
	cancel                   context.CancelFunc
	opts                     ExecOptions
	msgCh                    chan Message
	coalescer                *claudeStreamCoalescer
	supplements              *claudeSupplementSession
	initializer              *claudeSupplementSession
	usageSnapshot            *claudeUsageSnapshot
	baselineUsage            map[string]TokenUsage
	rateLimits               *rateLimitTracker
	controlWrites            sync.WaitGroup
	controlErrors            chan error
	resultCh                 chan struct{}
	resultOnce               sync.Once
	stopAfterErrorResultOnce sync.Once
	// commandUUID tags the prompt this turn writes. Claude Code reports each
	// queued input's progress as command_lifecycle events keyed by that UUID.
	commandUUID string

	controlMu       sync.Mutex
	pendingControls int
	closeRequested  bool

	mu sync.Mutex
	// Resuming a session whose last turn was cut off can make Claude Code
	// re-run that turn as its own command before the queued prompt
	// (GH #11506). A result that arrives after another command started but
	// before this turn's own command started is not this turn's answer.
	// Once the own command starts, every result counts, whatever other
	// commands do meanwhile (folded in, cancelled).
	otherCommandStarted      bool
	ownCommandStarted        bool
	lastAssistantText        string
	finalResultText          string
	sawResult                bool
	resultIsError            bool
	terminalReasonError      string
	sawRefusalNoFallback     bool
	sessionID                string
	lastUsageResult          *claudeSDKMessage
	lastRawModelUsage        map[string]TokenUsage
	sawAsyncLaunch           bool
	usage                    map[string]TokenUsage
	seenUsage                map[string]struct{}
	eventCount               int
	invalidEventCount        int
	assistantEventCount      int
	toolUseCount             int
	unreadableAssistantCount int
}

func (t *claudeTurn) handleMessage(msg claudeSDKMessage) {
	t.mu.Lock()
	t.eventCount++
	switch msg.Type {
	case "stream_event":
		if msg.ParentToolUseID == "" {
			t.coalescer.handleEvent(msg.Event)
		}
		t.mu.Unlock()
	case "assistant":
		t.assistantEventCount++
		turn := t.backend.handleAssistantWithStream(msg, t.msgCh, t.usage, t.seenUsage, t.coalescer)
		t.toolUseCount += turn.toolUses
		if !turn.understood {
			t.unreadableAssistantCount++
		}
		t.lastAssistantText = turn.resolveFallback(t.lastAssistantText)
		t.mu.Unlock()
	case "user":
		t.coalescer.flushAll()
		if t.backend.handleUser(msg, t.msgCh) {
			t.sawAsyncLaunch = true
		}
		t.mu.Unlock()
	case "rate_limit_event":
		rl := t.rateLimits
		t.mu.Unlock()
		if update, ok := parseClaudeRateLimitEvent(msg.RateLimitInfo); ok {
			rl.apply(update)
		}
	case "system":
		if msg.SessionID != "" {
			t.sessionID = msg.SessionID
		}
		// Only the main thread's refusal decides the turn. A subagent's
		// refusal is reported back to the main thread as a tool result, and
		// the main thread's own result says how the turn ended.
		if msg.Subtype == claudeSubtypeModelRefusalNoFallback && msg.ParentToolUseID == "" {
			t.sawRefusalNoFallback = true
		}
		sid := t.sessionID
		t.mu.Unlock()
		trySend(t.msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sid})
	case "command_lifecycle":
		if msg.State == "started" && !t.ownCommandStarted {
			if msg.CommandUUID == t.commandUUID {
				t.ownCommandStarted = true
				// Text streamed by an earlier command must not become this
				// turn's fallback output.
				t.coalescer.flushAll()
				t.lastAssistantText = ""
			} else {
				t.otherCommandStarted = true
			}
		}
		t.mu.Unlock()
	case "result":
		t.coalescer.flushAll()
		if t.otherCommandStarted && !t.ownCommandStarted {
			t.mu.Unlock()
			t.backend.cfg.Logger.Info("claude: ignoring result of a command this turn did not send",
				"turn_command_uuid", t.commandUUID,
				"result_bytes", len(msg.ResultText),
				"is_error", msg.IsError,
			)
			return
		}
		t.sawResult = true
		t.finalResultText = msg.ResultText
		t.resultIsError = msg.IsError
		t.terminalReasonError = claudeTerminalReasonFailure(msg.TerminalReason, msg.ResultText)
		if t.terminalReasonError == "" {
			t.terminalReasonError = claudeRefusalFailure(msg.StopReason, t.sawRefusalNoFallback, msg.IsError, msg.ResultText)
		}
		if msg.SessionID != "" {
			t.sessionID = msg.SessionID
		}
		if len(msg.ModelUsage) > 0 {
			t.lastRawModelUsage = claudeModelUsage(msg.ModelUsage)
		}
		// A resume whose baseline capture failed cannot trust the result's
		// modelUsage: newer Claude Code restores the session's cumulative
		// counters on resume, so the reported total may span every prior task
		// (GH #9564), and without a baseline there is no way to verify it is
		// per-run. Keep the stream-derived per-run usage in that case; the
		// reported totals are recorded in lastUsageResult only for the
		// resume-rejected recapture, where the run is known to have started a
		// fresh session whose totals are its own.
		unverifiableBaseline := t.usageSnapshot == nil && t.baselineUsage == nil && t.opts.ResumeSessionID != ""
		baseline := t.baselineUsage
		if baseline == nil && t.usageSnapshot != nil {
			baseline = t.usageSnapshot.baseline
		}
		if resultUsage, authoritative := claudeResultUsageSince(msg, t.opts.Model, baseline); authoritative {
			usageMsg := msg
			t.lastUsageResult = &usageMsg
			if !unverifiableBaseline {
				t.usage = resultUsage
			}
		}
		failed := t.resultIsError || t.terminalReasonError != ""
		t.mu.Unlock()
		t.resultOnce.Do(func() { close(t.resultCh) })
		if !t.proc.pooled {
			// Keep draining stdout while accepted control replies finish
			// writing. Once those replies drain, stdin closes; requests
			// arriving after that cannot be answered.
			t.closeInputAfterControls()
			if failed {
				t.stopAfterErrorResultOnce.Do(func() { go t.proc.stopAfterErrorResult() })
			}
		}
	case "log":
		t.mu.Unlock()
		if msg.Log != nil {
			trySend(t.msgCh, Message{
				Type:    MessageLog,
				Level:   msg.Log.Level,
				Content: msg.Log.Message,
			})
		}
	case "control_request":
		supplements := t.supplements
		t.mu.Unlock()
		var reply func(io.Writer) error
		if supplements != nil {
			reply, _ = supplements.prepareHook(msg)
		}
		t.controlMu.Lock()
		t.pendingControls++
		t.controlMu.Unlock()
		t.controlWrites.Add(1)
		go func(msg claudeSDKMessage, reply func(io.Writer) error) {
			defer t.controlWrites.Done()
			defer t.controlReplied()
			if reply == nil {
				t.backend.handleControlRequest(msg, t.proc.inputWriter)
				return
			}
			if err := reply(t.proc.inputWriter); err != nil {
				select {
				case t.controlErrors <- err:
				default:
				}
				t.cancel()
			}
		}(msg, reply)
	case "control_response":
		init := t.initializer
		t.mu.Unlock()
		if init != nil {
			init.handleResponse(msg.Response)
		}
	default:
		t.mu.Unlock()
	}
}

func (t *claudeTurn) noteInvalidEvent() {
	t.mu.Lock()
	t.invalidEventCount++
	t.mu.Unlock()
}

func (t *claudeTurn) endInitializer() {
	if t.initializer != nil {
		t.initializer.end()
	}
}

// closeInput EOFs the process's stdin and ends the initializer so a handshake
// still waiting for its reply gives up.
func (t *claudeTurn) closeInput() {
	t.proc.closeStdin()
	t.endInitializer()
}

func (t *claudeTurn) closeInputAfterControls() {
	t.endInitializer()
	t.controlMu.Lock()
	defer t.controlMu.Unlock()
	t.closeRequested = true
	if t.pendingControls == 0 {
		t.closeInput()
	}
}

func (t *claudeTurn) controlReplied() {
	t.controlMu.Lock()
	defer t.controlMu.Unlock()
	t.pendingControls--
	if t.closeRequested && t.pendingControls == 0 {
		t.closeInput()
	}
}

func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}) assistantTurn {
	return b.handleAssistantWithStream(msg, ch, usage, seenUsage, nil)
}

func (b *claudeBackend) handleAssistantWithStream(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}, coalescer *claudeStreamCoalescer) assistantTurn {
	var content claudeMessageContent
	if err := json.Unmarshal(msg.Message, &content); err != nil {
		// Unreadable body: understood stays false so the caller drops any
		// fallback rather than let an older turn stand in for this one.
		return assistantTurn{}
	}
	if coalescer != nil && msg.ParentToolUseID == "" {
		coalescer.flushAll()
	}
	turn := assistantTurn{understood: true}
	var assistantText strings.Builder
	var assistantThinking strings.Builder
	toolUseCount := 0

	// A response can emit several assistant blocks with the same message ID
	// and usage. Count its input/cache tokens once, without dropping any of
	// the blocks below. Missing IDs retain best-effort per-event accounting.
	// This fallback covers only the main loop: assistant output_tokens is a
	// placeholder, and subagent totals require the final result's modelUsage.
	// https://code.claude.com/docs/en/agent-sdk/cost-tracking#track-per-step-usage
	_, counted := seenUsage[content.ID]
	if msg.ParentToolUseID == "" && content.Usage != nil && content.Model != "" &&
		(content.ID == "" || !counted) && claudeUsageHasTokens(
		content.Usage.InputTokens, 0, content.Usage.CacheReadInputTokens, content.Usage.CacheCreationInputTokens,
	) {
		if content.ID != "" {
			seenUsage[content.ID] = struct{}{}
		}
		u := usage[content.Model]
		u.InputTokens += content.Usage.InputTokens
		u.CacheReadTokens += content.Usage.CacheReadInputTokens
		u.CacheWriteTokens += content.Usage.CacheCreationInputTokens
		usage[content.Model] = u
	}

	for _, block := range content.Content {
		switch block.Type {
		case "text":
			if block.Text != "" {
				assistantText.WriteString(block.Text)
				if coalescer == nil || msg.ParentToolUseID != "" || !coalescer.hasStreamedText() {
					trySend(ch, Message{Type: MessageText, Content: block.Text})
				}
			}
		case "thinking":
			if block.Thinking != "" {
				assistantThinking.WriteString(block.Thinking)
				if coalescer == nil || msg.ParentToolUseID != "" || !coalescer.hasStreamedThinking() {
					trySend(ch, Message{Type: MessageThinking, Content: block.Thinking})
				}
			}
		case "tool_use":
			toolUseCount++
			var input map[string]any
			if block.Input != nil {
				_ = json.Unmarshal(block.Input, &input)
			}
			trySend(ch, Message{
				Type:   MessageToolUse,
				Tool:   block.Name,
				CallID: block.ID,
				Input:  input,
			})
		default:
			// A block type we do not render may be carrying the model's answer
			// in a shape we cannot read, so we must not claim this turn was
			// silent. Recognising a new no-text block is a deliberate one-line
			// addition here, not an accident of falling through.
			turn.understood = false
		}
	}
	if coalescer != nil && msg.ParentToolUseID == "" {
		coalescer.reconcileAssistant(assistantText.String(), assistantThinking.String())
	}
	turn.text = assistantText.String()
	turn.toolUses = toolUseCount
	return turn
}

const (
	claudeStreamFlushInterval  = 50 * time.Millisecond
	claudeStreamAggregateBytes = agentStreamMaxLineBytes / 64
)

// claudeStreamCoalescer handles Anthropic SSE `stream_event` envelopes emitted
// by `claude --include-partial-messages`, delivering the leading delta
// immediately and coalescing subsequent tokens at claudeStreamFlushInterval.
// When the matching `assistant` snapshot arrives, reconcileAssistant emits any
// trailing suffix not already delivered and resets per-message state so zero
// text is duplicated or dropped.
type claudeStreamCoalescer struct {
	ch  chan<- Message
	now func() time.Time

	streamedText     bool
	deliveredText    strings.Builder
	pendingText      strings.Builder
	lastTextFlush    time.Time
	streamedThinking bool
	deliveredThink   strings.Builder
	pendingThink     strings.Builder
	lastThinkFlush   time.Time
}

func newClaudeStreamCoalescer(ch chan<- Message, now func() time.Time) *claudeStreamCoalescer {
	if now == nil {
		now = time.Now
	}
	return &claudeStreamCoalescer{ch: ch, now: now}
}

func (c *claudeStreamCoalescer) hasStreamedText() bool {
	return c != nil && c.streamedText
}

func (c *claudeStreamCoalescer) hasStreamedThinking() bool {
	return c != nil && c.streamedThinking
}

func (c *claudeStreamCoalescer) handleEvent(raw json.RawMessage) {
	if c == nil || len(raw) == 0 {
		return
	}
	var env struct {
		Type  string `json:"type"`
		Delta struct {
			Type     string `json:"type"`
			Text     string `json:"text"`
			Thinking string `json:"thinking"`
		} `json:"delta"`
	}
	if err := json.Unmarshal(raw, &env); err != nil {
		return
	}
	switch env.Type {
	case "message_start":
		c.flushAll()
		c.resetMessage()
	case "content_block_delta":
		switch env.Delta.Type {
		case "text_delta":
			if env.Delta.Text != "" {
				c.appendText(env.Delta.Text)
			}
		case "thinking_delta":
			if env.Delta.Thinking != "" {
				c.appendThinking(env.Delta.Thinking)
			}
		}
	case "content_block_stop", "message_stop":
		c.flushAll()
	}
}

func (c *claudeStreamCoalescer) appendText(delta string) {
	firstDelta := !c.streamedText && c.pendingText.Len() == 0
	c.streamedText = true
	c.pendingText.WriteString(delta)
	now := c.now()
	if firstDelta || c.pendingText.Len() >= claudeStreamAggregateBytes || (!c.lastTextFlush.IsZero() && now.Sub(c.lastTextFlush) >= claudeStreamFlushInterval) {
		c.flushText(now)
	}
}

func (c *claudeStreamCoalescer) appendThinking(delta string) {
	firstDelta := !c.streamedThinking && c.pendingThink.Len() == 0
	c.streamedThinking = true
	c.pendingThink.WriteString(delta)
	now := c.now()
	if firstDelta || c.pendingThink.Len() >= claudeStreamAggregateBytes || (!c.lastThinkFlush.IsZero() && now.Sub(c.lastThinkFlush) >= claudeStreamFlushInterval) {
		c.flushThinking(now)
	}
}

func (c *claudeStreamCoalescer) flushText(now time.Time) {
	if c.pendingText.Len() == 0 {
		return
	}
	chunk := c.pendingText.String()
	if trySend(c.ch, Message{Type: MessageText, Content: chunk}) {
		c.deliveredText.WriteString(chunk)
		c.pendingText.Reset()
		c.lastTextFlush = now
	}
}

func (c *claudeStreamCoalescer) flushThinking(now time.Time) {
	if c.pendingThink.Len() == 0 {
		return
	}
	chunk := c.pendingThink.String()
	if trySend(c.ch, Message{Type: MessageThinking, Content: chunk}) {
		c.deliveredThink.WriteString(chunk)
		c.pendingThink.Reset()
		c.lastThinkFlush = now
	}
}

func (c *claudeStreamCoalescer) flushAll() {
	if c == nil {
		return
	}
	now := c.now()
	c.flushText(now)
	c.flushThinking(now)
}

func (c *claudeStreamCoalescer) reconcileAssistant(fullText, fullThinking string) {
	if c == nil {
		return
	}
	if c.streamedText && fullText != "" {
		delivered := c.deliveredText.String()
		if len(fullText) > len(delivered) && strings.HasPrefix(fullText, delivered) {
			if tail := fullText[len(delivered):]; tail != "" {
				trySend(c.ch, Message{Type: MessageText, Content: tail})
			}
		}
	}
	if c.streamedThinking && fullThinking != "" {
		delivered := c.deliveredThink.String()
		if len(fullThinking) > len(delivered) && strings.HasPrefix(fullThinking, delivered) {
			if tail := fullThinking[len(delivered):]; tail != "" {
				trySend(c.ch, Message{Type: MessageThinking, Content: tail})
			}
		}
	}
	c.resetMessage()
}

func (c *claudeStreamCoalescer) resetMessage() {
	c.streamedText = false
	c.deliveredText.Reset()
	c.pendingText.Reset()
	c.lastTextFlush = time.Time{}
	c.streamedThinking = false
	c.deliveredThink.Reset()
	c.pendingThink.Reset()
	c.lastThinkFlush = time.Time{}
}

func (b *claudeBackend) handleUser(msg claudeSDKMessage, ch chan<- Message) bool {
	var content claudeMessageContent
	if err := json.Unmarshal(msg.Message, &content); err != nil {
		return false
	}

	sawAsyncLaunch := false
	for _, block := range content.Content {
		if block.Type == "tool_result" {
			resultStr := ""
			if block.Content != nil {
				resultStr = string(block.Content)
				if claudeToolResultHasAsyncLaunch(block.Content) {
					sawAsyncLaunch = true
				}
			}
			trySend(ch, Message{
				Type:   MessageToolResult,
				CallID: block.ToolUseID,
				Output: resultStr,
			})
		}
	}
	return sawAsyncLaunch
}

func (b *claudeBackend) handleControlRequest(msg claudeSDKMessage, stdin interface{ Write([]byte) (int, error) }) {
	// Auto-approve all tool uses in autonomous/daemon mode.
	var req claudeControlRequestPayload
	if err := json.Unmarshal(msg.Request, &req); err != nil {
		return
	}

	var inputMap map[string]any
	if req.Input != nil {
		_ = json.Unmarshal(req.Input, &inputMap)
	}
	if inputMap == nil {
		inputMap = map[string]any{}
	}
	if forceClaudeToolInputForeground(inputMap) {
		b.cfg.Logger.Info("claude: forced foreground tool execution",
			"request_id", msg.RequestID,
			"tool", req.ToolName,
		)
	}

	response := map[string]any{
		"type": "control_response",
		"response": map[string]any{
			"subtype":    "success",
			"request_id": msg.RequestID,
			"response": map[string]any{
				"behavior":     "allow",
				"updatedInput": inputMap,
			},
		},
	}

	data, err := json.Marshal(response)
	if err != nil {
		b.cfg.Logger.Warn("claude: failed to marshal control response", "error", err)
		return
	}
	data = append(data, '\n')
	if _, err := stdin.Write(data); err != nil {
		b.cfg.Logger.Warn("claude: failed to write control response", "error", err)
	}
}

func forceClaudeToolInputForeground(input map[string]any) bool {
	if runInBackground, ok := input["run_in_background"].(bool); ok && runInBackground {
		input["run_in_background"] = false
		return true
	}
	return false
}

func claudeToolResultHasAsyncLaunch(raw json.RawMessage) bool {
	if len(raw) == 0 {
		return false
	}
	var value any
	if err := json.Unmarshal(raw, &value); err != nil {
		return false
	}
	switch v := value.(type) {
	case map[string]any:
		if claudeMapHasAsyncLaunchStatus(v) {
			return true
		}
		if content, ok := v["content"].([]any); ok {
			return claudeArrayHasAsyncLaunchStatus(content)
		}
	case []any:
		return claudeArrayHasAsyncLaunchStatus(v)
	}
	return false
}

func claudeArrayHasAsyncLaunchStatus(values []any) bool {
	for _, value := range values {
		if item, ok := value.(map[string]any); ok && claudeMapHasAsyncLaunchStatus(item) {
			return true
		}
	}
	return false
}

func claudeMapHasAsyncLaunchStatus(value map[string]any) bool {
	status, ok := value["status"].(string)
	return ok && status == "async_launched"
}

// ── Claude SDK JSON types ──

type claudeSDKMessage struct {
	Type            string          `json:"type"`
	Message         json.RawMessage `json:"message,omitempty"`
	Subtype         string          `json:"subtype,omitempty"`
	SessionID       string          `json:"session_id,omitempty"`
	Model           string          `json:"model,omitempty"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`

	// result fields
	ResultText string `json:"result,omitempty"`
	IsError    bool   `json:"is_error,omitempty"`
	// TerminalReason is Claude Code's structured statement of why the turn
	// ended. Read separately from IsError because the CLI computes the two
	// independently — see claudeTerminalReasonFailure.
	TerminalReason string `json:"terminal_reason,omitempty"`
	// StopReason is the API stop_reason of the turn's last model response.
	// Read only to recognise a safeguards refusal — see claudeRefusalFailure.
	StopReason string                            `json:"stop_reason,omitempty"`
	DurationMs float64                           `json:"duration_ms,omitempty"`
	NumTurns   int                               `json:"num_turns,omitempty"`
	Usage      *claudeUsage                      `json:"usage,omitempty"`
	ModelUsage map[string]claudeResultModelUsage `json:"modelUsage,omitempty"`

	// log fields
	Log *claudeLogEntry `json:"log,omitempty"`

	// rate_limit_event fields
	RateLimitInfo json.RawMessage `json:"rate_limit_info,omitempty"`

	// stream_event fields (--include-partial-messages)
	Event json.RawMessage `json:"event,omitempty"`

	// command_lifecycle fields
	CommandUUID string `json:"command_uuid,omitempty"`
	State       string `json:"state,omitempty"`

	// control request fields
	RequestID string          `json:"request_id,omitempty"`
	Request   json.RawMessage `json:"request,omitempty"`
	Response  json.RawMessage `json:"response,omitempty"`
}

type claudeLogEntry struct {
	Level   string `json:"level"`
	Message string `json:"message"`
}

type claudeMessageContent struct {
	ID      string               `json:"id"`
	Role    string               `json:"role"`
	Model   string               `json:"model"`
	Content []claudeContentBlock `json:"content"`
	Usage   *claudeUsage         `json:"usage,omitempty"`
}

type claudeUsage struct {
	InputTokens              int64 `json:"input_tokens"`
	OutputTokens             int64 `json:"output_tokens"`
	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
}

type claudeResultModelUsage struct {
	InputTokens              int64 `json:"inputTokens"`
	OutputTokens             int64 `json:"outputTokens"`
	CacheReadInputTokens     int64 `json:"cacheReadInputTokens"`
	CacheCreationInputTokens int64 `json:"cacheCreationInputTokens"`
}

// claudeTerminalReasonFailure turns Claude Code's structured terminal_reason
// into an error string when the reason means the turn did not actually produce
// an answer, and returns "" when it says nothing of the sort.
//
// Only prompt_too_long is recognised, and deliberately so. Every other terminal
// reason the CLI can report either already arrives with is_error set (api_error,
// model_error, error_max_turns …) or is a legitimate completion, so widening
// this would second-guess a contract that works — while prompt_too_long is the
// one case observed reaching the platform as a clean success (GH #6402). The
// CLI computes is_error from whether the last message it rendered was an API
// error and terminal_reason from why the turn stopped; when compaction fails
// and the run ends on a message that is not itself flagged, the two disagree
// and only terminal_reason is telling the truth.
//
// The returned text quotes the enum token so taskfailure.Classify lands it in
// agent_error.context_overflow without depending on the CLI's prose, which
// varies by release and is empty in some shapes. That reason is on the resume
// blacklist (GetLastTaskSession / GetLastChatTaskSession), so the saturated
// session is retired and the next task on the issue starts fresh — the
// automated form of the transcript-archiving workaround #6402 reported.
func claudeTerminalReasonFailure(terminalReason, resultText string) string {
	if strings.TrimSpace(terminalReason) != taskfailure.TerminalReasonPromptTooLong {
		return ""
	}
	msg := "claude ended the turn with terminal_reason=" + taskfailure.TerminalReasonPromptTooLong +
		": the session's context window is exhausted and compaction could not recover it"
	if detail := strings.TrimSpace(resultText); detail != "" {
		msg += " (" + detail + ")"
	}
	return msg
}

// ClaudeModelRefusalMarker prefixes the error claudeRefusalFailure reports. It
// is fixed Multica prose, so the daemon can recognise the failure without
// depending on Claude Code's refusal copy, which changes between releases
// (2.1.263 writes "can't help with this", 2.1.280 "safeguards flagged this
// message").
const ClaudeModelRefusalMarker = "claude ended the turn with stop_reason=refusal"

// claudeSubtypeModelRefusalNoFallback is the system event Claude Code emits on
// the main thread when the model refused the turn and no fallback model
// answered it.
const claudeSubtypeModelRefusalNoFallback = "model_refusal_no_fallback"

// claudeRefusalFailure turns a safeguards refusal into an error naming it, and
// returns "" for every other turn.
//
// A refusal poisons the session. Claude Code keeps the refused user message in
// the transcript, so every --resume sends it to the API again and is refused
// again, whatever the new prompt says. A fresh session with the same new
// prompt is answered. Reproduced against Claude Code 2.1.263 and 2.1.280; the
// resumed frames are fixtured in
// testdata/claude-code-2.1.280-refusal-resume.jsonl. Before this the failure
// classified as agent_error.unknown, which no resume blacklist covers, so the
// next comment on the issue resumed the same session and failed the same way.
//
// Two structured signals, either is enough:
//
//   - stop_reason=refusal on the result frame. The CLI copies the last model
//     response's stop_reason there, so it is "end_turn" when a fallback model
//     answered after the primary refused (fixtured in
//     testdata/claude-code-2.1.280-refusal-fallback-answered.jsonl).
//   - the model_refusal_no_fallback system event, when the result is an error.
//     It covers a result frame that does not carry stop_reason.
//
// The daemon maps ClaudeModelRefusalMarker to a resume-unsafe failure reason
// (classifyPoisonedError), which retires the session so the next task starts
// fresh. The CLI's own text rides along for the user.
func claudeRefusalFailure(stopReason string, sawRefusalNoFallback, isError bool, resultText string) string {
	if strings.TrimSpace(stopReason) != "refusal" && !(sawRefusalNoFallback && isError) {
		return ""
	}
	msg := ClaudeModelRefusalMarker +
		": the model declined this conversation, and resuming the session would send the refused message again"
	if detail := strings.TrimSpace(resultText); detail != "" {
		msg += " (" + detail + ")"
	}
	return msg
}

func claudeResultUsage(msg claudeSDKMessage, fallbackModel string) map[string]TokenUsage {
	usage, _ := claudeResultUsageSince(msg, fallbackModel, nil)
	return usage
}

func claudeResultUsageSince(msg claudeSDKMessage, fallbackModel string, baseline map[string]TokenUsage) (map[string]TokenUsage, bool) {
	if len(msg.ModelUsage) > 0 {
		usage := claudeModelUsage(msg.ModelUsage)
		if len(usage) > 0 {
			return subtractClaudeUsage(usage, baseline), true
		}
	}

	model := msg.Model
	if model == "" {
		model = fallbackModel
	}
	if msg.Usage == nil || model == "" || !claudeUsageHasTokens(
		msg.Usage.InputTokens,
		msg.Usage.OutputTokens,
		msg.Usage.CacheReadInputTokens,
		msg.Usage.CacheCreationInputTokens,
	) {
		return nil, false
	}
	return map[string]TokenUsage{
		model: {
			InputTokens:      msg.Usage.InputTokens,
			OutputTokens:     msg.Usage.OutputTokens,
			CacheReadTokens:  msg.Usage.CacheReadInputTokens,
			CacheWriteTokens: msg.Usage.CacheCreationInputTokens,
		},
	}, true
}

func claudeModelUsage(modelUsage map[string]claudeResultModelUsage) map[string]TokenUsage {
	usage := make(map[string]TokenUsage, len(modelUsage))
	for model, u := range modelUsage {
		if model == "" || !claudeUsageHasTokens(u.InputTokens, u.OutputTokens, u.CacheReadInputTokens, u.CacheCreationInputTokens) {
			continue
		}
		usage[model] = TokenUsage{
			InputTokens:      u.InputTokens,
			OutputTokens:     u.OutputTokens,
			CacheReadTokens:  u.CacheReadInputTokens,
			CacheWriteTokens: u.CacheCreationInputTokens,
		}
	}
	return usage
}

func subtractClaudeUsage(current, baseline map[string]TokenUsage) map[string]TokenUsage {
	// A baseline is usable only when Claude restored all of it. Older versions,
	// downgrades, and future counter resets report per-run totals instead; in
	// those cases subtracting even one historical field would silently undercount.
	if !claudeUsageIncludesBaseline(current, baseline) {
		usage := make(map[string]TokenUsage, len(current))
		for model, modelUsage := range current {
			usage[model] = modelUsage
		}
		return usage
	}
	usage := make(map[string]TokenUsage, len(current))
	for model, currentUsage := range current {
		base := baseline[model]
		delta := TokenUsage{
			InputTokens:      currentUsage.InputTokens - base.InputTokens,
			OutputTokens:     currentUsage.OutputTokens - base.OutputTokens,
			CacheReadTokens:  currentUsage.CacheReadTokens - base.CacheReadTokens,
			CacheWriteTokens: currentUsage.CacheWriteTokens - base.CacheWriteTokens,
		}
		if claudeUsageHasTokens(delta.InputTokens, delta.OutputTokens, delta.CacheReadTokens, delta.CacheWriteTokens) {
			usage[model] = delta
		}
	}
	return usage
}

func claudeUsageIncludesBaseline(current, baseline map[string]TokenUsage) bool {
	for model, base := range baseline {
		modelUsage, ok := current[model]
		if !ok || modelUsage.InputTokens < base.InputTokens ||
			modelUsage.OutputTokens < base.OutputTokens ||
			modelUsage.CacheReadTokens < base.CacheReadTokens ||
			modelUsage.CacheWriteTokens < base.CacheWriteTokens {
			return false
		}
	}
	return true
}

const claudeSessionReadChunkSize = 64 * 1024

type claudeUsageSnapshot struct {
	path     string
	fileInfo os.FileInfo
	offset   int64
	baseline map[string]TokenUsage
}

func captureClaudeUsageSnapshot(env []string, cwd, sessionID string) (*claudeUsageSnapshot, error) {
	configDir, err := claudeConfigDir(env, cwd)
	if err != nil {
		return nil, err
	}
	path, err := findClaudeSessionFile(configDir, sessionID)
	if err != nil {
		return nil, err
	}
	f, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("open Claude session: %w", err)
	}
	defer f.Close()
	info, err := f.Stat()
	if err != nil {
		return nil, fmt.Errorf("stat Claude session: %w", err)
	}
	baseline, _, err := readLastClaudeCostStateUsage(f, 0, info.Size())
	if err != nil {
		return nil, fmt.Errorf("read Claude usage baseline: %w", err)
	}
	return &claudeUsageSnapshot{
		path:     path,
		fileInfo: info,
		offset:   info.Size(),
		baseline: baseline,
	}, nil
}

func (s *claudeUsageSnapshot) appendedCostStateUsage() (map[string]TokenUsage, bool, error) {
	f, err := os.Open(s.path)
	if err != nil {
		return nil, false, fmt.Errorf("reopen Claude session: %w", err)
	}
	defer f.Close()
	info, err := f.Stat()
	if err != nil {
		return nil, false, fmt.Errorf("stat Claude session after exit: %w", err)
	}
	if !os.SameFile(s.fileInfo, info) {
		return nil, false, errors.New("Claude session file was replaced during execution")
	}
	if info.Size() < s.offset {
		return nil, false, errors.New("Claude session file shrank during execution")
	}
	return readLastClaudeCostStateUsage(f, s.offset, info.Size())
}

// ClaudeConfigDir resolves Claude's config directory using the same inherited
// environment and task overrides as the backend's child process.
func ClaudeConfigDir(extraEnv map[string]string, cwd string) (string, error) {
	return claudeConfigDir(buildEnv(extraEnv), cwd)
}

func claudeConfigDir(env []string, cwd string) (string, error) {
	if value, ok := lastAgentEnvValue(env, "CLAUDE_CONFIG_DIR"); ok && value != "" {
		return resolveClaudeConfigPath(value, cwd)
	}
	if runtime.GOOS == "windows" {
		if value, ok := lastAgentEnvValue(env, "USERPROFILE"); ok && value != "" {
			return resolveClaudeConfigPath(filepath.Join(value, ".claude"), cwd)
		}
	} else if value, ok := lastAgentEnvValue(env, "HOME"); ok && value != "" {
		return resolveClaudeConfigPath(filepath.Join(value, ".claude"), cwd)
	}
	home, err := os.UserHomeDir()
	if err != nil {
		return "", fmt.Errorf("resolve home directory for Claude config: %w", err)
	}
	return resolveClaudeConfigPath(filepath.Join(home, ".claude"), cwd)
}

func resolveClaudeConfigPath(path, cwd string) (string, error) {
	if filepath.IsAbs(path) {
		return filepath.Clean(path), nil
	}
	if cwd != "" {
		if !filepath.IsAbs(cwd) {
			absoluteCwd, err := filepath.Abs(cwd)
			if err != nil {
				return "", fmt.Errorf("resolve Claude working directory: %w", err)
			}
			cwd = absoluteCwd
		}
		return filepath.Clean(filepath.Join(cwd, path)), nil
	}
	absolutePath, err := filepath.Abs(path)
	if err != nil {
		return "", fmt.Errorf("resolve Claude config directory: %w", err)
	}
	return absolutePath, nil
}

func lastAgentEnvValue(env []string, key string) (string, bool) {
	for i := len(env) - 1; i >= 0; i-- {
		name, value, ok := strings.Cut(env[i], "=")
		matches := name == key
		if runtime.GOOS == "windows" {
			matches = strings.EqualFold(name, key)
		}
		if ok && matches {
			return value, true
		}
	}
	return "", false
}

func findClaudeSessionFile(configDir, sessionID string) (string, error) {
	if sessionID == "" || sessionID == "." || sessionID == ".." || strings.ContainsAny(sessionID, "/\\:\x00") {
		return "", fmt.Errorf("invalid Claude session id %q", sessionID)
	}
	projectsDir := filepath.Join(configDir, "projects")
	projects, err := os.ReadDir(projectsDir)
	if err != nil {
		return "", fmt.Errorf("read Claude projects directory: %w", err)
	}
	var bestPath string
	var bestInfo os.FileInfo
	var firstErr error
	for _, project := range projects {
		path := filepath.Join(projectsDir, project.Name(), sessionID+".jsonl")
		info, statErr := os.Stat(path)
		if statErr != nil {
			if !errors.Is(statErr, os.ErrNotExist) && firstErr == nil {
				firstErr = statErr
			}
			continue
		}
		if !info.Mode().IsRegular() {
			continue
		}
		if bestInfo == nil || info.ModTime().After(bestInfo.ModTime()) {
			bestPath = path
			bestInfo = info
		}
	}
	if bestPath != "" {
		return bestPath, nil
	}
	if firstErr != nil {
		return "", fmt.Errorf("locate Claude session: %w", firstErr)
	}
	return "", fmt.Errorf("locate Claude session %q: %w", sessionID, os.ErrNotExist)
}

func readLastClaudeCostStateUsage(f *os.File, start, end int64) (map[string]TokenUsage, bool, error) {
	if start < 0 || end < start {
		return nil, false, fmt.Errorf("invalid Claude session range [%d,%d)", start, end)
	}
	var suffix []byte
	for position := end; position > start; {
		chunkStart := max(position-claudeSessionReadChunkSize, start)
		chunk := make([]byte, position-chunkStart)
		if _, err := f.ReadAt(chunk, chunkStart); err != nil && !errors.Is(err, io.EOF) {
			return nil, false, fmt.Errorf("read Claude session: %w", err)
		}
		data := make([]byte, 0, len(chunk)+len(suffix))
		data = append(data, chunk...)
		data = append(data, suffix...)
		lines := bytes.Split(data, []byte{'\n'})
		firstComplete := chunkStart == start
		firstLine := 0
		if !firstComplete {
			suffix = append(suffix[:0], lines[0]...)
			firstLine = 1
		}
		for i := len(lines) - 1; i >= firstLine; i-- {
			line := bytes.TrimSpace(lines[i])
			if len(line) == 0 {
				continue
			}
			var envelope struct {
				Type string `json:"type"`
			}
			if err := json.Unmarshal(line, &envelope); err != nil {
				continue
			}
			if envelope.Type == "cost-state" {
				var state struct {
					ModelUsage map[string]claudeResultModelUsage `json:"modelUsage"`
				}
				if err := json.Unmarshal(line, &state); err != nil {
					continue
				}
				usage := claudeModelUsage(state.ModelUsage)
				if len(usage) == 0 {
					// An empty or newly-incompatible shape is not authoritative.
					// Keeping the stream fallback is safer than dropping usage.
					return nil, false, nil
				}
				return usage, true, nil
			}
		}
		position = chunkStart
	}
	return nil, false, nil
}

func claudeUsageHasTokens(input, output, cacheRead, cacheWrite int64) bool {
	return input > 0 || output > 0 || cacheRead > 0 || cacheWrite > 0
}

type claudeContentBlock 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     json.RawMessage `json:"input,omitempty"`
	ToolUseID string          `json:"tool_use_id,omitempty"`
	Content   json.RawMessage `json:"content,omitempty"`
}

type claudeControlRequestPayload struct {
	Subtype  string          `json:"subtype"`
	ToolName string          `json:"tool_name,omitempty"`
	Input    json.RawMessage `json:"input,omitempty"`
}

// ── Shared helpers ──

func trySend(ch chan<- Message, msg Message) bool {
	select {
	case ch <- msg:
		return true
	default:
		// Channel full — drop message. Result.Output is finalized independently,
		// so only live transcript consumers are affected.
		return false
	}
}

// claudeBlockedArgs are flags hardcoded by the daemon that must not be
// overridden by user-configured custom_args. Overriding these would break
// the daemon↔Claude communication protocol.
var claudeBlockedArgs = map[string]blockedArgMode{
	"-p":                         blockedStandalone, // non-interactive mode
	"--output-format":            blockedWithValue,  // stream-json protocol
	"--input-format":             blockedWithValue,  // stream-json protocol
	"--include-partial-messages": blockedStandalone, // incremental stream_event deltas
	"--permission-mode":          blockedWithValue,  // bypassPermissions for autonomous operation
	"--mcp-config":               blockedWithValue,  // set by daemon from agent.mcp_config
	// `--effort` is owned by the per-agent thinking_level picker so a
	// user-supplied custom_arg cannot silently outvote it. The daemon
	// injects --effort only when opts.ThinkingLevel is set; if a user
	// nevertheless writes it in custom_args we drop the duplicate and
	// log a warning rather than letting the CLI receive two conflicting
	// --effort values.
	"--effort": blockedWithValue,
}

func buildClaudeArgs(opts ExecOptions, logger *slog.Logger) []string {
	args := []string{
		"-p",
		"--output-format", "stream-json",
		"--input-format", "stream-json",
		"--verbose",
		"--include-partial-messages",
		"--permission-mode", "bypassPermissions",
		// AskUserQuestion is Claude Code's built-in interactive question tool.
		// The daemon runs Claude in non-interactive stream-json mode and has
		// no UI for the prompt to render in, so a call returns an empty
		// answer and the agent ends up "inferring" silently — the user
		// never sees the question (see GitHub #2588). User-facing
		// clarification belongs in an issue comment instead.
		"--disallowedTools", "AskUserQuestion",
	}
	if hasManagedMcpConfig(opts.McpConfig) {
		// A saved agent-level config is authoritative, including an explicitly
		// empty object. With no managed config, omit strict mode so Claude can
		// inherit the user's local runtime MCP servers.
		args = append(args, "--strict-mcp-config")
	}
	if opts.Model != "" {
		args = append(args, "--model", opts.Model)
	}
	if opts.ThinkingLevel != "" {
		// Slotted right after --model so the per-session effort runs
		// against the same model selection the args advertise; the CLI
		// itself accepts the flag in any order but this ordering makes
		// the launch line readable in `agent command` logs.
		args = append(args, "--effort", opts.ThinkingLevel)
	}
	if opts.MaxTurns > 0 {
		args = append(args, "--max-turns", fmt.Sprintf("%d", opts.MaxTurns))
	}
	// SystemPrompt is intentionally not forwarded as --append-system-prompt:
	// Claude Code loads the per-task CLAUDE.md the daemon writes into the
	// workdir, so inlining the same runtime brief would duplicate it on every
	// turn. Verified against Claude Code 2.1.220 (MUL-5392).
	if opts.ResumeSessionID != "" {
		args = append(args, "--resume", opts.ResumeSessionID)
	}
	blockedArgs := claudeBlockedArgs
	if opts.ClaudeSettingsPath != "" {
		// The daemon-owned --settings file is the enforcement layer for disabled
		// inherited skills. Drop competing per-agent/default flags only while that
		// policy is active, then append the managed file last.
		blockedArgs = make(map[string]blockedArgMode, len(claudeBlockedArgs)+1)
		for key, mode := range claudeBlockedArgs {
			blockedArgs[key] = mode
		}
		blockedArgs["--settings"] = blockedWithValue
	}
	args = append(args, filterCustomArgs(opts.ExtraArgs, blockedArgs, logger)...)
	args = append(args, filterCustomArgs(opts.CustomArgs, blockedArgs, logger)...)
	if opts.ClaudeSettingsPath != "" {
		args = append(args, "--settings", opts.ClaudeSettingsPath)
	}
	return args
}

func writeClaudeInput(w io.Writer, commandUUID string, prompts ...string) error {
	data, err := buildClaudeInput(commandUUID, prompts...)
	if err != nil {
		return err
	}
	if _, err := w.Write(data); err != nil {
		return err
	}
	return nil
}

// buildClaudeInput encodes one user frame. A non-empty commandUUID becomes the
// frame's uuid, which Claude Code echoes in command_lifecycle events.
func buildClaudeInput(commandUUID string, prompts ...string) ([]byte, error) {
	content := make([]map[string]string, 0, len(prompts))
	for _, prompt := range prompts {
		content = append(content, map[string]string{"type": "text", "text": prompt})
	}
	payload := map[string]any{
		"type": "user",
		"message": map[string]any{
			"role":    "user",
			"content": content,
		},
	}
	if commandUUID != "" {
		payload["uuid"] = commandUUID
	}
	data, err := json.Marshal(payload)
	if err != nil {
		return nil, fmt.Errorf("marshal claude input: %w", err)
	}
	return append(data, '\n'), nil
}

// resumeRejectedPhrases are the provider messages that positively identify a
// refused resume, as opposed to a failure that merely happened to occur during
// a resumed run. Shared by the stream-json backends (claude, codebuddy, qwen);
// the ACP backends match structured error codes via isACPSessionNotFound
// instead.
//
// Matching must stay tight: a false positive makes the daemon throw away a
// recoverable session pointer and re-run the task, so anything ambiguous
// belongs out of this list.
var resumeRejectedPhrases = []string{
	// Verified: claude prints this when the transcript named by --resume is
	// absent. Covered by TestResolveSessionID's existing stderr fixture.
	"no conversation found",
	// Verified: qwen-code 0.20.0, captured in
	// testdata/qwen-code-0.20.0-resume-not-found.stderr.txt — "No saved
	// session found with ID <id>. Run `qwen --resume` without an ID to
	// choose from existing sessions."
	"no saved session found",
	// Reported verbatim in multica-ai/multica#5704 against Claude Code
	// 2.1.207 (zh-CN): "400 此 session 已绑定另外的ai账号,请执行 /new 开启新
	// session". This is the account-switch guardrail this signal exists for.
	"已绑定另外",
	// INFERRED, not yet observed: the en-US wording of the same guardrail has
	// not been captured. These are guesses derived from the zh-CN text and
	// should be corrected once a real English sample is available. A miss
	// here degrades to a terminal failure carrying the provider's raw error,
	// which is diagnosable — it does not silently mis-route the run.
	"bound to another account",
	"bound to a different account",
}

// resumeWasRejected reports whether a failed run's --resume was itself
// refused. It is the positive-evidence predicate behind Result.ResumeRejected:
// only a rejected resume can be cured by starting a fresh session.
//
// texts should include every place the provider may have written the reason —
// the final error string and the stderr tail — because the account-binding 400
// arrives in the stream-json result event while "no conversation found" is
// printed to stderr.
func resumeWasRejected(requestedResume, emitted string, failed bool, texts ...string) bool {
	if !failed || requestedResume == "" {
		return false
	}
	for _, text := range texts {
		lower := strings.ToLower(text)
		for _, phrase := range resumeRejectedPhrases {
			if strings.Contains(lower, phrase) {
				return true
			}
		}
	}
	// Claude answered with a different session than the one we asked to
	// continue: the requested transcript did not load.
	return emitted != "" && emitted != requestedResume
}

// resolveSessionID decides which session id to report on the Result. A session
// known to be dead must not be persisted as the resume pointer, so a rejected
// resume reports "" regardless of what claude echoed back.
//
// This is deliberately no longer the signal the daemon reads to decide *why*
// a run failed — Result.ResumeRejected carries that. An empty SessionID is
// also produced by any failure before the first stream message (a 401, a
// missing binary), which is why inferring "the resume was rejected" from it
// was wrong in both directions.
func resolveSessionID(requestedResume, emitted string, failed bool, texts ...string) string {
	if resumeWasRejected(requestedResume, emitted, failed, texts...) {
		return ""
	}
	return emitted
}

func buildEnv(extra map[string]string) []string {
	return mergeEnv(os.Environ(), extra)
}

func claudeRootSudoPreflight(args, env []string) error {
	if !argsRequestBypassPermissions(args) || os.Geteuid() != 0 || envHasSandbox(env) {
		return nil
	}
	return fmt.Errorf("Claude Code refuses bypassPermissions under root/sudo privileges. Run the Multica daemon as a non-root user, or set IS_SANDBOX=1 if running in a genuine container/sandbox")
}

func argsRequestBypassPermissions(args []string) bool {
	for i, arg := range args {
		if arg == "--dangerously-skip-permissions" {
			return true
		}
		if arg == "--permission-mode" && i+1 < len(args) && args[i+1] == "bypassPermissions" {
			return true
		}
	}
	return false
}

func envHasSandbox(env []string) bool {
	for i := len(env) - 1; i >= 0; i-- {
		key, value, ok := strings.Cut(env[i], "=")
		if key != "IS_SANDBOX" {
			continue
		}
		if !ok {
			return false
		}
		switch strings.ToLower(value) {
		case "1", "true", "yes", "on":
			return true
		default:
			return false
		}
	}
	return false
}

func mergeEnv(base []string, extra map[string]string) []string {
	env := make([]string, 0, len(base)+len(extra))
	for _, entry := range base {
		key, _, _ := strings.Cut(entry, "=")
		// MULTICA_* in the daemon's own environment is not task context. Drop
		// the inherited namespace for every backend and append only the values
		// daemon.go explicitly assembled for this task below.
		if isFilteredChildEnvKey(key) || strings.HasPrefix(strings.ToUpper(key), "MULTICA_") {
			continue
		}
		env = append(env, entry)
	}
	for k, v := range extra {
		env = append(env, k+"="+v)
	}
	return env
}

// isFilteredChildEnvKey reports whether an inherited env var is an internal
// Claude Code runtime/session marker that must NOT leak into the spawned child
// (otherwise the child mistakes itself for a nested or resumed session, or
// inherits the parent's exec path / transport).
//
// It must NOT strip the user-facing CLAUDE_CODE_* configuration namespace
// (CLAUDE_CODE_GIT_BASH_PATH, CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX,
// CLAUDE_CODE_MAX_OUTPUT_TOKENS, CLAUDE_CODE_TMPDIR, ...): users set those
// deliberately and the child needs them. Blanket-stripping the whole prefix is
// what broke Windows — CLAUDE_CODE_GIT_BASH_PATH was silently removed, so Claude
// Code could not find bash.exe and exited immediately. Strip internal markers by
// exact name and let every other CLAUDE_CODE_* var through.
//
// The denylist holds only undocumented, per-process runtime markers. Anything in
// the public env-vars reference (https://code.claude.com/docs/en/env-vars) is
// user config and stays out of this list — including CLAUDE_CODE_TMPDIR, a
// documented temp-dir override under which Claude Code creates its own
// per-session subdir, so inheriting it is harmless.
func isFilteredChildEnvKey(key string) bool {
	switch key {
	case "CLAUDECODE", // "1" when running inside Claude Code
		"CLAUDE_CODE_ENTRYPOINT", // entrypoint marker (cli/sdk-cli/...)
		"CLAUDE_CODE_EXECPATH",   // path to the running CLI binary
		"CLAUDE_CODE_SESSION_ID", // per-session identifier
		"CLAUDE_CODE_SSE_PORT":   // IDE-extension transport port
		return true
	}
	// CLAUDECODE_* (no underscore between CLAUDE and CODE) is wholly internal;
	// keep stripping it. The user-facing config namespace is CLAUDE_CODE_*.
	return strings.HasPrefix(key, "CLAUDECODE_")
}

// blockedArgMode specifies whether a blocked arg takes a value or is standalone.
type blockedArgMode int

const (
	blockedWithValue     blockedArgMode = iota // flag takes a value (next arg or =value)
	blockedStandalone                          // flag is boolean, no value
	blockedOptionalValue                       // flag may take the next non-flag arg or =value
)

// filterCustomArgs removes protocol-critical flags from user-configured custom
// args to prevent breaking daemon↔agent communication. Each backend defines its
// own blocked set (the flags it hardcodes). This is intentionally narrow — we
// only block args that would break the communication protocol, not every
// possible dangerous flag. Workspace members are trusted to configure agents
// sensibly, same as with custom_env.
//
// Shell quoting is stripped from each arg before processing: users commonly
// type custom_args in config fields using shell syntax (e.g.
// --deny-tool='write'). Since the daemon spawns processes directly without a
// shell, those quotes would otherwise be passed literally to the child process,
// which typically rejects them as unrecognised flag values.
func filterCustomArgs(args []string, blocked map[string]blockedArgMode, logger *slog.Logger) []string {
	if len(args) == 0 {
		return args
	}
	filtered := make([]string, 0, len(args))
	for i := 0; i < len(args); i++ {
		raw := args[i]
		arg := unshellQuoteArg(raw)
		flag := arg
		hasInlineValue := false
		if idx := strings.Index(arg, "="); idx > 0 {
			flag = arg[:idx]
			hasInlineValue = true
		}
		mode, isBlocked := blocked[flag]
		if isBlocked {
			logger.Warn("custom_args: blocked protocol-critical flag, skipping", "flag", flag)
			if mode == blockedWithValue && !hasInlineValue {
				// The next arg is the value for this flag — skip it too.
				i++
			} else if mode == blockedOptionalValue && !hasInlineValue && i+1 < len(args) &&
				!strings.HasPrefix(unshellQuoteArg(args[i+1]), "-") {
				// Optional values are consumed only when the next token is not
				// another flag, so a boolean form cannot swallow an unrelated
				// option.
				i++
			}
			continue
		}
		filtered = append(filtered, arg)
	}
	return filtered
}

// unshellQuoteArg strips a single layer of shell-style single or double quotes
// from an argument. It handles two forms:
//
//   - --flag='value' or --flag="value" → --flag=value
//   - 'standalone' or "standalone"     → standalone
//
// Only flag-style args (`-x=…`, `--flag=…`) get inline value unquoting. Plain
// assignment syntax like `model="o3"` is left alone because the quotes may be
// semantic for the child process (for example Codex `-c model="o3"`). Only
// matching outer quotes are stripped; no escape processing is done.
func unshellQuoteArg(arg string) string {
	if strings.HasPrefix(arg, "-") {
		if idx := strings.Index(arg, "="); idx > 0 {
			value := arg[idx+1:]
			if unquoted, ok := stripSurroundingQuotes(value); ok {
				return arg[:idx+1] + unquoted
			}
			return arg
		}
	}
	if unquoted, ok := stripSurroundingQuotes(arg); ok {
		return unquoted
	}
	return arg
}

// stripSurroundingQuotes removes a matching outer pair of single or double
// quotes from s and returns (unquoted, true). Returns (s, false) if s does not
// start and end with the same quote character.
func stripSurroundingQuotes(s string) (string, bool) {
	if len(s) >= 2 {
		if (s[0] == '\'' && s[len(s)-1] == '\'') || (s[0] == '"' && s[len(s)-1] == '"') {
			return s[1 : len(s)-1], true
		}
	}
	return s, false
}

// writeMcpConfigToTemp writes MCP config JSON to a temporary file and returns
// its path. The caller is responsible for removing it via cleanupMcpConfigTemp.
func writeMcpConfigToTemp(raw json.RawMessage) (string, error) {
	dir, err := os.MkdirTemp("", "multica-mcp-*")
	if err != nil {
		return "", fmt.Errorf("create mcp config temp dir: %w", err)
	}
	data, err := hardenBrowserMcpConfig(raw, dir)
	if err != nil {
		cleanupMcpConfigTemp(filepath.Join(dir, "mcp-config.json"))
		return "", err
	}
	path := filepath.Join(dir, "mcp-config.json")
	if err := os.WriteFile(path, data, 0o600); err != nil {
		cleanupMcpConfigTemp(path)
		return "", fmt.Errorf("write mcp config temp file: %w", err)
	}
	return path, nil
}

func cleanupMcpConfigTemp(path string) {
	if path == "" {
		return
	}
	dir := filepath.Dir(path)
	if strings.HasPrefix(filepath.Base(dir), "multica-mcp-") {
		_ = os.RemoveAll(dir)
		return
	}
	_ = os.Remove(path)
}

// detectVersionTimeout bounds a single `<cli> --version` probe. Version
// detection runs inside the daemon's blocking preflight (registerRuntimesForWorkspace),
// so a CLI that never returns from `--version` — e.g. a brew-installed claude
// wedged by a bun regression (MUL-3812) — would otherwise stall the whole
// registration loop, the daemon would never flip /health from "starting" to
// "running", and *every* runtime on the host would appear disconnected. A real
// `--version` returns well under this bound even on a cold cache or with
// Windows AV scanning; the timeout exists only to fail a wedged probe fast and
// in isolation so the remaining runtimes still register. A var (not const) so
// tests can shrink it without waiting out the real bound.
var detectVersionTimeout = 10 * time.Second

// Keep the deadline in the error chain without its network-timeout wording:
// task failures are also classified from the diagnostic text.
type versionProbeTimeoutError struct {
	limit time.Duration
	cause error
}

func (e *versionProbeTimeoutError) Error() string {
	return fmt.Sprintf("version probe timed out (limit %s): %v", e.limit, e.cause)
}

func (e *versionProbeTimeoutError) Unwrap() []error {
	return []error{context.DeadlineExceeded, e.cause}
}

func detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, detectVersionTimeout)
	defer cancel()
	probeCmd, cleanup, err := runtimeCmd.withProbeDirectory()
	if err != nil {
		return "", fmt.Errorf("detect version for %s: %w", runtimeCmd, ExplainExecError(err))
	}
	defer cleanup()
	runtimeCmd = probeCmd
	if runtime.GOOS == "windows" {
		if native := resolveCodeArtsNativeFromShim(runtimeCmd.Path, os.Stat); native != "" {
			runtimeCmd.Path = native
		}
	}

	// outputOwned, not the collector in run_collect_quiet.go, and the difference
	// is which signal means "the answer is in". A broken CLI (node/bun shim) can
	// leave grandchildren that inherited and still hold our stdout pipe open, and
	// os/exec's Wait blocks until those pipes reach EOF — which is why this call
	// carries a WaitDelay backstop, and why the deadline above needs one at all.
	//
	// An earlier revision of this branch used the collector here, so that Wait
	// returned on the *direct child's* exit whatever a descendant was holding.
	// That is wrong on this path: a wrapper may exit successfully while the real
	// CLI, its descendant, still owes us the version. Review measured it — the
	// wrapper exits 0, its child prints the version 500ms later, and treating
	// leader exit as completion killed the child and returned an empty version
	// with a nil error, where outputOwned returns the version. Pipe EOF is the
	// only signal that means "no more output is coming"; leader exit does not.
	//
	// What this branch still fixes here is the *reporting*: a lingering
	// descendant makes Wait hit WaitDelay and report exec.ErrWaitDelay even
	// though the version arrived, and a failed --version probe skips runtime
	// registration entirely (#6084 reverted a WaitDelay backstop over exactly
	// that). So the error is dropped when — and only when — the answer itself is
	// present. See salvageProbeAnswer.
	//
	// Built through runtimeCmd.exec so a custom runtime's fixed_args prefix is
	// still applied (MUL-6260). Desktop ZCode ships as a Node .cjs/.mjs bundle;
	// those and Linux Electron entries use the same headless invocation as
	// Execute, with a clear error when the required runtime or script is missing.
	_, zcodeDesktop := zcodeDesktopScript(runtimeCmd.Path)
	if isNodeScriptPath(runtimeCmd.Path) || zcodeDesktop {
		if err := requireNodeForZcodeScript(runtimeCmd.Path); err != nil {
			return "", err
		}
	}

	// A provider-specific probe (see Command.ForVersionProbe) runs first. A
	// build too old to know it rejects the arguments outright, and only that
	// case falls back to `--version`: a probe that hung or could not start would
	// fail the same way again, and here it would also spend the remaining
	// budget on the side effects the provider-specific probe exists to avoid.
	if len(runtimeCmd.versionArgs) > 0 {
		version, err := runVersionProbe(ctx, runtimeCmd, runtimeCmd.versionArgs)
		if err == nil {
			return version, nil
		}
		if !versionProbeRejectedArgs(ctx, err) {
			return "", fmt.Errorf("detect version for %s: %w", runtimeCmd, ExplainExecError(err))
		}
		if runtimeCmd.logger != nil {
			runtimeCmd.logger.Debug("agent: CLI rejected its version probe; falling back to --version",
				"command", runtimeCmd.String(), "probe", strings.Join(runtimeCmd.versionArgs, " "), "err", err)
		}
	}

	version, err := runVersionProbe(ctx, runtimeCmd, []string{"--version"})
	if err != nil {
		// One provider-agnostic boundary for probes: DetectVersion routes every
		// provider through here, so an ENOEXEC diagnosis added at this point
		// reaches the reason the daemon reports for a skipped runtime
		// (MUL-6164).
		return "", fmt.Errorf("detect version for %s: %w", runtimeCmd, ExplainExecError(err))
	}
	return version, nil
}

// versionProbeRejectedArgs reports whether a failed provider-specific version
// probe is the CLI refusing its arguments: the process ran and exited non-zero
// on its own, before the deadline. A kill on timeout also surfaces as an
// *exec.ExitError, with exit code -1, which is why both the code and the
// context are checked.
func versionProbeRejectedArgs(ctx context.Context, err error) bool {
	if ctx.Err() != nil {
		return false
	}
	var exitErr *exec.ExitError
	return errors.As(err, &exitErr) && exitErr.ExitCode() > 0
}

// runVersionProbe runs one `<cli> <args>` version probe and returns the
// recognised version line. detectCLIVersion adds the command and the exec
// diagnosis to any probe error.
func runVersionProbe(ctx context.Context, runtimeCmd Command, args []string) (string, error) {
	var cmd *exec.Cmd
	_, zcodeDesktop := zcodeDesktopScript(runtimeCmd.Path)
	if isNodeScriptPath(runtimeCmd.Path) || zcodeDesktop {
		cmd, _, _ = runtimeCmd.execVia(ctx, chooseZcodeInvocation, runtimeCmd.Path, args, runtimeCmd.logger)
		if zcodeDesktop {
			cmd.Env = zcodeRuntimeEnv(runtimeCmd.Path, os.Environ())
		}
	} else {
		cmd = runtimeCmd.exec(ctx, args...)
	}
	hideAgentWindow(cmd)
	cmd.WaitDelay = probeWaitDelay
	data, err := outputOwned(cmd, runtimeCmd.logger)
	version, recognised := extractVersionLine(string(data))
	if err != nil {
		// recognised, not `version != ""`. The two differ exactly where it
		// matters: extractVersionLine falls back to the trimmed raw output when
		// no line carries a semver token, so non-empty means "the CLI printed
		// something", which on this path may be a banner its wrapper emitted
		// before the real version existed. Review measured that — a stub
		// printing "initializing plugins", exiting 0, with the version arriving
		// after WaitDelay — registering `initializing plugins` as the version
		// with a nil error. A salvage decision needs the stronger question, so
		// it asks whether a version was actually recognised.
		//
		// The fallback still stands on the success path: a CLI that exits 0 with
		// an unusual version format is reporting its version, and dropping that
		// to empty would be a regression (#2516). It is only unusable as
		// evidence that a *bounded, incomplete* read already contains the
		// answer.
		if salvageProbeAnswer(runtimeCmd, strings.Join(args, " "), recognised, err) {
			return version, nil
		}
		if ctx.Err() == context.DeadlineExceeded {
			return "", &versionProbeTimeoutError{limit: detectVersionTimeout, cause: err}
		}
		return "", err
	}
	return version, nil
}

// salvageProbeAnswer decides whether a one-shot probe that produced its answer
// may ignore the error os/exec reported, and logs the decision.
//
// It exists for one shape: the CLI printed what we asked for, and then something
// about its *lifecycle* failed — a descendant held the output pipes past
// cmd.WaitDelay (exec.ErrWaitDelay), so Wait reports failure over an answer that
// is already in the buffer. OpenClaw does this on every invocation: it forks an
// `openclaw-config` helper that inherits stdout. #6084 measured that shape,
// tried a WaitDelay backstop, and reverted it on review precisely because the
// call then fails; MUL-5467 is the follow-up.
//
// Deliberately narrow, because "we have output" must never be confused with "we
// have the answer":
//
//   - answered is the caller's own *recognition* of the answer, not a length
//     check and not a parse that falls back to accepting anything. A version is
//     salvaged only if extractVersionLine matched a version-shaped line — its
//     trimmed-raw fallback does not qualify, since a wrapper's banner satisfies
//     it — and a catalog only if it parsed.
//   - Only ErrWaitDelay qualifies. A non-zero exit still fails: a CLI that
//     printed something and then exited 1 is reporting a problem, and its stderr
//     is the diagnosis. Cancellation and deadlines still fail too — reaching the
//     deadline means the CLI never finished, and this is not the layer that
//     decides a timeout was acceptable.
func salvageProbeAnswer(runtimeCmd Command, probe string, answered bool, err error) bool {
	if !answered || !errors.Is(err, exec.ErrWaitDelay) {
		return false
	}
	if runtimeCmd.logger != nil {
		runtimeCmd.logger.Warn("agent: CLI answered but left its output pipes open; "+
			"using the answer and reaping the tree",
			"command", runtimeCmd.String(), "probe", probe, "err", err)
	}
	return true
}

// extractVersionLine pulls the version line out of a `<cli> --version` capture,
// discarding leading shell noise. On Windows, npm-installed CLI shims (notably
// gemini's) emit `chcp` output like `Active code page: 65001` before the real
// version reaches stdout, and the raw concatenation was being persisted as the
// runtime version (see #2516).
//
// The heuristic: return the first non-empty line that contains a semver-shaped
// token (matches versionRe). Full version strings like "2.1.5 (Claude Code)"
// or "codex-cli 0.118.0" survive unchanged because the whole matching line is
// returned. If no line carries a semver token, fall back to the trimmed raw
// output so unusual version formats aren't silently dropped to empty.
//
// The second return reports whether that scan actually matched, i.e. whether the
// first return is a recognised version or only the fallback. It exists because
// the fallback accepts *any* non-empty text, which is fine when the CLI exited
// cleanly (it said what it says) and unusable as evidence when a caller has to
// decide whether an incomplete read already holds the answer — see
// salvageProbeAnswer.
func extractVersionLine(raw string) (string, bool) {
	for _, line := range strings.Split(raw, "\n") {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		if versionRe.MatchString(line) {
			return line, true
		}
	}
	return strings.TrimSpace(raw), false
}

// logWriter adapts a *slog.Logger to an io.Writer for capturing stderr.
type logWriter struct {
	logger *slog.Logger
	prefix string
}

func newLogWriter(logger *slog.Logger, prefix string) *logWriter {
	return &logWriter{logger: logger, prefix: prefix}
}

func (w *logWriter) Write(p []byte) (int, error) {
	text := strings.TrimSpace(string(p))
	if text != "" {
		w.logger.Debug(w.prefix + text)
	}
	return len(p), nil
}