cmd/ez-agent-builtin/internal/builtin/registry/registry.go

// Package registry is the builtin capability catalog and dispatch authority.
//
// It deliberately separates registration from transport: composition binds the
// final handlers before the connection starts, while this package owns the
// names, metadata lookup order, and completion-lane classification.
package registry

import (
	"context"
	"fmt"

	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
)

type ToolHandler func(context.Context, ezagentapi.ToolCall)
type PluginHandler func(context.Context, ezagentapi.PluginCall)
type MacroHandler func(context.Context, ezagentapi.MacroCall)

type Bindings struct {
	Tools   map[string]ToolHandler
	Plugins map[string]PluginHandler
	Macros  map[string]MacroHandler
}

type Catalog struct {
	tools    map[string]protocol.ToolInfo
	plugins  map[string]protocol.PluginInfo
	macros   map[string]protocol.MacroInfo
	bindings Bindings
}

// New constructs the complete fixed builtin catalog. Bindings are copied so a
// caller cannot mutate routing after startup; callers must bind all final
// callbacks before Conn.Start.
func New(tools []protocol.ToolInfo, bindings Bindings) *Catalog {
	c := &Catalog{
		tools: map[string]protocol.ToolInfo{},
		plugins: map[string]protocol.PluginInfo{
			"main_systemprompt": {Name: "main_systemprompt", Description: "Inject system prompt from leaf config", Priority: 0},
			"skill_mentions":    {Name: "skill_mentions", Description: "Attach skills explicitly mentioned in user messages", Priority: 5},
			"inline_files":      {Name: "inline_files", Description: "Attach files referenced in user messages", Priority: 10},
			"mode_user_tag":     {Name: "mode_user_tag", Description: "Prefix user messages with the active mode tag", Priority: 15},
		},
		macros:   macroCatalog(),
		bindings: Bindings{Tools: copyTools(bindings.Tools), Plugins: copyPlugins(bindings.Plugins), Macros: copyMacros(bindings.Macros)},
	}
	for _, info := range tools {
		c.tools[info.Name] = info
	}
	// Failure callbacks share the owning worker dispatcher, but keep distinct
	// names so no trigger-type field or live-state inference is needed.
	for name, owner := range workerFailureOwners {
		if _, explicit := c.bindings.Macros[name]; !explicit && c.bindings.Macros[owner] != nil {
			c.bindings.Macros[name] = c.bindings.Macros[owner]
		}
	}
	return c
}

func (c *Catalog) Validate() error {
	if c == nil {
		return fmt.Errorf("nil registry")
	}
	checks := []struct {
		name     string
		metadata int
		handlers map[string]bool
	}{
		{"tool", len(c.tools), nonNilTools(c.bindings.Tools)},
		{"plugin", len(c.plugins), nonNilPlugins(c.bindings.Plugins)},
		{"macro", len(c.macros), nonNilMacros(c.bindings.Macros)},
	}
	for _, check := range checks {
		if len(check.handlers) != check.metadata {
			return fmt.Errorf("%s bindings incomplete: got %d, want %d", check.name, len(check.handlers), check.metadata)
		}
	}
	for name := range c.bindings.Tools {
		if _, ok := c.tools[name]; !ok {
			return fmt.Errorf("unknown tool binding: %s", name)
		}
	}
	for name := range c.bindings.Plugins {
		if _, ok := c.plugins[name]; !ok {
			return fmt.Errorf("unknown plugin binding: %s", name)
		}
	}
	for name := range c.bindings.Macros {
		if _, ok := c.macros[name]; !ok {
			return fmt.Errorf("unknown macro binding: %s", name)
		}
	}
	return nil
}
func nonNilTools(in map[string]ToolHandler) map[string]bool {
	out := map[string]bool{}
	for n, h := range in {
		if h != nil {
			out[n] = true
		}
	}
	return out
}
func nonNilPlugins(in map[string]PluginHandler) map[string]bool {
	out := map[string]bool{}
	for n, h := range in {
		if h != nil {
			out[n] = true
		}
	}
	return out
}
func nonNilMacros(in map[string]MacroHandler) map[string]bool {
	out := map[string]bool{}
	for n, h := range in {
		if h != nil {
			out[n] = true
		}
	}
	return out
}

func copyTools(in map[string]ToolHandler) map[string]ToolHandler {
	out := make(map[string]ToolHandler, len(in))
	for k, v := range in {
		out[k] = v
	}
	return out
}
func copyPlugins(in map[string]PluginHandler) map[string]PluginHandler {
	out := make(map[string]PluginHandler, len(in))
	for k, v := range in {
		out[k] = v
	}
	return out
}
func copyMacros(in map[string]MacroHandler) map[string]MacroHandler {
	out := make(map[string]MacroHandler, len(in))
	for k, v := range in {
		out[k] = v
	}
	return out
}

func (c *Catalog) Tools(names []string) []protocol.ToolInfo {
	out := make([]protocol.ToolInfo, 0, len(names))
	for _, name := range names {
		if entry, ok := c.tools[name]; ok {
			out = append(out, entry)
		}
	}
	return out
}

func (c *Catalog) Plugins(names []string) []protocol.PluginInfo {
	out := make([]protocol.PluginInfo, 0, len(names))
	for _, name := range names {
		if entry, ok := c.plugins[name]; ok {
			out = append(out, entry)
		}
	}
	return out
}

// Macros returns copies of trigger slices, keeping the registry's metadata
// authoritative even if a transport caller modifies its response value.
func (c *Catalog) Macros(names []string) []protocol.MacroInfo {
	out := make([]protocol.MacroInfo, 0, len(names))
	for _, name := range names {
		if entry, ok := c.macros[name]; ok {
			entry.Triggers = append([]string(nil), entry.Triggers...)
			out = append(out, entry)
		}
	}
	return out
}

func (c *Catalog) DispatchTool(ctx context.Context, call ezagentapi.ToolCall) bool {
	h, ok := c.bindings.Tools[call.Name]
	if ok {
		h(ctx, call)
	}
	return ok
}
func (c *Catalog) DispatchPlugin(ctx context.Context, call ezagentapi.PluginCall) bool {
	h, ok := c.bindings.Plugins[call.Name]
	if ok {
		h(ctx, call)
	}
	return ok
}
func (c *Catalog) DispatchMacro(ctx context.Context, call ezagentapi.MacroCall) bool {
	h, ok := c.bindings.Macros[call.MacroName]
	if ok {
		h(ctx, call)
	}
	return ok
}

func IsInternalCompletionMacro(name string) bool {
	if _, ok := workerFailureOwners[name]; ok {
		return true
	}
	return name == "builtin.safer_bash_audit_done" || name == "builtin.compact-done" || name == "builtin.auto_title_done"
}

var workerFailureOwners = map[string]string{
	"builtin.compact-background":          "builtin.compact-done",
	"builtin.compact-error":               "builtin.compact-done",
	"builtin.auto_title_background":       "builtin.auto_title_done",
	"builtin.auto_title_error":            "builtin.auto_title_done",
	"builtin.safer_bash_audit_background": "builtin.safer_bash_audit_done",
	"builtin.safer_bash_audit_error":      "builtin.safer_bash_audit_done",
}

func macroCatalog() map[string]protocol.MacroInfo {
	entries := []protocol.MacroInfo{
		{Name: "builtins.ruby_state", Internal: true, Description: "Private per-leaf Ruby state and notifications", Timeout: "35s", MaxTimeout: "40s"},
		{Name: "default.unique_buffer", Description: "Atomically reserve a unique builtin-owned temporary buffer file", Timeout: "5s", MaxTimeout: "15s"},
		{Name: "builtins.file_cache", Description: "Remove expired general cache files", Triggers: []string{"cache_cleanup"}, Timeout: "30s", MaxTimeout: "60s"},
		{Name: "builtins.buffer_cache", Description: "Remove expired dynamic buffer cache files", Triggers: []string{"cache_cleanup", "on_user"}, Timeout: "30s", MaxTimeout: "60s"},
		{Name: "builtin.auto_title", Description: "Auto-generate a session title from conversation", Triggers: []string{"on_idle", "on_user"}, Timeout: "30s", MaxTimeout: "60s"},
		{Name: "builtin.auto_title_done", Internal: true, Description: "Complete an internal auto-title temporary leaf", Triggers: []string{"on_idle"}, Timeout: "30s", MaxTimeout: "60s"},
		{Name: "builtin.system-agents-string", Description: "Generate the system AGENTS.md string for a leaf's root", Timeout: "5s", MaxTimeout: "15s"},
		{Name: "builtin.minify", Description: "Minify conversation history under a virtual root", Triggers: []string{"on_user"}, Timeout: "30s", MaxTimeout: "60s"},
		{Name: "builtin.complete-files", Description: "Suggest file references for @word-style tokens in prompt input", Triggers: []string{"completions"}, Timeout: "5s", MaxTimeout: "15s"},
		{Name: "builtin.complete-skills", Description: "Suggest skill mentions for slash- and dollar-prefixed prompt tokens", Triggers: []string{"completions"}, Timeout: "5s", MaxTimeout: "15s"},
		{Name: "builtin.setmode", Description: "Set or clear the active mode for this leaf", Triggers: []string{"on_user"}, Timeout: "5s", MaxTimeout: "15s"},
		{Name: "builtin.compact", Description: "Manually compact older conversation context, optionally retaining from a turn ID", Triggers: []string{"on_user"}, Timeout: "30s", MaxTimeout: "5m"},
		{Name: "builtin.compact-auto", Description: "Automatically compact context at the configured threshold", Triggers: []string{"on_preplugin"}, Timeout: "30s", MaxTimeout: "5m"},
		{Name: "builtin.compact-done", Internal: true, Description: "Finalize a builtin-owned temporary compaction leaf", Triggers: []string{"on_idle"}, Timeout: "30s", MaxTimeout: "60s"},
		{Name: "builtin.safer_bash_audit_done", Internal: true, Description: "Complete an internal safer_bash command audit", Triggers: []string{"on_idle"}, Timeout: "150s", MaxTimeout: "300s"},
	}
	out := make(map[string]protocol.MacroInfo, len(entries))
	for _, entry := range entries {
		out[entry.Name] = entry
	}
	for name, owner := range workerFailureOwners {
		entry := out[owner]
		entry.Name = name
		entry.Description = "Reject a failed or background one-shot worker"
		entry.Triggers = []string{"on_error"}
		if name == "builtin.compact-background" || name == "builtin.auto_title_background" || name == "builtin.safer_bash_audit_background" {
			entry.Triggers = []string{"on_background"}
		}
		out[name] = entry
	}
	return out
}