Skip to content

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

Go
44.3 KB
Raw Blame
package agent

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"maps"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"time"
)

// antigravityBackend implements Backend by spawning Google's Antigravity CLI
// with a one-shot prompt (`agy -p <prompt>`). Despite the upstream flag name,
// current agy print mode is still capable of running Antigravity tools; it is
// the daemon-compatible mode because `agy -i` requires an attached TTY. Unlike
// Claude / Codex / Cursor / Gemini, older Antigravity CLI releases exposed only
// plain assistant text. agy 1.1.8 added stream-json output with per-turn token
// usage, so the backend consumes that format while retaining plain-text
// handling for diagnostics and test executables.
//
// agy 1.0.14's print mode regressed this stdout contract: a turn can run tools
// and produce a final reply while emitting ZERO bytes to stdout (the log shows
// "PlannerResponse without ModifiedResponse encountered"). Exit code is 0 and
// no error is logged, so a blank-but-"completed" run reaches the daemon and the
// user sees an empty result even though the work happened (MUL-3726, #4595).
// When stdout comes back empty on an otherwise-completed turn, the backend
// therefore recovers the assistant text agy durably wrote to its per-
// conversation transcript (see readAntigravityTranscriptOutput).
//
// Session resumption uses `--conversation <id>`. The conversation id is not
// emitted on stdout; we capture it by routing `--log-file` to a temp file and
// scanning its glog-formatted lines for the `conversation=<uuid>` token that
// printmode.go logs at message-send time.
//
// Print mode reads no input after the prompt, so steering a running turn goes
// through a PreInvocation workspace hook instead (see
// antigravitySupplementSession).
type antigravityBackend struct {
	cfg Config
}

type antigravityStreamUsage struct {
	InputTokens      int64 `json:"input_tokens"`
	OutputTokens     int64 `json:"output_tokens"`
	ThinkingTokens   int64 `json:"thinking_tokens"`
	CacheReadTokens  int64 `json:"cache_read_tokens"`
	CacheWriteTokens int64 `json:"cache_write_tokens"`
	TotalTokens      int64 `json:"total_tokens"`
}

type antigravityStreamStepUpdate struct {
	ConversationID string                  `json:"conversation_id"`
	StepIndex      *int                    `json:"step_index"`
	State          string                  `json:"state"`
	StepType       string                  `json:"step_type"`
	TextDelta      string                  `json:"text_delta"`
	Usage          *antigravityStreamUsage `json:"usage"`
	ToolName       string                  `json:"tool_name"`
	ToolInfo       *antigravityStreamTool  `json:"tool_info"`
}

type antigravityStreamTool struct {
	Name       string          `json:"name"`
	Parameters map[string]any  `json:"parameters"`
	Output     json.RawMessage `json:"output"`
	Error      *struct {
		Type    string `json:"type"`
		Message string `json:"message"`
	} `json:"error"`
}

type antigravityToolState struct {
	name string
	done bool
}

// Normalize the shared transcript input without duplicating commands or file
// bodies. Preserve collisions and unknown fields, and do not mutate the snapshot.
func antigravityToolInput(parameters map[string]any) map[string]any {
	input := maps.Clone(parameters)
	for _, alias := range []struct {
		from, to   string
		allowEmpty bool
	}{
		{"CommandLine", "command", false},
		{"AbsolutePath", "file_path", false},
		{"TargetFile", "file_path", false},
		{"CodeContent", "content", true},
		{"TargetContent", "old_string", true},
		{"ReplacementContent", "new_string", true},
	} {
		if _, exists := input[alias.to]; exists {
			continue
		}
		if value, ok := parameters[alias.from].(string); ok && (value != "" || alias.allowEmpty) {
			input[alias.to] = value
			delete(input, alias.from)
		}
	}
	return input
}

// Each step has one tool lifecycle, even when agy repeats state snapshots or
// only emits DONE. The existing daemon uploader handles these normal messages;
// tool output must never be appended to the assistant's final answer.
func antigravityToolMessages(step *antigravityStreamStepUpdate, states map[int]antigravityToolState) []Message {
	if step.StepType != "tool" || step.StepIndex == nil || *step.StepIndex < 0 {
		return nil
	}
	active := strings.EqualFold(step.State, "active")
	done := strings.EqualFold(step.State, "done")
	if !active && !done {
		return nil
	}
	index := *step.StepIndex
	state := states[index]
	if state.done {
		return nil
	}
	callID := fmt.Sprintf("agy-step-%d", index)
	var messages []Message
	if state.name == "" {
		name := step.ToolName
		var input map[string]any
		if step.ToolInfo != nil {
			if name == "" {
				name = step.ToolInfo.Name
			}
			input = antigravityToolInput(step.ToolInfo.Parameters)
		}
		if name == "" {
			return nil // A later snapshot may provide the missing metadata.
		}
		state.name = name
		messages = append(messages, Message{Type: MessageToolUse, Tool: name, CallID: callID, Input: input})
	}
	if done {
		var output string
		if info := step.ToolInfo; info != nil {
			if len(info.Output) > 0 && string(info.Output) != "null" {
				if err := json.Unmarshal(info.Output, &output); err != nil {
					output = string(info.Output)
				}
			}
			if info.Error != nil {
				detail := info.Error.Message
				if info.Error.Type != "" {
					if detail != "" {
						detail = info.Error.Type + ": " + detail
					} else {
						detail = info.Error.Type
					}
				}
				// The daemon uploads a bounded prefix of tool output. Put the
				// error first so verbose stdout cannot hide the failure detail.
				if output != "" {
					output = "\n" + output
				}
				output = "Tool error: " + detail + output
			}
		}
		messages = append(messages, Message{Type: MessageToolResult, Tool: state.name, CallID: callID, Output: output})
		state.done = true
	}
	states[index] = state
	return messages
}

type antigravityStreamResult struct {
	ConversationID string                  `json:"conversation_id"`
	Status         string                  `json:"status"`
	Response       string                  `json:"response"`
	Error          string                  `json:"error"`
	Usage          *antigravityStreamUsage `json:"usage"`
}

type antigravityStreamEvent struct {
	Event          string `json:"event"`
	ConversationID string `json:"conversation_id"`
	Init           struct {
		Model string `json:"model"`
	} `json:"init"`
	StepUpdate *antigravityStreamStepUpdate `json:"step_update"`
	Result     *antigravityStreamResult     `json:"result"`
}

type antigravityStepSummary struct {
	kind, state string
	hasText     bool
}

type antigravityTurn struct {
	start *int
	// injected holds the user_input steps that appeared while steering
	// guidance was in flight; checkTranscript is set until the transcript
	// shows which guidance they carried, and rescanTranscript until the next
	// check has read it from the start.
	injected         map[int]bool
	checkTranscript  bool
	rescanTranscript bool
	steps            map[int]antigravityStepSummary
	invalid          bool
}

// observeUserInput classifies a user_input step. The first one opens the turn;
// a later one is valid only while injected steering guidance awaits its step.
func (t *antigravityTurn) observeUserInput(index int, supplements *antigravitySupplementSession) {
	switch {
	case t.start == nil:
		t.start = &index
	case *t.start == index || t.injected[index]:
	case supplements.awaitingReceipt():
		if t.injected == nil {
			t.injected = make(map[int]bool)
		}
		t.injected[index] = true
		t.checkTranscript, t.rescanTranscript = true, true
	default:
		t.invalid = true
	}
}

// confirmInjected settles guidance whose marker the transcript shows in a
// USER_INPUT record. A step another hook injected carries no marker and
// settles nothing, so the guidance it displaced fails at the end of the turn
// and falls back.
func (t *antigravityTurn) confirmInjected(supplements *antigravitySupplementSession, transcript *antigravityTranscript, conversationID string) {
	if !t.checkTranscript {
		return
	}
	// agy can rewrite the transcript in place when it compacts, leaving the
	// remembered offset inside an unrelated line. A new step is rare, so read
	// the whole file once for it; later checks only read what was added.
	if t.rescanTranscript {
		transcript.offset, t.rescanTranscript = 0, false
	}
	transcript.scan(conversationID, supplements.inflightMarkers(), supplements.receipt)
	t.checkTranscript = supplements.awaitingReceipt()
}

func (t *antigravityTurn) settledResponse() int {
	latest := -1
	for index, step := range t.steps {
		if step.kind == "agent_response" && index > latest {
			latest = index
		}
	}
	for index, step := range t.steps {
		if index > latest && (step.state != "DONE" || step.kind == "error_message" ||
			step.kind == "tool" || step.kind == "subagent" || step.kind == "agent_response" || step.kind == "user_input") {
			return -1
		}
	}
	return latest
}

func (t *antigravityTurn) completed(response string) bool {
	latest := t.settledResponse()
	return !t.invalid && strings.TrimSpace(response) != "" && t.start != nil && t.steps[*t.start].state == "DONE" &&
		latest > *t.start && t.steps[latest].state == "DONE" && t.steps[latest].hasText
}

// antigravityNetworkIssueError is the provider sentence some agy releases
// report when a trailing round trip fails. It carries no Go error text, so it
// has to stay a literal match alongside the transport patterns below.
const antigravityNetworkIssueError = "There was a network issue connecting to the server, please try again."

// agy 1.4.6 may carry this historical/recovered stream error into a resumed
// turn's result even when the current final response is DONE (#9528).
const antigravityStreamInterruptedError = "The stream was interrupted. Please continue the task you were working on."

// antigravityTransportErrorRe matches the causes Go's http client reports when
// a round trip never produced a response: socket, DNS and TLS failures. These
// are the strings that appear inside the `*url.Error` agy wraps as
// `API error (attempt N): request failed: Post "...": <cause>`.
//
// Two things are deliberately excluded.
//
//   - agy's own `request failed:` prefix. It is tempting to match it directly
//     since it marks an http.Client failure, but only one spelling has been
//     observed in the field, and nothing rules out agy reusing the same prefix
//     for an HTTP status error. Matching the cause keeps a provider rejection
//     from being read as transport noise.
//   - Provider-side rejections: quota, capacity, overload, policy and auth all
//     arrive as an HTTP response, so they are decisions about the request
//     rather than a failure to deliver it. Those must stay failures the user
//     sees instead of being smoothed over by a complete-looking answer —
//     reportTaskResult documents failing closed for exactly that reason.
var antigravityTransportErrorRe = regexp.MustCompile(`(?i)(\bEOF\b|connection reset by peer|broken pipe|connection refused|connection timed out|i/o timeout|tls handshake timeout|tls: handshake failure|use of closed network connection|network is unreachable|no such host|server misbehaving|malformed HTTP response|http2: client connection lost|http2: server sent GOAWAY)`)

// antigravityTrailingTransportError reports whether agy's provider error
// describes a transport-level failure rather than a decision the provider made
// about the request.
func antigravityTrailingTransportError(providerError string) bool {
	trimmed := strings.TrimSpace(providerError)
	if trimmed == "" {
		return false
	}
	if strings.EqualFold(trimmed, antigravityNetworkIssueError) || strings.EqualFold(trimmed, antigravityStreamInterruptedError) {
		return true
	}
	return antigravityTransportErrorRe.MatchString(trimmed)
}

func (u antigravityStreamUsage) hasTokens() bool {
	return u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0
}

// tokenUsage maps agy's provider-defined buckets directly. Cache reads are
// separate from input_tokens even when total_tokens equals input + output; the
// official structured-output examples include cache reads larger than input.
// thinking_tokens is already included in output_tokens and must not be added
// again.
func (u antigravityStreamUsage) tokenUsage() TokenUsage {
	return TokenUsage{
		InputTokens:      nonNegativeTokens(u.InputTokens),
		OutputTokens:     nonNegativeTokens(u.OutputTokens),
		CacheReadTokens:  nonNegativeTokens(u.CacheReadTokens),
		CacheWriteTokens: nonNegativeTokens(u.CacheWriteTokens),
	}
}

func sumAntigravityStepUsage(steps map[int]TokenUsage) (TokenUsage, bool) {
	var total TokenUsage
	for _, step := range steps {
		total.InputTokens += step.InputTokens
		total.OutputTokens += step.OutputTokens
		total.CacheReadTokens += step.CacheReadTokens
		total.CacheWriteTokens += step.CacheWriteTokens
	}
	return total, len(steps) > 0
}

func antigravityResultStatus(status string) string {
	switch strings.ToUpper(strings.TrimSpace(status)) {
	case "", "SUCCESS", "COMPLETED":
		return "completed"
	case "CANCELLED", "CANCELED":
		return "cancelled"
	case "ABORTED":
		return "aborted"
	case "TIMEOUT", "TIMED_OUT":
		return "timeout"
	default:
		return "failed"
	}
}

// antigravityCompletedDespiteTrailingNetworkError reports whether a turn that
// agy ended in an error actually delivered a finished answer first. All three
// conditions are required: the trailing failure has to be transport-level (a
// provider-side rejection is a real failure), agy has to have handed back a
// non-empty canonical response, and the latest agent_response step has to have
// reached DONE — an ACTIVE step means the answer was still being written when
// the connection went away. The stream-interrupted sentence also requires a
// successful process exit, since a DONE step can precede a genuinely interrupted
// tool call in the same turn.
func antigravityCompletedDespiteTrailingNetworkError(providerError, response string, agentResponseDone, exitedSuccessfully bool) bool {
	if strings.EqualFold(strings.TrimSpace(providerError), antigravityStreamInterruptedError) && !exitedSuccessfully {
		return false
	}
	return antigravityTrailingTransportError(providerError) &&
		strings.TrimSpace(response) != "" &&
		agentResponseDone
}

var antigravitySelectedModelRe = regexp.MustCompile(
	`Propagating selected model override to backend:\s*label="([^"\r\n]+)"`,
)

func readAntigravitySelectedModel(logPath, streamModel, configuredModel string) string {
	if model := strings.TrimSpace(streamModel); model != "" {
		return model
	}
	if logPath != "" {
		if data, err := os.ReadFile(logPath); err == nil {
			matches := antigravitySelectedModelRe.FindAllSubmatch(data, -1)
			if len(matches) > 0 {
				return strings.TrimSpace(string(matches[len(matches)-1][1]))
			}
		}
	}
	if model := strings.TrimSpace(configuredModel); model != "" {
		return model
	}
	return "unknown"
}

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

	// Guard against agy's silent no-op on an unrecognised --model: it exits 0
	// with empty output, which would otherwise surface as a "completed" but
	// empty task. opts.Model is the single funnel for both agent.model and the
	// daemon-wide MULTICA_ANTIGRAVITY_MODEL default (resolved in daemon.go), so
	// validating it here covers every source — UI free-text, API, a persisted
	// value, and the env default alike. Reject a non-empty model the installed
	// CLI definitively does not advertise, with an actionable error. Validation
	// is fail-OPEN: if the `agy models` catalog can't be discovered we let agy
	// resolve the value itself rather than blocking the run on a discovery
	// hiccup (see antigravityModelError).
	if opts.Model != "" {
		catalog, _ := ListModels(ctx, "antigravity", b.cfg.commandAt(execPath))
		if err := antigravityModelError(opts.Model, catalog.Models); err != nil {
			return nil, err
		}
	}

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

	logFile, err := os.CreateTemp("", "multica-agy-log-*.log")
	if err != nil {
		cancel()
		return nil, fmt.Errorf("create agy log file: %w", err)
	}
	logPath := logFile.Name()
	_ = logFile.Close()

	if opts.SkillInvocation != nil {
		prompt = opts.SkillInvocation.antigravityPrompt(supportsAntigravitySlashSkills(runCtx, b.cfg, execPath, opts))
	}

	args := buildAntigravityArgs(prompt, logPath, timeout, opts, b.cfg.Logger)

	cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)
	hideAgentWindow(cmd)
	b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))
	cmd.WaitDelay = 10 * time.Second
	if opts.Cwd != "" {
		cmd.Dir = opts.Cwd
	}
	cmd.Env = buildEnv(b.cfg.Env)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		cancel()
		_ = os.Remove(logPath)
		return nil, fmt.Errorf("agy stdout pipe: %w", err)
	}

	var supplements *antigravitySupplementSession
	var supplementErr error
	if opts.EnableTaskSupplement {
		supplements, supplementErr = startAntigravitySupplementSession(runCtx, opts.Cwd, opts.SupplementHookCommand, b.cfg.Logger)
		if supplementErr != nil {
			b.cfg.Logger.Warn("agy additional messages unavailable for this run", "error", supplementErr)
			supplements = nil
		} else {
			cmd.Env = append(cmd.Env, supplements.env()...)
		}
	}
	stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[agy:stderr] "), agentStderrTailBytes)
	cmd.Stderr = stderrBuf

	if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
		supplements.close()
		cancel()
		_ = os.Remove(logPath)
		return nil, fmt.Errorf("start agy: %w", err)
	}

	b.cfg.Logger.Info("agy started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)

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

	go func() {
		<-runCtx.Done()
		_ = stdout.Close()
	}()

	go func() {
		defer cancel()
		defer close(msgCh)
		defer close(resCh)
		defer os.Remove(logPath)
		defer supplements.close()

		startTime := time.Now()
		var output strings.Builder
		var streamModel string
		var streamSessionID string
		var streamResultStatus string
		var streamResultError string
		var streamResponse string
		var streamResultUsage *antigravityStreamUsage
		streamStepUsage := make(map[int]TokenUsage)
		streamTools := make(map[int]antigravityToolState)
		turn := antigravityTurn{steps: make(map[int]antigravityStepSummary)}
		transcript := &antigravityTranscript{logPath: logPath}
		finalStatus := "completed"
		var finalError string

		scanner := newAgentStreamScanner(stdout)

		trySend(msgCh, Message{Type: MessageStatus, Status: "running"})
		// Announce the conversation id the moment agy names it so the daemon
		// pins the resume pointer mid-run. A run that is cancelled or killed
		// never reaches the terminal Result, and without the pin its follow-up
		// would start a brand-new conversation.
		var announcedSessionID string
		announceSession := func(id string) {
			if id == "" || id == announcedSessionID {
				return
			}
			announcedSessionID = id
			trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: id})
		}

	streamLoop:
		for scanner.Scan() {
			line := scanner.Text()
			var event antigravityStreamEvent
			if err := json.Unmarshal([]byte(line), &event); err == nil && event.Event != "" {
				switch event.Event {
				case "init":
					streamSessionID = event.ConversationID
					streamModel = event.Init.Model
					supplements.activate(streamSessionID)
					announceSession(streamSessionID)
				case "step_update":
					if event.StepUpdate == nil {
						turn.invalid = true
						continue
					}
					step := event.StepUpdate
					if idx := step.StepIndex; idx == nil || *idx < 0 {
						turn.invalid = true
					} else {
						if step.StepType == "user_input" {
							turn.observeUserInput(*idx, supplements)
						}
						turn.steps[*idx] = antigravityStepSummary{
							kind: step.StepType, state: strings.ToUpper(step.State),
							hasText: turn.steps[*idx].hasText || strings.TrimSpace(step.TextDelta) != "",
						}
					}
					if event.StepUpdate.ConversationID != "" {
						streamSessionID = event.StepUpdate.ConversationID
						supplements.activate(streamSessionID)
						announceSession(streamSessionID)
					}
					turn.confirmInjected(supplements, transcript, streamSessionID)
					for _, message := range antigravityToolMessages(event.StepUpdate, streamTools) {
						// Tool lifecycle events also drive the daemon's in-flight
						// counter. Unlike best-effort text, neither half may be
						// dropped when a transcript consumer temporarily falls behind.
						select {
						case msgCh <- message:
						case <-runCtx.Done():
							break streamLoop
						}
					}
					if event.StepUpdate.StepType == "agent_response" && event.StepUpdate.TextDelta != "" {
						output.WriteString(event.StepUpdate.TextDelta)
						trySend(msgCh, Message{Type: MessageText, Content: event.StepUpdate.TextDelta})
					}
					if strings.EqualFold(event.StepUpdate.State, "done") && event.StepUpdate.StepIndex != nil && event.StepUpdate.Usage != nil && event.StepUpdate.Usage.hasTokens() {
						// A step may be re-emitted as its state changes. Keying by
						// index makes the final DONE snapshot replace, not duplicate,
						// an earlier copy of the same step.
						streamStepUsage[*event.StepUpdate.StepIndex] = event.StepUpdate.Usage.tokenUsage()
					}
				case "result":
					if event.Result == nil {
						continue
					}
					turn.confirmInjected(supplements, transcript, streamSessionID)
					supplements.end()
					if event.Result.ConversationID != "" {
						streamSessionID = event.Result.ConversationID
					}
					streamResultStatus = event.Result.Status
					streamResultError = event.Result.Error
					streamResponse = event.Result.Response
					if event.Result.Usage != nil && event.Result.Usage.hasTokens() {
						streamResultUsage = event.Result.Usage
					}
				}
				continue
			}
			// The daemon concatenates streamed MessageText with no separator
			// (pendingText.WriteString), so the streamed text must carry the
			// line breaks itself. Mirror output's construction — prefix the
			// newline on every line after the first, and stream blank lines
			// too — so the persisted task_message text reconstructs output
			// exactly. Emitting bare, blank-skipped lines dropped every newline,
			// collapsing block markdown (headings, lists) onto one line in
			// chat (#6149).
			chunk := line
			if output.Len() > 0 {
				output.WriteByte('\n')
				chunk = "\n" + line
			}
			output.WriteString(line)
			if chunk != "" {
				trySend(msgCh, Message{Type: MessageText, Content: chunk})
			}
		}
		if err := scanner.Err(); err != nil {
			b.cfg.Logger.Warn("agy stdout scanner error", "err", err)
		}

		turn.confirmInjected(supplements, transcript, streamSessionID)
		supplements.end()
		waitErr := cmd.Wait()
		releaseProcessGroup(cmd)
		// Remove the managed hooks before the result is reported, so a
		// follow-up run never observes them.
		supplements.close()
		duration := time.Since(startTime)

		sessionID := streamSessionID
		if sessionID == "" {
			sessionID = readAntigravityConversationID(logPath)
		}

		if runCtx.Err() == context.DeadlineExceeded {
			finalStatus = "timeout"
			finalError = fmt.Sprintf("agy timed out after %s", timeout)
		} else if runCtx.Err() == context.Canceled {
			finalStatus = "aborted"
			finalError = "execution cancelled"
		} else if status := antigravityResultStatus(streamResultStatus); finalStatus == "completed" && status != "completed" {
			recovered := strings.EqualFold(strings.TrimSpace(streamResultStatus), "ERROR") && waitErr == nil && turn.completed(streamResponse)
			if latest := turn.settledResponse(); turn.start == nil && latest >= 0 {
				recovered = antigravityCompletedDespiteTrailingNetworkError(streamResultError, streamResponse, turn.steps[latest].state == "DONE", waitErr == nil)
			}
			if recovered {
				b.cfg.Logger.Warn("agy reported an error after a completed response", "err", streamResultError)
			} else {
				// Prefer the provider's structured error even when agy also exits
				// non-zero; the process status alone discards the actionable cause.
				finalStatus = status
				finalError = streamResultError
				if finalError == "" {
					finalError = fmt.Sprintf("agy returned status %s", streamResultStatus)
				}
			}
		} else if waitErr != nil && finalStatus == "completed" {
			finalStatus = "failed"
			finalError = fmt.Sprintf("agy exited with error: %v", waitErr)
		} else if finalStatus == "completed" && antigravityPrintTimedOut(logPath) {
			// agy hit its own --print-timeout: it printed "Error: timed out
			// waiting for response" to stdout and EXITED 0, so runCtx never
			// tripped and waitErr is nil — the checks above leave the turn as
			// "completed". Surface it as a real timeout instead of a truncated
			// success the user can't distinguish from a finished task (MUL-3570).
			finalStatus = "timeout"
			finalError = fmt.Sprintf(
				"agy --print-timeout elapsed after %s waiting for the agent response; a long-running command likely outlived the print timeout",
				antigravityPrintTimeout(timeout),
			)
		} else if providerErr := antigravityProviderError(logPath); finalStatus == "completed" && providerErr != "" {
			// agy can also surface terminal model/provider failures only in the
			// per-run log while exiting 0 with empty stdout. Without promoting
			// that marker, the daemon records a failed turn as a blank success.
			finalStatus = "failed"
			finalError = fmt.Sprintf("agy provider error: %s", providerErr)
		}
		if finalError != "" {
			finalError = withAgentStderr(finalError, "agy", stderrBuf.Tail())
		}

		finalOutput := output.String()
		if streamResponse != "" {
			// result.response is agy's canonical complete reply. Deltas normally
			// reconstruct it exactly; if none arrived, emit the response now so
			// the task transcript and final result both receive the answer.
			if finalOutput == "" {
				trySend(msgCh, Message{Type: MessageText, Content: streamResponse})
			}
			finalOutput = streamResponse
		}
		if finalStatus == "completed" && strings.TrimSpace(finalOutput) == "" {
			// agy 1.0.14 print mode can finish a turn (tools executed, reply
			// produced) without writing anything to stdout, leaving a blank but
			// "completed" run none of the guards above catch (MUL-3726). Recover
			// the assistant text agy persisted to its conversation transcript so
			// the user sees the actual answer instead of an empty result. Also
			// emit it as a MessageText event so the task transcript catches up;
			// otherwise Result.Output becomes visible only in the synthesized
			// final comment while the execution transcript remains blank.
			if recovered := readAntigravityTranscriptOutput(logPath, sessionID); recovered != "" {
				finalOutput = recovered
				trySend(msgCh, Message{Type: MessageText, Content: recovered})
				b.cfg.Logger.Info("agy recovered empty stdout from transcript", "bytes", len(recovered))
			}
		}

		b.cfg.Logger.Info("agy finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())

		// agy result.usage is cumulative across a resumed conversation, while
		// completed step usage covers only this execution. Prefer the
		// deduplicated step sum so resumed tasks do not persist earlier turns
		// again. A terminal result remains the fallback for failures that emit
		// no completed step usage.
		usage, hasStepUsage := sumAntigravityStepUsage(streamStepUsage)
		if !hasStepUsage && streamResultUsage != nil {
			usage = streamResultUsage.tokenUsage()
		}
		usageByModel := map[string]TokenUsage{}
		if usage != (TokenUsage{}) {
			model := readAntigravitySelectedModel(logPath, streamModel, opts.Model)
			usageByModel[model] = usage
		}

		resCh <- Result{
			Status:     finalStatus,
			Output:     finalOutput,
			Error:      finalError,
			DurationMs: duration.Milliseconds(),
			SessionID:  sessionID,
			Usage:      usageByModel,
		}
	}()

	session := &Session{Messages: msgCh, Result: resCh}
	switch {
	case supplements != nil:
		session.Supplement = supplements.supplement
		session.SupplementReady = supplements.ready
	case supplementErr != nil:
		// The daemon already offered steering for this run and there is no way
		// to withdraw it, so settle each message as failed right away instead of
		// leaving it pending until the turn ends.
		session.Supplement = func(context.Context, string) error {
			return fmt.Errorf("agy hooks unavailable: %w", supplementErr)
		}
		session.SupplementReady = func() bool { return runCtx.Err() == nil }
	}
	return session, nil
}

// antigravityConversationIDRe matches the glog line printmode.go writes when
// the CLI dispatches the user's message — the only place in the log that
// reliably surfaces the conversation UUID for both fresh and resumed turns.
//
// Example: `I0528 13:36:23.318877 73304 printmode.go:130] Print mode:
// conversation=b8b263a4-4b2f-4339-acc9-78b248e2b606, sending message`
var antigravityConversationIDRe = regexp.MustCompile(
	`conversation=([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})`,
)

// antigravityPrintTimeoutRe matches the glog line agy's printmode.go writes when
// the print-mode wall-clock budget (--print-timeout) elapses before the agent
// produced a final response. agy then prints "Error: timed out waiting for
// response" to stdout and EXITS 0 — runCtx never trips and cmd.Wait returns nil
// — so without this signal the daemon would record the truncated turn as a
// successful "completed" (MUL-3570).
//
// Example: `E0623 17:17:59.017212 65926 printmode.go:289] Print mode: timed out
// after 100 polls (printed=3)`
var antigravityPrintTimeoutRe = regexp.MustCompile(`Print mode: timed out after \d+ polls`)

var antigravityProviderErrorRe = regexp.MustCompile(`agent executor error:\s*(.+)`)

// antigravityPrintTimedOut reports whether the per-run log shows agy hit its own
// print-mode timeout. Best-effort: returns false if the log is missing or the
// marker format changes upstream, in which case the run is classified by its
// exit status as before.
func antigravityPrintTimedOut(logPath string) bool {
	if logPath == "" {
		return false
	}
	data, err := os.ReadFile(logPath)
	if err != nil {
		return false
	}
	return antigravityPrintTimeoutRe.Match(data)
}

// antigravityProviderError extracts terminal upstream/model errors that agy logs
// but does not necessarily print to stdout or reflect in its exit code.
func antigravityProviderError(logPath string) string {
	if logPath == "" {
		return ""
	}
	data, err := os.ReadFile(logPath)
	if err != nil {
		return ""
	}
	matches := antigravityProviderErrorRe.FindAllSubmatch(data, -1)
	if len(matches) == 0 {
		return ""
	}
	return strings.TrimSpace(string(matches[len(matches)-1][1]))
}

// readAntigravityConversationID scans the per-run log file for the
// conversation UUID. Best-effort: returns "" if the log file is missing, the
// CLI exited before dispatching, or the format changes upstream.
func readAntigravityConversationID(logPath string) string {
	if logPath == "" {
		return ""
	}
	data, err := os.ReadFile(logPath)
	if err != nil {
		return ""
	}
	matches := antigravityConversationIDRe.FindAllSubmatch(data, -1)
	if len(matches) == 0 {
		return ""
	}
	// The CLI logs the conversation id repeatedly during a turn (one entry
	// per dispatched message, plus stream-update lines). Any non-empty UUID
	// in the file resolves to the same conversation, so the last match wins
	// — that's what `--conversation` should be pinned to next turn.
	return string(matches[len(matches)-1][1])
}

// antigravityAppDataDirRe matches the glog line agy writes at startup naming its
// CLI app data directory — the root under which per-conversation transcripts
// live. Reading the path from the log (which the daemon owns via --log-file)
// is more robust than guessing $HOME, and follows agy through a custom data dir.
//
// Example: `I0630 14:19:40.582492 88197 common.go:156] CLI app data directory:
// /Users/me/.gemini/antigravity-cli`
var antigravityAppDataDirRe = regexp.MustCompile(`CLI app data directory:\s*(.+)`)

// antigravityTranscriptRecord is the minimal shape of one line in agy's
// per-conversation transcript.jsonl. A turn opens with a USER_INPUT record; the
// assistant's replies are PLANNER_RESPONSE records with source=MODEL and (once
// settled) status=DONE. Content holds the text, or JSON null for a tool-only
// step — it is RawMessage so a null or non-string value is skipped rather than
// failing the whole line.
type antigravityTranscriptRecord struct {
	Type    string          `json:"type"`
	Source  string          `json:"source"`
	Status  string          `json:"status"`
	Content json.RawMessage `json:"content"`
}

// readAntigravityTranscriptOutput recovers the assistant's text from agy's
// per-conversation transcript when stdout carried nothing. agy 1.0.14's print
// mode can finish a turn (tools executed, final reply produced) while emitting
// zero bytes to stdout, leaving the daemon with a blank but "completed" run
// (MUL-3726, #4595). The full reply is still durably written to:
//
//	<appDataDir>/brain/<conversation-id>/.system_generated/logs/transcript.jsonl
//
// as PLANNER_RESPONSE / source=MODEL records.
//
// The transcript is per-conversation and ACCUMULATES across resumed turns
// (daemon reuses the conversation via --conversation / ResumeSessionID), so we
// must return only the CURRENT turn's reply — otherwise a later empty-stdout
// turn would re-emit prior turns' answers. Each turn opens with a USER_INPUT
// record, so we reset on every USER_INPUT and keep only the model text that
// follows the last one. We also require status=DONE to skip any future
// streaming/partial planner records. The remaining text is joined in order
// (intermediate narration + final reply), mirroring what stdout would have
// streamed for this turn. Best-effort: returns "" if the app data dir or
// conversation id is unknown, the transcript is missing, or it holds no model
// text for the current turn.
func readAntigravityTranscriptOutput(logPath, conversationID string) string {
	if logPath == "" || conversationID == "" {
		return ""
	}
	appDataDir := readAntigravityAppDataDir(logPath)
	if appDataDir == "" {
		return ""
	}
	transcriptPath := filepath.Join(
		appDataDir, "brain", conversationID, ".system_generated", "logs", "transcript.jsonl",
	)
	f, err := os.Open(transcriptPath)
	if err != nil {
		return ""
	}
	defer f.Close()

	var parts []string
	scanner := newAgentStreamScanner(f)
	for scanner.Scan() {
		line := scanner.Bytes()
		if len(line) == 0 {
			continue
		}
		var rec antigravityTranscriptRecord
		if err := json.Unmarshal(line, &rec); err != nil {
			continue
		}
		if rec.Type == "USER_INPUT" {
			// New turn boundary: drop anything collected for prior turns so a
			// resumed conversation yields only the current turn's reply.
			parts = parts[:0]
			continue
		}
		if rec.Type != "PLANNER_RESPONSE" || rec.Source != "MODEL" || rec.Status != "DONE" {
			continue
		}
		var text string
		// Content is JSON null for tool-only steps; unmarshal leaves text "".
		// A non-string value (object) errors and is skipped.
		if err := json.Unmarshal(rec.Content, &text); err != nil {
			continue
		}
		if strings.TrimSpace(text) != "" {
			parts = append(parts, text)
		}
	}
	return strings.Join(parts, "\n\n")
}

// antigravityTranscriptLineLimit bounds the transcript line the receipt scan
// decodes. Longer lines are skipped: the record of the largest guidance, even
// with every byte JSON-escaped, stays well below it.
const antigravityTranscriptLineLimit = 1 << 20

// antigravityTranscript scans the conversation transcript agy writes during
// the turn for the USER_INPUT records injected guidance became. Each scan
// reads only what was added since the previous one, through one bounded
// buffer, and decodes only lines that carry an in-flight marker. agy rewrites
// the file when it compacts the conversation, so a replaced or shrunken file
// is read again from the start, and so is the file at each new injected step
// (see confirmInjected), which catches a rewrite in place.
type antigravityTranscript struct {
	logPath string
	path    string
	file    os.FileInfo
	offset  int64
	reader  *bufio.Reader
}

func (r *antigravityTranscript) scan(conversationID string, markers []string, found func(marker string)) {
	if len(markers) == 0 {
		return
	}
	if r.path == "" {
		if conversationID == "" {
			return
		}
		// agy logs its data dir at startup, before any step; without it there
		// is no transcript to follow, so do not rescan the log on every event.
		appDataDir := readAntigravityAppDataDir(r.logPath)
		r.logPath = ""
		if appDataDir == "" {
			return
		}
		r.path = filepath.Join(appDataDir, "brain", conversationID, ".system_generated", "logs", "transcript.jsonl")
	}
	f, err := os.Open(r.path)
	if err != nil {
		return
	}
	defer f.Close()
	info, err := f.Stat()
	if err != nil {
		return
	}
	if r.file == nil || !os.SameFile(r.file, info) || info.Size() < r.offset {
		r.offset = 0
	}
	r.file = info
	if _, err := f.Seek(r.offset, io.SeekStart); err != nil {
		return
	}
	if r.reader == nil {
		r.reader = bufio.NewReaderSize(f, antigravityTranscriptLineLimit)
	} else {
		r.reader.Reset(f)
	}
	pos, long := r.offset, false
	for {
		line, err := r.reader.ReadSlice('\n')
		pos += int64(len(line))
		if errors.Is(err, bufio.ErrBufferFull) {
			long = true
			continue
		}
		if err != nil {
			// A partial last line is read again once agy completes it.
			return
		}
		if !long {
			for _, marker := range markers {
				if antigravityTranscriptCarries(line, marker) {
					found(marker)
				}
			}
		}
		long = false
		r.offset = pos
	}
}

func antigravityTranscriptCarries(line []byte, marker string) bool {
	if !bytes.Contains(line, []byte(marker)) {
		return false
	}
	var rec struct {
		Type    string `json:"type"`
		Content string `json:"content"`
	}
	return json.Unmarshal(line, &rec) == nil && rec.Type == "USER_INPUT" && strings.Contains(rec.Content, marker)
}

// readAntigravityAppDataDir extracts agy's CLI app data directory from the
// per-run log. Best-effort: returns "" if the log is missing or the marker
// format changes upstream.
func readAntigravityAppDataDir(logPath string) string {
	if logPath == "" {
		return ""
	}
	data, err := os.ReadFile(logPath)
	if err != nil {
		return ""
	}
	m := antigravityAppDataDirRe.FindSubmatch(data)
	if m == nil {
		return ""
	}
	return strings.TrimSpace(string(m[1]))
}

// antigravityBlockedArgs are flags hardcoded by the daemon that must not be
// overridden by user-configured custom_args. Overriding these would break
// non-interactive operation or the daemon's session-resume bookkeeping.
var antigravityBlockedArgs = map[string]blockedArgMode{
	"-p":                             blockedWithValue,
	"--print":                        blockedWithValue,
	"--prompt":                       blockedWithValue,
	"-i":                             blockedStandalone, // interactive mode requires a TTY and cannot run under the daemon
	"--prompt-interactive":           blockedStandalone,
	"-c":                             blockedStandalone, // resume via --conversation, not --continue
	"--continue":                     blockedStandalone,
	"--conversation":                 blockedWithValue, // managed via ExecOptions.ResumeSessionID
	"--model":                        blockedWithValue, // managed via ExecOptions.Model / agent.model
	"--output-format":                blockedWithValue, // stream-json is required for token accounting
	"--print-timeout":                blockedWithValue,
	"--dangerously-skip-permissions": blockedStandalone, // always-on in daemon mode
	"--log-file":                     blockedWithValue,  // daemon needs it for session capture
	"--settings":                     blockedWithValue,  // Claude Code-only flag; agy rejects it
}

// buildAntigravityArgs assembles the argv for a daemon-compatible one-shot agy
// invocation.
//
//	agy -p <prompt> --dangerously-skip-permissions [--model <catalog id>]
//	    --print-timeout <duration> --log-file <tmp>
//	    [--conversation <id>] [--add-dir <cwd>]
//
// agy 1.0.6 added a `--model` flag (MUL-3125), so opts.Model is now wired
// through when set. The value is the catalog identifier parseAntigravityModels
// read out of `agy models`: a slug (e.g. "gemini-3.6-flash-high") on agy
// 1.1.11+, or the verbatim single-column value (e.g. "Claude Opus 4.6
// (Thinking)") on older output. Either shape ships as one exec arg, so spaces
// and parens need no shell quoting. agy still exposes no --system-prompt;
// runtime instructions are delivered via AGENTS.md in the task workdir.
//
// agy silently no-ops on a model string it doesn't recognise (empty output,
// exit 0), so Execute validates opts.Model against the `agy models` catalog
// and rejects an unrecognised value up front (see antigravityModelError) —
// by the time we build argv the value is either empty or known-good. When
// opts.Model is empty we omit the flag and agy resolves its own default.
func buildAntigravityArgs(prompt, logPath string, timeout time.Duration, opts ExecOptions, logger *slog.Logger) []string {
	args := []string{
		"-p", prompt,
		"--dangerously-skip-permissions",
		"--output-format", "stream-json",
	}
	if opts.Model != "" {
		args = append(args, "--model", opts.Model)
	}
	// agy's --print-timeout has NO "disabled" value and DEFAULTS TO 5m when the
	// flag is omitted, so "no cap" cannot be expressed by dropping it — that
	// silently guillotines every turn at 5 minutes, killing any run whose build
	// or tests outlive the budget (MUL-3570). Always pass the flag: the
	// configured wall-clock cap when positive, else a value so large agy's own
	// timeout never fires before the daemon's idle/tool watchdogs reclaim a
	// genuinely stuck run (see antigravityPrintTimeout).
	args = append(args, "--print-timeout", antigravityFormatTimeout(antigravityPrintTimeout(timeout)))
	args = append(args, "--log-file", logPath)
	if opts.ResumeSessionID != "" {
		args = append(args, "--conversation", opts.ResumeSessionID)
	}
	if opts.Cwd != "" {
		args = append(args, "--add-dir", filepath.Clean(opts.Cwd))
	}
	args = append(args, filterCustomArgs(opts.ExtraArgs, antigravityBlockedArgs, logger)...)
	args = append(args, filterCustomArgs(opts.CustomArgs, antigravityBlockedArgs, logger)...)
	return args
}

// antigravityModelError returns an actionable error when `model` is non-empty
// and definitively absent from `available` (the `agy models` catalog); it
// returns nil otherwise. An empty `available` means discovery couldn't produce
// a catalog (agy missing, transient failure) — we fail OPEN there and let agy
// resolve the value, so a discovery hiccup never blocks a run. The match is
// exact because agy's --model wants the precise catalog identifier; a near-miss
// (extra space, dropped suffix) is correctly rejected since agy would silently
// no-op on it anyway.
func antigravityModelError(model string, available []Model) error {
	if model == "" || len(available) == 0 {
		return nil
	}
	ids := make([]string, 0, len(available))
	for _, m := range available {
		if m.ID == model {
			return nil
		}
		ids = append(ids, m.ID)
	}
	return fmt.Errorf(
		"antigravity model %q is not available from `agy models`; pick one of: %s",
		model, strings.Join(ids, ", "),
	)
}

// antigravityNoCapPrintTimeout is the --print-timeout value used when the daemon
// configures no wall-clock cap (opts.Timeout <= 0). agy's --print-timeout has no
// "disabled" sentinel and falls back to a 5-minute default when omitted, so "no
// cap" must instead be a value large enough that agy's own guillotine never
// fires before the daemon's inactivity watchdog reclaims a genuinely stuck run.
// 24h is effectively unbounded for any real turn while still being a finite
// duration agy can parse, and it stays above the watchdog budget even when an
// operator raises MULTICA_AGENT_IDLE_WATCHDOG well past its default.
const antigravityNoCapPrintTimeout = 24 * time.Hour

// antigravityPrintTimeout resolves the wall-clock budget handed to agy's
// --print-timeout: the daemon's configured cap when positive, else the no-cap
// sentinel above. It is the single source of truth shared by
// buildAntigravityArgs (which sets the flag) and Execute (which labels a
// print-mode timeout).
func antigravityPrintTimeout(timeout time.Duration) time.Duration {
	if timeout > 0 {
		return timeout
	}
	return antigravityNoCapPrintTimeout
}

// antigravityFormatTimeout renders a Go duration in the `<n>m<n>s` shape the
// agy CLI accepts (e.g. 20m0s). Sub-second timeouts round up to 1s so the CLI
// doesn't reject the flag.
func antigravityFormatTimeout(d time.Duration) string {
	if d < time.Second {
		d = time.Second
	}
	// time.Duration.String() already produces shapes like "20m0s" / "1h30m0s"
	// that agy parses via Go's stdlib flag.Duration on the receiving side.
	return d.String()
}