|
| 1 | +package builtin |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/docker/cagent/pkg/tools" |
| 11 | +) |
| 12 | + |
| 13 | +// LSPMultiplexer combines multiple LSP backends into a single toolset. |
| 14 | +// It presents one set of lsp_* tools and routes each call to the appropriate |
| 15 | +// backend based on the file extension in the tool arguments. |
| 16 | +type LSPMultiplexer struct { |
| 17 | + backends []LSPBackend |
| 18 | +} |
| 19 | + |
| 20 | +// LSPBackend pairs a raw LSPTool (used for file-type routing) with an |
| 21 | +// optionally-wrapped ToolSet (used for tool enumeration, so that per-toolset |
| 22 | +// config like tool filters, instructions, or toon wrappers are respected). |
| 23 | +type LSPBackend struct { |
| 24 | + LSP *LSPTool |
| 25 | + Toolset tools.ToolSet |
| 26 | +} |
| 27 | + |
| 28 | +// lspRouteTarget pairs a backend with the tool handler it produced for a given tool name. |
| 29 | +type lspRouteTarget struct { |
| 30 | + lsp *LSPTool |
| 31 | + handler tools.ToolHandler |
| 32 | +} |
| 33 | + |
| 34 | +// Verify interface compliance. |
| 35 | +var ( |
| 36 | + _ tools.ToolSet = (*LSPMultiplexer)(nil) |
| 37 | + _ tools.Startable = (*LSPMultiplexer)(nil) |
| 38 | + _ tools.Instructable = (*LSPMultiplexer)(nil) |
| 39 | +) |
| 40 | + |
| 41 | +// NewLSPMultiplexer creates a multiplexer that routes LSP tool calls |
| 42 | +// to the appropriate backend based on file type. |
| 43 | +func NewLSPMultiplexer(backends []LSPBackend) *LSPMultiplexer { |
| 44 | + return &LSPMultiplexer{backends: append([]LSPBackend{}, backends...)} |
| 45 | +} |
| 46 | + |
| 47 | +func (m *LSPMultiplexer) Start(ctx context.Context) error { |
| 48 | + var started int |
| 49 | + for _, b := range m.backends { |
| 50 | + if err := b.LSP.Start(ctx); err != nil { |
| 51 | + // Clean up previously started backends to avoid resource leaks. |
| 52 | + for _, s := range m.backends[:started] { |
| 53 | + _ = s.LSP.Stop(ctx) |
| 54 | + } |
| 55 | + return fmt.Errorf("starting LSP backend %q: %w", b.LSP.handler.command, err) |
| 56 | + } |
| 57 | + started++ |
| 58 | + } |
| 59 | + return nil |
| 60 | +} |
| 61 | + |
| 62 | +func (m *LSPMultiplexer) Stop(ctx context.Context) error { |
| 63 | + var errs []error |
| 64 | + for _, b := range m.backends { |
| 65 | + if err := b.LSP.Stop(ctx); err != nil { |
| 66 | + errs = append(errs, fmt.Errorf("stopping LSP backend %q: %w", b.LSP.handler.command, err)) |
| 67 | + } |
| 68 | + } |
| 69 | + return errors.Join(errs...) |
| 70 | +} |
| 71 | + |
| 72 | +func (m *LSPMultiplexer) Instructions() string { |
| 73 | + // Combine instructions from all backends, deduplicating identical ones. |
| 74 | + // Typically they share the same base LSP instructions, but individual |
| 75 | + // toolsets may override them via the Instruction config field. |
| 76 | + var parts []string |
| 77 | + seen := make(map[string]bool) |
| 78 | + for _, b := range m.backends { |
| 79 | + instr := tools.GetInstructions(b.Toolset) |
| 80 | + if instr != "" && !seen[instr] { |
| 81 | + seen[instr] = true |
| 82 | + parts = append(parts, instr) |
| 83 | + } |
| 84 | + } |
| 85 | + return strings.Join(parts, "\n\n") |
| 86 | +} |
| 87 | + |
| 88 | +func (m *LSPMultiplexer) Tools(ctx context.Context) ([]tools.Tool, error) { |
| 89 | + // Collect each backend's tools keyed by name. We build the union of all |
| 90 | + // tool names (not just the first backend's) so that per-backend tool |
| 91 | + // filters don't accidentally hide tools that other backends expose. |
| 92 | + handlersByName := make(map[string][]lspRouteTarget) |
| 93 | + seenTools := make(map[string]tools.Tool) // first definition wins (for schema/description) |
| 94 | + var toolOrder []string // preserve insertion order |
| 95 | + for _, b := range m.backends { |
| 96 | + bTools, err := b.Toolset.Tools(ctx) |
| 97 | + if err != nil { |
| 98 | + return nil, fmt.Errorf("getting tools from LSP backend %q: %w", b.LSP.handler.command, err) |
| 99 | + } |
| 100 | + for _, t := range bTools { |
| 101 | + handlersByName[t.Name] = append(handlersByName[t.Name], lspRouteTarget{b.LSP, t.Handler}) |
| 102 | + if _, exists := seenTools[t.Name]; !exists { |
| 103 | + seenTools[t.Name] = t |
| 104 | + toolOrder = append(toolOrder, t.Name) |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + result := make([]tools.Tool, 0, len(toolOrder)) |
| 110 | + for _, name := range toolOrder { |
| 111 | + t := seenTools[name] |
| 112 | + handlers := handlersByName[name] |
| 113 | + if name == ToolNameLSPWorkspace || name == ToolNameLSPWorkspaceSymbols { |
| 114 | + t.Handler = broadcastLSP(handlers) |
| 115 | + } else { |
| 116 | + t.Handler = routeByFile(handlers) |
| 117 | + } |
| 118 | + result = append(result, t) |
| 119 | + } |
| 120 | + return result, nil |
| 121 | +} |
| 122 | + |
| 123 | +// routeByFile returns a handler that extracts the "file" field from the JSON |
| 124 | +// arguments and dispatches to the backend whose file-type filter matches. |
| 125 | +func routeByFile(handlers []lspRouteTarget) tools.ToolHandler { |
| 126 | + return func(ctx context.Context, tc tools.ToolCall) (*tools.ToolCallResult, error) { |
| 127 | + var args struct { |
| 128 | + File string `json:"file"` |
| 129 | + } |
| 130 | + if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil { |
| 131 | + return tools.ResultError(fmt.Sprintf("failed to parse file argument: %s", err)), nil |
| 132 | + } |
| 133 | + if args.File == "" { |
| 134 | + return tools.ResultError("file argument is required"), nil |
| 135 | + } |
| 136 | + for _, h := range handlers { |
| 137 | + if h.lsp.HandlesFile(args.File) { |
| 138 | + return h.handler(ctx, tc) |
| 139 | + } |
| 140 | + } |
| 141 | + return tools.ResultError(fmt.Sprintf("no LSP server configured for file: %s", args.File)), nil |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +// broadcastLSP returns a handler that calls every backend best-effort and |
| 146 | +// merges the outputs. Individual backend failures are collected rather than |
| 147 | +// aborting the entire operation. |
| 148 | +func broadcastLSP(handlers []lspRouteTarget) tools.ToolHandler { |
| 149 | + return func(ctx context.Context, tc tools.ToolCall) (*tools.ToolCallResult, error) { |
| 150 | + var sections []string |
| 151 | + var errs []error |
| 152 | + for _, h := range handlers { |
| 153 | + result, err := h.handler(ctx, tc) |
| 154 | + if err != nil { |
| 155 | + errs = append(errs, fmt.Errorf("backend %s: %w", h.lsp.handler.command, err)) |
| 156 | + continue |
| 157 | + } |
| 158 | + if result.IsError { |
| 159 | + sections = append(sections, fmt.Sprintf("[LSP %s] Error: %s", h.lsp.handler.command, result.Output)) |
| 160 | + } else if result.Output != "" { |
| 161 | + sections = append(sections, result.Output) |
| 162 | + } |
| 163 | + } |
| 164 | + if len(sections) == 0 && len(errs) > 0 { |
| 165 | + return nil, errors.Join(errs...) |
| 166 | + } |
| 167 | + if len(sections) == 0 { |
| 168 | + return tools.ResultSuccess("No results"), nil |
| 169 | + } |
| 170 | + return tools.ResultSuccess(strings.Join(sections, "\n---\n")), nil |
| 171 | + } |
| 172 | +} |
0 commit comments