cmd/ez-agent-builtin/main.go

package main

import (
	"context"
	"fmt"
	"io"
	"log/slog"
	"os"
	"os/exec"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/attachments"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/buffer"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/command"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/completion"
	builtinconfig "git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/config"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/fileedit"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/history"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/modes"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/prompt"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/registry"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/rubystate"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/runcommand"
	builtinruntime "git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/runtime"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/skills"
	"git.cafe/ezterry/ez-agent/cmd/ez-agent-builtin/internal/builtin/storage"
	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	serviceconfig "git.cafe/ezterry/ez-agent/pkg/service/config"
)

type application struct {
	runCommand *runcommand.Service
	conn       *ezagentapi.Conn
	ready      chan struct{}
	readyErr   error
	readyOnce  sync.Once
	catalog    *registry.Catalog
	scheduler  *builtinruntime.Scheduler
	aborts     *builtinruntime.AbortRegistry
	delivery   *builtinruntime.Delivery
	shutdown   *builtinruntime.ShutdownCoordinator

	failure     chan struct{}
	failureOnce sync.Once
}

func (a *application) publishReady(err error) {
	a.readyOnce.Do(func() {
		a.readyErr = err
		close(a.ready)
	})
}
func (a *application) waitReady() error {
	<-a.ready
	return a.readyErr
}
func (a *application) connectionFailed() {
	a.failureOnce.Do(func() { close(a.failure) })
}

func (a *application) handlers() ezagentapi.Handlers {
	return ezagentapi.Handlers{
		OnToolCall: func(_ context.Context, call ezagentapi.ToolCall) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			callCtx := a.aborts.Register(call.ToolCallID)
			accepted := a.scheduler.EnqueueOrdinaryWithDiscard(func() {
				defer a.aborts.Done(call.ToolCallID)
				if !a.catalog.DispatchTool(callCtx, call) {
					a.sendUnknownTool(call)
				}
			}, func() { a.aborts.Done(call.ToolCallID) })
			if !accepted {
				a.aborts.Done(call.ToolCallID)
			}
			return nil
		},
		OnPluginCall: func(ctx context.Context, call ezagentapi.PluginCall) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			a.scheduler.EnqueueOrdinary(func() {
				if !a.catalog.DispatchPlugin(ctx, call) {
					_, _ = a.delivery.SendPlugin(ezagentapi.PluginResult{PluginCallID: call.PluginCallID, PendingTurns: call.PendingTurns, IsError: true})
				}
			})
			return nil
		},
		OnMacroCall: func(ctx context.Context, call ezagentapi.MacroCall) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			job := func() {
				if call.MacroName == "builtins.ruby_state" {
					slog.Info("handleMacroCall", "macro_name", call.MacroName, "leaf_id", call.LeafID)
				} else {
					slog.Info("handleMacroCall", "macro_name", call.MacroName, "leaf_id", call.LeafID, "param", call.ParamString)
				}
				if !a.catalog.DispatchMacro(ctx, call) {
					_, _ = a.delivery.SendMacro(ezagentapi.MacroResult{MacroCallID: call.MacroCallID, Result: "unknown macro: " + call.MacroName, IsError: true})
				}
			}
			if registry.IsInternalCompletionMacro(call.MacroName) {
				a.scheduler.EnqueueInternal(job)
			} else {
				a.scheduler.EnqueueOrdinary(job)
			}
			return nil
		},
		OnToolAbort: func(ctx context.Context, abort ezagentapi.ToolAbort) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			a.aborts.Abort(abort.ToolCallID)
			return a.conn.AckToolAbort(ctx, abort.ToolCallID)
		},
		OnBackgroundTaskKill: func(ctx context.Context, kill protocol.BackgroundTaskKill) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			a.runCommand.KillBackground(kill.TaskID, kill.Reason)
			return nil
		},
		OnToolInfoRequest: func(ctx context.Context, req ezagentapi.ToolInfoRequest) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			return a.conn.SendToolInfoResponse(ctx, req.RequestID, a.catalog.Tools(req.Names))
		},
		OnPluginInfoRequest: func(ctx context.Context, req ezagentapi.PluginInfoRequest) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			return a.conn.SendPluginInfoResponse(ctx, req.RequestID, a.catalog.Plugins(req.Names))
		},
		OnMacroInfoRequest: func(ctx context.Context, req ezagentapi.MacroInfoRequest) error {
			if err := a.waitReady(); err != nil {
				return err
			}
			return a.conn.SendMacroInfoResponse(ctx, req.RequestID, a.catalog.Macros(req.Names))
		},
		OnUnsupportedMessage: func(_ context.Context, msg ezagentapi.UnsupportedMessage) error {
			fmt.Fprintf(os.Stderr, "ez-agent-builtin: unsupported message type %q\n", msg.Type)
			return nil
		},
		OnError: func(_ context.Context, err error) {
			fmt.Fprintf(os.Stderr, "ez-agent-builtin: handler error: %v\n", err)
		},
	}
}

func (a *application) sendUnknownTool(call ezagentapi.ToolCall) {
	result, err := ezagentapi.NewToolResult(call.ToolCallID, "unknown tool: "+call.Name, ezagentapi.ToolResultOptions{Metadata: ezagentapi.ToolResultMetadata{IsError: true, FriendlyCall: call.Name}})
	if err == nil {
		_, _ = a.delivery.SendTool(result)
	}
}

func buildProductionCatalog(
	runCommandService *runcommand.Service, bufferService *buffer.Service, fileeditService *fileedit.Service,
	promptService *prompt.Service, skillsService *skills.Service, inlineFiles *attachments.InlineFilesPlugin,
	modesService *modes.Service, storageService *storage.Storage, historyService *history.Service,
	filesMacro *completion.FilesMacro, skillsMacro *completion.SkillsMacro,
	stateService *rubystate.Service,
	validators ...func(*registry.Catalog) error,
) (*registry.Catalog, error) {
	commands := command.Dispatcher{Reject: runCommandService.RejectCommand, Control: runCommandService.CommandTasks().Control, Complete: runCommandService.CompleteCommand}
	if _, err := exec.LookPath("bash"); err == nil {
		commands.Bash = runCommandService.Handle
	}
	if runCommandService.RubyAvailable() {
		commands.Ruby = runCommandService.HandleRuby
	}
	if promptService != nil {
		promptService.SetCommandCapabilities(prompt.CommandCapabilities{Ruby: commands.Ruby != nil, Shell: commands.Bash != nil})
	}
	catalog := registry.New([]protocol.ToolInfo{commands.Info(runCommandService.Info()), bufferService.Info(), fileeditService.Info()}, registry.Bindings{
		Tools:   map[string]registry.ToolHandler{"run-cmd": commands.Handle, "buffer": bufferService.Handle, "write_file": fileeditService.Handle},
		Plugins: map[string]registry.PluginHandler{"main_systemprompt": promptService.HandleSystemPrompt, "skill_mentions": skillsService.HandleMentions, "inline_files": inlineFiles.Handle, "mode_user_tag": modesService.HandleUserTag},
		Macros: map[string]registry.MacroHandler{
			"builtins.ruby_state":   stateService.Handle,
			"default.unique_buffer": storageService.HandleUniqueBuffer, "builtins.file_cache": storageService.HandleFileCache, "builtins.buffer_cache": storageService.HandleBufferCache,
			"builtin.auto_title": historyService.HandleAutoTitle, "builtin.auto_title_done": historyService.HandleAutoTitleDone, "builtin.system-agents-string": promptService.HandleSystemAgents,
			"builtin.minify": historyService.HandleMinify, "builtin.complete-files": filesMacro.Handle, "builtin.complete-skills": skillsMacro.Handle, "builtin.setmode": modesService.HandleSetMode,
			"builtin.compact": historyService.HandleCompact, "builtin.compact-auto": historyService.HandleCompactAuto, "builtin.compact-done": historyService.HandleCompactDone,
			"builtin.safer_bash_audit_done": runCommandService.HandleAuditDone,
		},
	})
	validate := (*registry.Catalog).Validate
	if len(validators) != 0 && validators[0] != nil {
		validate = validators[0]
	}
	return catalog, validate(catalog)
}

type fileCacheStatus interface {
	FileCache() (string, string)
}

func fileCacheStartupWarning(cache fileCacheStatus) string {
	if _, unavailable := cache.FileCache(); unavailable != "" {
		return "ez-agent-builtin: file cache unavailable: " + unavailable
	}
	return ""
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintf(os.Stderr, "ez-agent-builtin: %v\n", err)
		os.Exit(processStatus(err))
	}
}

func processStatus(err error) int {
	if err != nil {
		return 1
	}
	return 0
}

type runOptions struct {
	validateCatalog func(*registry.Catalog) error
	announce        func(context.Context, *ezagentapi.Conn, ezagentapi.Capabilities) error
	onComposed      func(*application)
	rubyPath        string // isolated test executable; production probes its sibling
}

type postStartOwners struct {
	app *application
}

// builtinMonitors composes shutdown ownership without mixing History or Bash
// semantic state into the generic runtime.
type builtinMonitors []builtinruntime.ShutdownMonitors

func (owners builtinMonitors) Stop() {
	for _, owner := range owners {
		owner.Stop()
	}
}

func (owners builtinMonitors) Wait() {
	for _, owner := range owners {
		owner.Wait()
	}
}

// fail releases every owner created after a successful connection startup.
// publishReady comes first so transport callbacks can return the same startup
// error without observing an absent or invalid catalog. Shutdown itself never
// waits, preserving terminal-send callback safety; this owner-level path then
// performs the blocking drain and connection collection.
func (o postStartOwners) fail(err error) error {
	o.app.publishReady(err)
	o.app.shutdown.Shutdown()
	o.app.shutdown.Wait()
	_ = o.app.conn.Wait()
	return err
}

func run() error {
	return runWithTransport(os.Stdin, os.Stdout, func() error { return os.Stdin.Close() })
}

func runWithTransport(input io.Reader, output io.Writer, closeInput func() error) error {
	return runWithOptions(input, output, closeInput, runOptions{})
}

func runWithOptions(input io.Reader, output io.Writer, closeInput func() error, options runOptions) error {
	signal.Ignore(syscall.SIGPIPE)
	loader := builtinconfig.NewLoader(serviceconfig.ConfigDir(), func(format string, args ...any) { fmt.Fprintf(os.Stderr, "ez-agent-builtin: "+format+"\n", args...) })
	// Retain builtin_plugin.yaml loading/normalization for compatibility.
	// max_parallel is a legacy no-op, not execution or Bash capacity.
	builtinConfig := loader.Load()
	loader.EnsureAuthTemplate()
	app := &application{ready: make(chan struct{}), scheduler: builtinruntime.NewScheduler(), aborts: builtinruntime.NewAbortRegistry(5 * time.Second), failure: make(chan struct{})}
	app.conn = ezagentapi.ConnectClient(input, output, closeInput, ezagentapi.ClientOptions{Name: "ez-agent-builtin", Handlers: app.handlers()})
	rpc := app.conn.RPC()
	app.delivery = builtinruntime.NewDelivery(app.conn, func(_, _ string, _ error) { app.connectionFailed() })
	progress := builtinruntime.NewProgress(app.conn, func(err error) {
		fmt.Fprintf(os.Stderr, "ez-agent-builtin: progress send failed: %v\n", err)
		app.connectionFailed()
	})
	if err := app.conn.Start(); err != nil {
		startupErr := fmt.Errorf("startup failed: %w", err)
		app.publishReady(startupErr)
		app.scheduler.Close()
		app.aborts.AbortAll()
		_ = app.conn.Close()
		app.scheduler.Wait()
		_ = app.conn.Wait()
		return startupErr
	}
	stateDir := ""
	if ack, ok := app.conn.HelloAck(); ok {
		stateDir = ack.StateDir
	}
	storageService := storage.NewFromStateDir(stateDir, app.delivery)
	stateManager := rubystate.NewManager(stateDir, rubystate.RegistrationClient{
		GetLeafConfig: rpc.GetLeafConfig,
		Attach: func(ctx context.Context, leaf, key string) (rubystate.Descriptor, error) {
			file, err := rpc.AttachLeafFile(ctx, leaf, key)
			if err != nil {
				return rubystate.Descriptor{}, err
			}
			return rubystate.Descriptor{FileID: file.FileID, Key: file.Key, Path: file.Path}, nil
		},
	})
	stateService := rubystate.NewService(stateManager, app.delivery)
	if warning := fileCacheStartupWarning(storageService); warning != "" {
		fmt.Fprintln(os.Stderr, warning)
	}
	modesService := modes.NewService(rpc, app.delivery)
	skillsService := skills.NewService(rpc, app.delivery)
	promptService := prompt.NewService(rpc, app.delivery, skillsService, storageService)
	inlineFiles := attachments.NewInlineFilesPlugin(app.delivery)
	filesMacro := completion.NewFilesMacro(rpc, app.delivery)
	skillsMacro := completion.NewSkillsMacro(skillsService, app.delivery)
	bufferService := buffer.NewService(rpc, app.delivery, storageService, skillsService, stateDir, prompt.EmbeddedAgentsMD())
	fileeditService := fileedit.NewService(app.delivery, modesService)
	historyService := history.NewService(rpc, app.delivery, progress, promptService, skillsService)
	runCommandService := runcommand.NewService(rpc, app.delivery, progress, modesService, stateDir)
	commandTasks := runCommandService.CommandTasks()
	if options.rubyPath != "" {
		runCommandService.ConfigureRuby(stateManager, options.rubyPath)
	} else {
		runCommandService.EnableRuby(stateManager, builtinConfig.RubyMaxWorkers)
	}
	app.runCommand = runCommandService
	runCommandService.OnBackgroundRPCFailure = func(error) { app.connectionFailed() }
	bufferService.BashState = runCommandService.StateBuffer
	bufferService.TaskSnapshot = commandTasks.SnapshotLeaf
	historyService.BackgroundReminder = runCommandService.ActiveBackgroundReminder
	app.shutdown = builtinruntime.NewShutdownCoordinator(app.scheduler, app.aborts, builtinMonitors{historyService, runCommandService, stateManager}, app.conn, runCommandService)
	owners := postStartOwners{app: app}
	if options.onComposed != nil {
		options.onComposed(app)
	}
	catalog, err := buildProductionCatalog(runCommandService, bufferService, fileeditService, promptService, skillsService, inlineFiles, modesService, storageService, historyService, filesMacro, skillsMacro, stateService, options.validateCatalog)
	if err != nil {
		return owners.fail(fmt.Errorf("registry invalid: %w", err))
	}
	app.catalog = catalog
	announce := func(ctx context.Context, conn *ezagentapi.Conn, capabilities ezagentapi.Capabilities) error {
		return conn.Announce(ctx, capabilities)
	}
	if options.announce != nil {
		announce = options.announce
	}
	if err := announce(context.Background(), app.conn, ezagentapi.Capabilities{}); err != nil {
		return owners.fail(fmt.Errorf("announce failed: %w", err))
	}
	app.publishReady(nil)

	connDone := make(chan error, 1)
	go func() { connDone <- app.conn.Wait() }()
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
	defer signal.Stop(sigCh)
	var connErr error
	connObserved := false
	select {
	case connErr = <-connDone:
		connObserved = true
	case <-app.failure:
	case <-sigCh:
	}
	app.shutdown.Shutdown()
	app.shutdown.Wait()
	if !connObserved {
		connErr = <-connDone
	}
	if connErr != nil {
		fmt.Fprintf(os.Stderr, "ez-agent-builtin: connection ended: %v\n", connErr)
	}
	return nil
}