internal/webfetch/run.go

// Package webfetch implements the standalone ez-agent-webfetch command. It
// parses arguments, runs HTTP and WebSocket operations, and reports safe
// diagnostics. See docs/internal/webfetch.md for the contracts refactors must
// preserve.
package webfetch

import (
	"context"
	"errors"
	"fmt"
	"io"
	"strings"

	"git.cafe/ezterry/ez-agent/internal/webfetch/mcp/contract"
	"git.cafe/ezterry/ez-agent/pkg/buildinfo"
)

const commandName = "ez-agent-webfetch"

// OperationRunner is an injected scheme-specific implementation.
type OperationRunner func(context.Context, *Options, io.Reader, io.Writer) error

// Dependencies contains operation entry points and release identity used by Run.
type Dependencies struct {
	HTTP      OperationRunner
	WebSocket OperationRunner
	MCP       func(context.Context, contract.ControlRequest) (contract.ControlResponse, error)
	// MCPTokenPrompt must return a token without echoing it. Nil uses terminal stdin.
	MCPTokenPrompt func(io.Reader, io.Writer) ([]byte, error)
	Version        string
}

// DefaultDependencies wires the production HTTP, WebSocket and MCP runners.
func DefaultDependencies() Dependencies {
	return Dependencies{
		HTTP:      NewHTTPOperation(HTTPDependencies{}),
		WebSocket: NewWebSocketOperation(WebSocketDependencies{}),
		MCP:       executeMCP,
		Version:   buildinfo.Version,
	}
}

// Run validates arguments, handles help/version output, dispatches the selected
// operation, and maps its result to a process status without exiting.
func Run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer, deps Dependencies) int {
	options, err := ParseOptions(args)
	if err != nil {
		writeUsageError(stderr, err)
		return 2
	}

	if text, ok := informationText(options.Information); ok {
		if _, err := io.WriteString(stdout, text); err != nil {
			writeRuntimeError(stderr, fmt.Errorf("write help: %w", err))
			return 1
		}
		return 0
	}
	if options.Information == InformationVersion {
		version := deps.Version
		if version == "" {
			version = buildinfo.Version
		}
		if _, err := fmt.Fprintf(stdout, "%s %s\n", commandName, version); err != nil {
			writeRuntimeError(stderr, fmt.Errorf("write version: %w", err))
			return 1
		}
		return 0
	}
	if options.Operation == OperationMCP {
		return runMCP(ctx, &options, stdin, stdout, stderr, deps)
	}
	if err := loadHeaderFiles(&options); err != nil {
		writeUsageError(stderr, err)
		return 2
	}

	run := deps.HTTP
	kind := "HTTP"
	if options.Operation == OperationWebSocket {
		run = deps.WebSocket
		kind = "WebSocket"
	}
	if run == nil {
		writeRuntimeError(stderr, fmt.Errorf("%s operation runner is unavailable", kind))
		return 1
	}

	operationContext := ctx
	cancel := func() {}
	if options.Timeout > 0 {
		operationContext, cancel = context.WithTimeout(ctx, options.Timeout)
	}
	defer cancel()

	if err := run(operationContext, &options, stdin, stdout); err != nil {
		var usage *UsageError
		if errors.As(err, &usage) {
			message := "invalid operation usage"
			if public, ok := publicDiagnostic(err, &options); ok {
				message = public
			}
			writeUsageError(stderr, &UsageError{Message: message, Hint: usage.Hint})
			return 2
		}
		message := "operation failed (details unavailable)"
		if public, ok := publicDiagnostic(err, &options); ok {
			message = public
		}
		writeRuntimeError(stderr, fmt.Errorf("%s operation for %s failed: %s", kind, options.SafeURL(), message))
		return 1
	}
	return 0
}

func writeUsageError(w io.Writer, err error) {
	hint := InformationHelp
	var usage *UsageError
	if errors.As(err, &usage) {
		hint = usage.Hint
	}
	fmt.Fprintf(w, "%s: %v\nTry '%s %s' for usage.\n", commandName, err, commandName, informationOption(hint))
}

func writeRuntimeError(w io.Writer, err error) {
	fmt.Fprintf(w, "%s: %v\n", commandName, err)
}

// publicDiagnostic exposes only errors that explicitly promise safe text, then
// removes URL details that could contain credentials or query data.
func publicDiagnostic(err error, options *Options) (string, bool) {
	var public SafeDiagnosticError
	if !errors.As(err, &public) {
		return "", false
	}
	message := public.SafeDiagnostic()
	if message == "" {
		return "", false
	}
	return sanitizePublicDiagnosticURL(message, options), true
}

func sanitizePublicDiagnosticURL(message string, options *Options) string {
	if options == nil || options.URL == nil {
		return message
	}
	u := options.URL
	safe := SanitizeURL(u)
	for _, unsafe := range []string{u.String(), u.Redacted()} {
		if unsafe != "" && unsafe != safe {
			message = strings.ReplaceAll(message, unsafe, safe)
		}
	}
	if u.RawQuery != "" {
		requestURI := u.RequestURI()
		pathOnly := u.EscapedPath()
		if pathOnly == "" {
			pathOnly = "/"
		}
		message = strings.ReplaceAll(message, requestURI, pathOnly)
		message = strings.ReplaceAll(message, u.RawQuery, "[redacted query]")
	}
	return message
}